blob: c387c3d03a1e6e93444b0486a9a39943fa23b6f6 [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
Caroline Tice5ddbe212011-05-06 21:37:15 +0000159 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
160 if (cmd_obj_sp)
Jason Molenda47eb00e2011-10-22 00:47:41 +0000161 {
162 AddAlias ("stepi", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000163 AddAlias ("si", cmd_obj_sp);
Jason Molenda47eb00e2011-10-22 00:47:41 +0000164 }
165
166 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
167 if (cmd_obj_sp)
168 {
169 AddAlias ("nexti", cmd_obj_sp);
170 AddAlias ("ni", cmd_obj_sp);
171 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000172
173 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
174 if (cmd_obj_sp)
175 {
176 AddAlias ("s", cmd_obj_sp);
177 AddAlias ("step", cmd_obj_sp);
178 }
179
180 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
181 if (cmd_obj_sp)
182 {
183 AddAlias ("n", cmd_obj_sp);
184 AddAlias ("next", cmd_obj_sp);
185 }
186
187 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
188 if (cmd_obj_sp)
189 {
Caroline Tice5ddbe212011-05-06 21:37:15 +0000190 AddAlias ("finish", cmd_obj_sp);
191 }
192
Jim Ingham59355252011-12-02 01:12:59 +0000193 cmd_obj_sp = GetCommandSPExact ("frame select", false);
194 if (cmd_obj_sp)
195 {
196 AddAlias ("f", cmd_obj_sp);
197 }
198
Caroline Tice5ddbe212011-05-06 21:37:15 +0000199 cmd_obj_sp = GetCommandSPExact ("source list", false);
200 if (cmd_obj_sp)
201 {
202 AddAlias ("l", cmd_obj_sp);
203 AddAlias ("list", cmd_obj_sp);
204 }
205
206 cmd_obj_sp = GetCommandSPExact ("memory read", false);
207 if (cmd_obj_sp)
208 AddAlias ("x", cmd_obj_sp);
209
210 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
211 if (cmd_obj_sp)
212 AddAlias ("up", cmd_obj_sp);
213
214 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
215 if (cmd_obj_sp)
216 AddAlias ("down", cmd_obj_sp);
217
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000218 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000219 if (cmd_obj_sp)
220 AddAlias ("display", cmd_obj_sp);
Jim Ingham9d1acc12011-10-24 18:37:00 +0000221
222 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
223 if (cmd_obj_sp)
224 AddAlias ("dis", cmd_obj_sp);
225
226 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
227 if (cmd_obj_sp)
228 AddAlias ("di", cmd_obj_sp);
229
230
Jason Molenda730cae02011-10-22 01:30:52 +0000231
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000232 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000233 if (cmd_obj_sp)
234 AddAlias ("undisplay", cmd_obj_sp);
235
Caroline Tice5ddbe212011-05-06 21:37:15 +0000236 cmd_obj_sp = GetCommandSPExact ("target create", false);
237 if (cmd_obj_sp)
238 AddAlias ("file", cmd_obj_sp);
239
240 cmd_obj_sp = GetCommandSPExact ("target modules", false);
241 if (cmd_obj_sp)
242 AddAlias ("image", cmd_obj_sp);
243
244
245 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000246
Caroline Tice5ddbe212011-05-06 21:37:15 +0000247 cmd_obj_sp = GetCommandSPExact ("expression", false);
248 if (cmd_obj_sp)
249 {
250 AddAlias ("expr", cmd_obj_sp);
251
252 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
253 AddAlias ("p", cmd_obj_sp);
254 AddAlias ("print", cmd_obj_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000255 AddAlias ("call", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000256 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
257 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000258 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000259
260 alias_arguments_vector_sp.reset (new OptionArgVector);
261 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
262 AddAlias ("po", cmd_obj_sp);
263 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
264 }
265
Sean Callananee301fa2012-06-01 23:29:32 +0000266 cmd_obj_sp = GetCommandSPExact ("process kill", false);
267 if (cmd_obj_sp)
Greg Claytonf2e53a52012-09-27 00:02:27 +0000268 {
Sean Callananee301fa2012-06-01 23:29:32 +0000269 AddAlias ("kill", cmd_obj_sp);
Greg Claytonf2e53a52012-09-27 00:02:27 +0000270 AddAlias ("k", cmd_obj_sp);
271 }
Sean Callananee301fa2012-06-01 23:29:32 +0000272
Caroline Tice5ddbe212011-05-06 21:37:15 +0000273 cmd_obj_sp = GetCommandSPExact ("process launch", false);
274 if (cmd_obj_sp)
275 {
276 alias_arguments_vector_sp.reset (new OptionArgVector);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000277#if defined (__arm__)
278 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
279#else
Greg Clayton86c50d72012-05-18 00:04:38 +0000280 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000281#endif
Caroline Tice5ddbe212011-05-06 21:37:15 +0000282 AddAlias ("r", cmd_obj_sp);
283 AddAlias ("run", cmd_obj_sp);
284 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
285 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
286 }
Greg Claytonc84623f2012-03-29 21:47:51 +0000287
288 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
289 if (cmd_obj_sp)
290 {
291 AddAlias ("add-dsym", cmd_obj_sp);
292 }
Sean Callanan7b71b172012-05-21 18:25:19 +0000293
294 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
295 if (cmd_obj_sp)
296 {
297 alias_arguments_vector_sp.reset (new OptionArgVector);
298 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
299 AddAlias ("rb", cmd_obj_sp);
300 AddOrReplaceAliasOptions("rb", alias_arguments_vector_sp);
301 }
Chris Lattner24943d22010-06-08 16:52:24 +0000302}
303
Chris Lattner24943d22010-06-08 16:52:24 +0000304const char *
305CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
306{
307 // This function has not yet been implemented.
308
309 // Look for any embedded script command
310 // If found,
311 // get interpreter object from the command dictionary,
312 // call execute_one_command on it,
313 // get the results as a string,
314 // substitute that string for current stuff.
315
316 return arg;
317}
318
319
320void
321CommandInterpreter::LoadCommandDictionary ()
322{
323 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
324
325 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
326 //
327 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
328 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
329 // the cross-referencing stuff) are created!!!
330 //
331 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
332
333
334 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
335 // are created. This is so that when another command is created that needs to go into a crossref object,
336 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
337 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
338
Chris Lattner24943d22010-06-08 16:52:24 +0000339 // Non-CommandObjectCrossref commands can now be created.
340
Caroline Tice5bc8c972010-09-20 20:44:43 +0000341 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000342
Greg Clayton238c0a12010-09-18 01:14:36 +0000343 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000344 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000345 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000346 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000347 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
348 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000349// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000350 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000351 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000352 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000353 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
354 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000355 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata6d101882012-09-28 23:57:51 +0000356 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000357 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000358 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000359 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000360 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000361 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000362 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000363 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
364 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000365 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000366 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000367 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000368
369 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000370 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000371 "_regexp-break",
Johnny Chen58edac32012-08-23 00:32:22 +0000372 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
373 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000374 if (break_regex_cmd_ap.get())
375 {
376 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
Johnny Chen58edac32012-08-23 00:32:22 +0000377 break_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000378 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
379 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000380 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000381 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000382 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000383 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
384 {
385 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
386 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
387 }
388 }
Jim Inghame56493f2011-03-22 02:29:32 +0000389
390 std::auto_ptr<CommandObjectRegexCommand>
Johnny Chena47e44b2012-08-24 18:15:45 +0000391 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
392 "_regexp-attach",
393 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.",
394 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]", 2));
395 if (attach_regex_cmd_ap.get())
396 {
397 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "process attach --pid %1") &&
398 attach_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "process attach --name '%1'"))
399 {
400 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
401 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
402 }
403 }
404
405 std::auto_ptr<CommandObjectRegexCommand>
Jim Inghame56493f2011-03-22 02:29:32 +0000406 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000407 "_regexp-down",
408 "Go down \"n\" frames in the stack (1 frame by default).",
409 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000410 if (down_regex_cmd_ap.get())
411 {
412 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
413 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
414 {
415 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
416 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
417 }
418 }
419
420 std::auto_ptr<CommandObjectRegexCommand>
421 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000422 "_regexp-up",
423 "Go up \"n\" frames in the stack (1 frame by default).",
424 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000425 if (up_regex_cmd_ap.get())
426 {
427 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
428 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
429 {
430 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
431 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
432 }
433 }
Jason Molenda730cae02011-10-22 01:30:52 +0000434
435 std::auto_ptr<CommandObjectRegexCommand>
436 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000437 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000438 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000439 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000440 if (display_regex_cmd_ap.get())
441 {
442 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
443 {
444 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
445 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
446 }
447 }
448
449 std::auto_ptr<CommandObjectRegexCommand>
450 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000451 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000452 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000453 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000454 if (undisplay_regex_cmd_ap.get())
455 {
456 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
457 {
458 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
459 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
460 }
461 }
462
Greg Claytonc3750432012-09-26 22:26:47 +0000463 std::auto_ptr<CommandObjectRegexCommand>
464 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
465 "gdb-remote",
466 "Connect to a remote GDB server.",
467 "gdb-remote [<host>:<port>]\ngdb-remote [<port>]", 2));
468 if (connect_gdb_remote_cmd_ap.get())
469 {
470 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
471 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
472 {
473 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
474 m_command_dict[command_sp->GetCommandName ()] = command_sp;
475 }
476 }
477
478 std::auto_ptr<CommandObjectRegexCommand>
479 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
480 "kdp-remote",
481 "Connect to a remote KDP server.",
482 "kdp-remote [<host>]\nkdp-remote [<host>:<port>]", 2));
483 if (connect_kdp_remote_cmd_ap.get())
484 {
485 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molenda73feea42012-09-27 02:47:55 +0000486 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Claytonc3750432012-09-26 22:26:47 +0000487 {
488 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
489 m_command_dict[command_sp->GetCommandName ()] = command_sp;
490 }
491 }
492
Jason Molenda1a48cb72012-10-05 05:29:32 +0000493 std::auto_ptr<CommandObjectRegexCommand>
494 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
495 "bt",
496 "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.",
497 "bt [<digit>|all]", 2));
498 if (bt_regex_cmd_ap.get())
499 {
500 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
501 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
502 // so now "bt 3" is the preferred form, in line with gdb.
503 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
504 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
505 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
506 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
507 {
508 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
509 m_command_dict[command_sp->GetCommandName ()] = command_sp;
510 }
511 }
512
Chris Lattner24943d22010-06-08 16:52:24 +0000513}
514
515int
516CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
517 StringList &matches)
518{
519 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
520
521 if (include_aliases)
522 {
523 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
524 }
525
526 return matches.GetSize();
527}
528
529CommandObjectSP
530CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
531{
532 CommandObject::CommandMap::iterator pos;
533 CommandObjectSP ret_val;
534
535 std::string cmd(cmd_cstr);
536
537 if (HasCommands())
538 {
539 pos = m_command_dict.find(cmd);
540 if (pos != m_command_dict.end())
541 ret_val = pos->second;
542 }
543
544 if (include_aliases && HasAliases())
545 {
546 pos = m_alias_dict.find(cmd);
547 if (pos != m_alias_dict.end())
548 ret_val = pos->second;
549 }
550
551 if (HasUserCommands())
552 {
553 pos = m_user_dict.find(cmd);
554 if (pos != m_user_dict.end())
555 ret_val = pos->second;
556 }
557
Sean Callananb386d822012-08-09 00:50:26 +0000558 if (!exact && !ret_val)
Chris Lattner24943d22010-06-08 16:52:24 +0000559 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000560 // We will only get into here if we didn't find any exact matches.
561
562 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
563
Chris Lattner24943d22010-06-08 16:52:24 +0000564 StringList local_matches;
565 if (matches == NULL)
566 matches = &local_matches;
567
Jim Inghamd40f8a62010-07-06 22:46:59 +0000568 unsigned int num_cmd_matches = 0;
569 unsigned int num_alias_matches = 0;
570 unsigned int num_user_matches = 0;
571
572 // Look through the command dictionaries one by one, and if we get only one match from any of
573 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
574
Chris Lattner24943d22010-06-08 16:52:24 +0000575 if (HasCommands())
576 {
577 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
578 }
579
580 if (num_cmd_matches == 1)
581 {
582 cmd.assign(matches->GetStringAtIndex(0));
583 pos = m_command_dict.find(cmd);
584 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000585 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000586 }
587
Jim Ingham9a574172010-06-24 20:28:42 +0000588 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000589 {
590 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
591
592 }
593
Jim Inghamd40f8a62010-07-06 22:46:59 +0000594 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000595 {
596 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
597 pos = m_alias_dict.find(cmd);
598 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000599 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000600 }
601
Jim Ingham9a574172010-06-24 20:28:42 +0000602 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000603 {
604 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
605 }
606
Jim Inghamd40f8a62010-07-06 22:46:59 +0000607 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000608 {
609 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
610
611 pos = m_user_dict.find (cmd);
612 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000613 user_match_sp = pos->second;
614 }
615
616 // If we got exactly one match, return that, otherwise return the match list.
617
618 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
619 {
620 if (num_cmd_matches)
621 return real_match_sp;
622 else if (num_alias_matches)
623 return alias_match_sp;
624 else
625 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000626 }
627 }
Sean Callananb386d822012-08-09 00:50:26 +0000628 else if (matches && ret_val)
Jim Inghamd40f8a62010-07-06 22:46:59 +0000629 {
630 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000631 }
632
633
634 return ret_val;
635}
636
Greg Claytond12aeab2011-04-20 16:37:46 +0000637bool
638CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
639{
640 if (name && name[0])
641 {
642 std::string name_sstr(name);
Enrico Granata2f1014b2012-10-01 17:19:37 +0000643 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
644 if (found && !can_replace)
645 return false;
646 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata6d101882012-09-28 23:57:51 +0000647 return false;
Greg Claytond12aeab2011-04-20 16:37:46 +0000648 m_command_dict[name_sstr] = cmd_sp;
649 return true;
650 }
651 return false;
652}
653
Enrico Granata6b1596d2011-08-16 23:24:13 +0000654bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000655CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000656 const lldb::CommandObjectSP &cmd_sp,
657 bool can_replace)
658{
Enrico Granata6010ace2011-11-07 22:57:04 +0000659 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000660 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000661
662 const char* name_cstr = name.c_str();
663
664 // do not allow replacement of internal commands
665 if (CommandExists(name_cstr))
Enrico Granata6d101882012-09-28 23:57:51 +0000666 {
667 if (can_replace == false)
668 return false;
669 if (m_command_dict[name]->IsRemovable() == false)
670 return false;
671 }
Enrico Granata6010ace2011-11-07 22:57:04 +0000672
Enrico Granata6d101882012-09-28 23:57:51 +0000673 if (UserCommandExists(name_cstr))
674 {
675 if (can_replace == false)
676 return false;
677 if (m_user_dict[name]->IsRemovable() == false)
678 return false;
679 }
680
Enrico Granata6010ace2011-11-07 22:57:04 +0000681 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000682 return true;
683 }
684 return false;
685}
Greg Claytond12aeab2011-04-20 16:37:46 +0000686
Jim Inghamd40f8a62010-07-06 22:46:59 +0000687CommandObjectSP
688CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000689{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000690 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
691 CommandObjectSP ret_val; // Possibly empty return value.
692
693 if (cmd_cstr == NULL)
694 return ret_val;
695
696 if (cmd_words.GetArgumentCount() == 1)
697 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
698 else
699 {
700 // We have a multi-word command (seemingly), so we need to do more work.
701 // First, get the cmd_obj_sp for the first word in the command.
702 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
703 if (cmd_obj_sp.get() != NULL)
704 {
705 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
706 // command name), and find the appropriate sub-command SP for each command word....
707 size_t end = cmd_words.GetArgumentCount();
708 for (size_t j= 1; j < end; ++j)
709 {
710 if (cmd_obj_sp->IsMultiwordObject())
711 {
712 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
713 (cmd_words.GetArgumentAtIndex (j));
714 if (cmd_obj_sp.get() == NULL)
715 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
716 return ret_val;
717 }
718 else
719 // We have more words in the command name, but we don't have a multiword object. Fail and return
720 // empty 'ret_val'.
721 return ret_val;
722 }
723 // We successfully looped through all the command words and got valid command objects for them. Assign the
724 // last object retrieved to 'ret_val'.
725 ret_val = cmd_obj_sp;
726 }
727 }
728 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000729}
730
731CommandObject *
732CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
733{
734 return GetCommandSPExact (cmd_cstr, include_aliases).get();
735}
736
737CommandObject *
738CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
739{
740 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
741
742 // If we didn't find an exact match to the command string in the commands, look in
743 // the aliases.
744
745 if (command_obj == NULL)
746 {
747 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
748 }
749
750 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
751 // in both the commands and the aliases.
752
753 if (command_obj == NULL)
754 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
755
756 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000757}
758
759bool
760CommandInterpreter::CommandExists (const char *cmd)
761{
762 return m_command_dict.find(cmd) != m_command_dict.end();
763}
764
765bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000766CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
767 const char *options_args,
768 OptionArgVectorSP &option_arg_vector_sp)
769{
770 bool success = true;
771 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
772
773 if (!options_args || (strlen (options_args) < 1))
774 return true;
775
776 std::string options_string (options_args);
777 Args args (options_args);
778 CommandReturnObject result;
779 // Check to see if the command being aliased can take any command options.
780 Options *options = cmd_obj_sp->GetOptions ();
781 if (options)
782 {
783 // See if any options were specified as part of the alias; if so, handle them appropriately.
784 options->NotifyOptionParsingStarting ();
785 args.Unshift ("dummy_arg");
786 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
787 args.Shift ();
788 if (result.Succeeded())
789 options->VerifyPartialOptions (result);
790 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
791 {
792 result.AppendError ("Unable to create requested alias.\n");
793 return false;
794 }
795 }
796
Greg Clayton7268b4c2011-10-28 21:38:01 +0000797 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000798 {
799 if (cmd_obj_sp->WantsRawCommandString ())
800 option_arg_vector->push_back (OptionArgPair ("<argument>",
801 OptionArgValue (-1,
802 options_string)));
803 else
804 {
805 int argc = args.GetArgumentCount();
806 for (size_t i = 0; i < argc; ++i)
807 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
808 option_arg_vector->push_back
809 (OptionArgPair ("<argument>",
810 OptionArgValue (-1,
811 std::string (args.GetArgumentAtIndex (i)))));
812 }
813 }
814
815 return success;
816}
817
818bool
Chris Lattner24943d22010-06-08 16:52:24 +0000819CommandInterpreter::AliasExists (const char *cmd)
820{
821 return m_alias_dict.find(cmd) != m_alias_dict.end();
822}
823
824bool
825CommandInterpreter::UserCommandExists (const char *cmd)
826{
827 return m_user_dict.find(cmd) != m_user_dict.end();
828}
829
830void
831CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
832{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000833 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000834 m_alias_dict[alias_name] = command_obj_sp;
835}
836
837bool
838CommandInterpreter::RemoveAlias (const char *alias_name)
839{
840 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
841 if (pos != m_alias_dict.end())
842 {
843 m_alias_dict.erase(pos);
844 return true;
845 }
846 return false;
847}
848bool
849CommandInterpreter::RemoveUser (const char *alias_name)
850{
851 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
852 if (pos != m_user_dict.end())
853 {
854 m_user_dict.erase(pos);
855 return true;
856 }
857 return false;
858}
859
Chris Lattner24943d22010-06-08 16:52:24 +0000860void
861CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
862{
863 help_string.Printf ("'%s", command_name);
864 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
865
Sean Callananb386d822012-08-09 00:50:26 +0000866 if (option_arg_vector_sp)
Chris Lattner24943d22010-06-08 16:52:24 +0000867 {
868 OptionArgVector *options = option_arg_vector_sp.get();
869 for (int i = 0; i < options->size(); ++i)
870 {
871 OptionArgPair cur_option = (*options)[i];
872 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000873 OptionArgValue value_pair = cur_option.second;
874 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000875 if (opt.compare("<argument>") == 0)
876 {
877 help_string.Printf (" %s", value.c_str());
878 }
879 else
880 {
881 help_string.Printf (" %s", opt.c_str());
882 if ((value.compare ("<no-argument>") != 0)
883 && (value.compare ("<need-argument") != 0))
884 {
885 help_string.Printf (" %s", value.c_str());
886 }
887 }
888 }
889 }
890
891 help_string.Printf ("'");
892}
893
Greg Clayton65124ea2010-08-26 22:05:43 +0000894size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000895CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
896{
897 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000898 CommandObject::CommandMap::const_iterator end = dict.end();
899 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000900
Greg Clayton65124ea2010-08-26 22:05:43 +0000901 for (pos = dict.begin(); pos != end; ++pos)
902 {
903 size_t len = pos->first.size();
904 if (max_len < len)
905 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000906 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000907 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000908}
909
910void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000911CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000912 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000913{
914 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000915 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000916
917 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000918 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000919
920 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
921 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000922
Enrico Granata6b1596d2011-08-16 23:24:13 +0000923 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
924 {
925 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
926 max_len);
927 }
928 result.AppendMessage("");
929
930 }
931
Greg Clayton7268b4c2011-10-28 21:38:01 +0000932 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000933 {
Jim Inghame3663e82010-10-22 18:47:16 +0000934 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000935 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000936 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000937 max_len = FindLongestCommandWord (m_alias_dict);
938
Chris Lattner24943d22010-06-08 16:52:24 +0000939 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
940 {
941 StreamString sstr;
942 StreamString translation_and_help;
943 std::string entry_name = pos->first;
944 std::string second_entry = pos->second.get()->GetCommandName();
945 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
946
947 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
948 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
949 translation_and_help.GetData(), max_len);
950 }
951 result.AppendMessage("");
952 }
953
Greg Clayton7268b4c2011-10-28 21:38:01 +0000954 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000955 {
956 result.AppendMessage ("The following is a list of your current user-defined commands:");
957 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000958 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000959 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
960 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000961 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
962 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000963 }
964 result.AppendMessage("");
965 }
966
967 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
968}
969
Caroline Ticee0da7a52010-12-09 22:52:49 +0000970CommandObject *
971CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000972{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000973 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
974 // eventually be invoked by the given command line.
975
976 CommandObject *cmd_obj = NULL;
977 std::string white_space (" \t\v");
978 size_t start = command_string.find_first_not_of (white_space);
979 size_t end = 0;
980 bool done = false;
981 while (!done)
982 {
983 if (start != std::string::npos)
984 {
985 // Get the next word from command_string.
986 end = command_string.find_first_of (white_space, start);
987 if (end == std::string::npos)
988 end = command_string.size();
989 std::string cmd_word = command_string.substr (start, end - start);
990
991 if (cmd_obj == NULL)
992 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
993 // command or alias.
994 cmd_obj = GetCommandObject (cmd_word.c_str());
995 else if (cmd_obj->IsMultiwordObject ())
996 {
997 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
998 CommandObject *sub_cmd_obj =
999 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
1000 if (sub_cmd_obj)
1001 cmd_obj = sub_cmd_obj;
1002 else // cmd_word was not a valid sub-command word, so we are donee
1003 done = true;
1004 }
1005 else
1006 // We have a cmd_obj and it is not a multi-word object, so we are done.
1007 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001008
Caroline Ticee0da7a52010-12-09 22:52:49 +00001009 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1010 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1011 // next word.
1012
1013 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1014 done = true;
1015 else
1016 start = command_string.find_first_not_of (white_space, end);
1017 }
1018 else
1019 // Unable to find any more words.
1020 done = true;
1021 }
1022
1023 if (end == command_string.size())
1024 command_string.clear();
1025 else
1026 command_string = command_string.substr(end);
1027
1028 return cmd_obj;
1029}
1030
Greg Clayton9d855c62011-10-25 00:36:27 +00001031static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +00001032static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +00001033static void
1034StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001035{
Greg Clayton9d855c62011-10-25 00:36:27 +00001036 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001037 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001038 size_t pos = s.find_first_not_of (k_white_space);
1039 if (pos == std::string::npos)
1040 s.clear();
1041 else if (pos == 0)
1042 return;
1043 s.erase (0, pos);
1044 }
1045}
1046
Greg Clayton3840cd72011-11-09 23:25:03 +00001047static size_t
1048FindArgumentTerminator (const std::string &s)
1049{
Greg Clayton3840cd72011-11-09 23:25:03 +00001050 const size_t s_len = s.size();
1051 size_t offset = 0;
1052 while (offset < s_len)
1053 {
1054 size_t pos = s.find ("--", offset);
1055 if (pos == std::string::npos)
1056 break;
1057 if (pos > 0)
1058 {
1059 if (isspace(s[pos-1]))
1060 {
1061 // Check if the string ends "\s--" (where \s is a space character)
1062 // or if we have "\s--\s".
1063 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1064 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001065 return pos;
1066 }
1067 }
1068 }
1069 offset = pos + 2;
1070 }
Greg Clayton3840cd72011-11-09 23:25:03 +00001071 return std::string::npos;
1072}
1073
Greg Clayton9d855c62011-10-25 00:36:27 +00001074static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +00001075ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +00001076{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001077 command.clear();
1078 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +00001079 StripLeadingSpaces (command_string);
1080
1081 bool result = false;
1082 quote_char = '\0';
1083
1084 if (!command_string.empty())
1085 {
1086 const char first_char = command_string[0];
1087 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +00001088 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001089 quote_char = first_char;
1090 const size_t end_quote_pos = command_string.find (quote_char, 1);
1091 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001092 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001093 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001094 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001095 }
1096 else
1097 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001098 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +00001099 if (end_quote_pos + 1 < command_string.size())
1100 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1101 else
1102 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001103 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001104 }
1105 else
1106 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001107 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1108 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001109 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001110 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001111 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +00001112 }
1113 else
1114 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001115 command.assign (command_string, 0, first_space_pos);
1116 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +00001117 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001118 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001119 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001120 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001121
1122
1123 if (!command.empty())
1124 {
1125 // actual commands can't start with '-' or '_'
1126 if (command[0] != '-' && command[0] != '_')
1127 {
1128 size_t pos = command.find_first_not_of(k_valid_command_chars);
1129 if (pos > 0 && pos != std::string::npos)
1130 {
1131 suffix.assign (command.begin() + pos, command.end());
1132 command.erase (pos);
1133 }
1134 }
1135 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001136
1137 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001138}
1139
Greg Clayton7268b4c2011-10-28 21:38:01 +00001140CommandObject *
1141CommandInterpreter::BuildAliasResult (const char *alias_name,
1142 std::string &raw_input_string,
1143 std::string &alias_result,
1144 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001145{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001146 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001147 Args cmd_args (raw_input_string.c_str());
1148 alias_cmd_obj = GetCommandObject (alias_name);
1149 StreamString result_str;
1150
1151 if (alias_cmd_obj)
1152 {
1153 std::string alias_name_str = alias_name;
1154 if ((cmd_args.GetArgumentCount() == 0)
1155 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1156 cmd_args.Unshift (alias_name);
1157
1158 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1159 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1160
1161 if (option_arg_vector_sp.get())
1162 {
1163 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1164
1165 for (int i = 0; i < option_arg_vector->size(); ++i)
1166 {
1167 OptionArgPair option_pair = (*option_arg_vector)[i];
1168 OptionArgValue value_pair = option_pair.second;
1169 int value_type = value_pair.first;
1170 std::string option = option_pair.first;
1171 std::string value = value_pair.second;
1172 if (option.compare ("<argument>") == 0)
1173 result_str.Printf (" %s", value.c_str());
1174 else
1175 {
1176 result_str.Printf (" %s", option.c_str());
1177 if (value_type != optional_argument)
1178 result_str.Printf (" ");
1179 if (value.compare ("<no_argument>") != 0)
1180 {
1181 int index = GetOptionArgumentPosition (value.c_str());
1182 if (index == 0)
1183 result_str.Printf ("%s", value.c_str());
1184 else if (index >= cmd_args.GetArgumentCount())
1185 {
1186
1187 result.AppendErrorWithFormat
1188 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1189 index);
1190 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001191 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001192 }
1193 else
1194 {
1195 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1196 if (strpos != std::string::npos)
1197 raw_input_string = raw_input_string.erase (strpos,
1198 strlen (cmd_args.GetArgumentAtIndex (index)));
1199 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1200 }
1201 }
1202 }
1203 }
1204 }
1205
1206 alias_result = result_str.GetData();
1207 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001208 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001209}
1210
Greg Claytonf5c0c722011-10-14 07:41:33 +00001211Error
1212CommandInterpreter::PreprocessCommand (std::string &command)
1213{
1214 // The command preprocessor needs to do things to the command
1215 // line before any parsing of arguments or anything else is done.
1216 // The only current stuff that gets proprocessed is anyting enclosed
1217 // in backtick ('`') characters is evaluated as an expression and
1218 // the result of the expression must be a scalar that can be substituted
1219 // into the command. An example would be:
1220 // (lldb) memory read `$rsp + 20`
1221 Error error; // Error for any expressions that might not evaluate
1222 size_t start_backtick;
1223 size_t pos = 0;
1224 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1225 {
1226 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1227 {
1228 // The backtick was preceeded by a '\' character, remove the slash
1229 // and don't treat the backtick as the start of an expression
1230 command.erase(start_backtick-1, 1);
1231 // No need to add one to start_backtick since we just deleted a char
1232 pos = start_backtick;
1233 }
1234 else
1235 {
1236 const size_t expr_content_start = start_backtick + 1;
1237 const size_t end_backtick = command.find ('`', expr_content_start);
1238 if (end_backtick == std::string::npos)
1239 return error;
1240 else if (end_backtick == expr_content_start)
1241 {
1242 // Empty expression (two backticks in a row)
1243 command.erase (start_backtick, 2);
1244 }
1245 else
1246 {
1247 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1248
Greg Claytonbcaf99a2012-07-12 20:32:19 +00001249 ExecutionContext exe_ctx(GetExecutionContext());
1250 Target *target = exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001251 // Get a dummy target to allow for calculator mode while processing backticks.
1252 // This also helps break the infinite loop caused when target is null.
1253 if (!target)
1254 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001255 if (target)
1256 {
Greg Claytonf5c0c722011-10-14 07:41:33 +00001257 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad27026e2012-09-05 20:41:26 +00001258
1259 Target::EvaluateExpressionOptions options;
1260 options.SetCoerceToId(false)
1261 .SetUnwindOnError(true)
1262 .SetKeepInMemory(false)
1263 .SetSingleThreadTimeoutUsec(0);
1264
Greg Claytonf5c0c722011-10-14 07:41:33 +00001265 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad27026e2012-09-05 20:41:26 +00001266 exe_ctx.GetFramePtr(),
Enrico Granata6cca9692012-07-16 23:10:35 +00001267 expr_result_valobj_sp,
Enrico Granatad27026e2012-09-05 20:41:26 +00001268 options);
1269
Greg Claytonf5c0c722011-10-14 07:41:33 +00001270 if (expr_result == eExecutionCompleted)
1271 {
1272 Scalar scalar;
1273 if (expr_result_valobj_sp->ResolveValue (scalar))
1274 {
1275 command.erase (start_backtick, end_backtick - start_backtick + 1);
1276 StreamString value_strm;
1277 const bool show_type = false;
1278 scalar.GetValue (&value_strm, show_type);
1279 size_t value_string_size = value_strm.GetSize();
1280 if (value_string_size)
1281 {
1282 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1283 pos = start_backtick + value_string_size;
1284 continue;
1285 }
1286 else
1287 {
1288 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1289 }
1290 }
1291 else
1292 {
1293 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1294 }
1295 }
1296 else
1297 {
1298 if (expr_result_valobj_sp)
1299 error = expr_result_valobj_sp->GetError();
1300 if (error.Success())
1301 {
1302
1303 switch (expr_result)
1304 {
1305 case eExecutionSetupError:
1306 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1307 break;
1308 case eExecutionCompleted:
1309 break;
1310 case eExecutionDiscarded:
1311 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1312 break;
1313 case eExecutionInterrupted:
1314 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1315 break;
1316 case eExecutionTimedOut:
1317 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1318 break;
1319 }
1320 }
1321 }
1322 }
1323 }
1324 if (error.Fail())
1325 break;
1326 }
1327 }
1328 return error;
1329}
1330
1331
Caroline Ticee0da7a52010-12-09 22:52:49 +00001332bool
1333CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata01bc2d42012-05-31 01:09:06 +00001334 LazyBool lazy_add_to_history,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001335 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001336 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001337 bool repeat_on_empty_command,
1338 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001339
Caroline Ticee0da7a52010-12-09 22:52:49 +00001340{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001341
Caroline Ticee0da7a52010-12-09 22:52:49 +00001342 bool done = false;
1343 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001344 bool wants_raw_input = false;
1345 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001346 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001347
1348 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001349 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1350
1351 // Make a scoped cleanup object that will clear the crash description string
1352 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001353 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001354
Caroline Ticee0da7a52010-12-09 22:52:49 +00001355 if (log)
1356 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001357
Jim Inghamabab14b2010-11-04 23:08:45 +00001358 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1359
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001360 if (!no_context_switching)
1361 UpdateExecutionContext (override_context);
Enrico Granata01bc2d42012-05-31 01:09:06 +00001362
1363 // <rdar://problem/11328896>
1364 bool add_to_history;
1365 if (lazy_add_to_history == eLazyBoolCalculate)
1366 add_to_history = (m_command_source_depth == 0);
1367 else
1368 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1369
Jim Ingham949d5ac2011-02-18 00:54:25 +00001370 bool empty_command = false;
1371 bool comment_command = false;
1372 if (command_string.empty())
1373 empty_command = true;
1374 else
Chris Lattner24943d22010-06-08 16:52:24 +00001375 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001376 const char *k_space_characters = "\t\n\v\f\r ";
1377
1378 size_t non_space = command_string.find_first_not_of (k_space_characters);
1379 // Check for empty line or comment line (lines whose first
1380 // non-space character is the comment character for this interpreter)
1381 if (non_space == std::string::npos)
1382 empty_command = true;
1383 else if (command_string[non_space] == m_comment_char)
1384 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001385 else if (command_string[non_space] == m_repeat_char)
1386 {
1387 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1388 if (history_string == NULL)
1389 {
1390 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1391 result.SetStatus(eReturnStatusFailed);
1392 return false;
1393 }
1394 add_to_history = false;
1395 command_string = history_string;
1396 original_command_string = history_string;
1397 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001398 }
1399
1400 if (empty_command)
1401 {
1402 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001403 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001404 if (m_command_history.empty())
1405 {
1406 result.AppendError ("empty command");
1407 result.SetStatus(eReturnStatusFailed);
1408 return false;
1409 }
1410 else
1411 {
1412 command_line = m_repeat_command.c_str();
1413 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001414 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001415 if (m_repeat_command.empty())
1416 {
1417 result.AppendErrorWithFormat("No auto repeat.\n");
1418 result.SetStatus (eReturnStatusFailed);
1419 return false;
1420 }
1421 }
1422 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001423 }
1424 else
1425 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001426 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1427 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001428 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001429 }
1430 else if (comment_command)
1431 {
1432 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1433 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001434 }
Caroline Tice649116c2011-05-11 16:07:06 +00001435
Greg Claytonf5c0c722011-10-14 07:41:33 +00001436
1437 Error error (PreprocessCommand (command_string));
1438
1439 if (error.Fail())
1440 {
1441 result.AppendError (error.AsCString());
1442 result.SetStatus(eReturnStatusFailed);
1443 return false;
1444 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001445 // Phase 1.
1446
1447 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1448 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1449 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1450 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1451 // 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 +00001452 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001453 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001454
Caroline Ticee0da7a52010-12-09 22:52:49 +00001455 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001456 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001457 std::string next_word;
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001458 StringList matches;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001459 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001460 {
Caroline Tice649116c2011-05-11 16:07:06 +00001461 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001462 std::string suffix;
1463 ExtractCommand (command_string, next_word, suffix, quote_char);
1464 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001465 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001466 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001467 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001468 std::string alias_result;
1469 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1470 revised_command_line.Printf ("%s", alias_result.c_str());
1471 if (cmd_obj)
1472 {
1473 wants_raw_input = cmd_obj->WantsRawCommandString ();
1474 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1475 }
Chris Lattner24943d22010-06-08 16:52:24 +00001476 }
1477 else
1478 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001479 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001480 if (cmd_obj)
1481 {
1482 actual_cmd_name_len += next_word.length();
1483 revised_command_line.Printf ("%s", next_word.c_str());
1484 wants_raw_input = cmd_obj->WantsRawCommandString ();
1485 }
Caroline Tice649116c2011-05-11 16:07:06 +00001486 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001487 {
1488 revised_command_line.Printf ("%s", next_word.c_str());
1489 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001490 }
1491 }
1492 else
1493 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001494 if (cmd_obj->IsMultiwordObject ())
1495 {
1496 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1497 if (sub_cmd_obj)
1498 {
1499 actual_cmd_name_len += next_word.length() + 1;
1500 revised_command_line.Printf (" %s", next_word.c_str());
1501 cmd_obj = sub_cmd_obj;
1502 wants_raw_input = cmd_obj->WantsRawCommandString ();
1503 }
1504 else
1505 {
1506 if (quote_char)
1507 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1508 else
1509 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1510 done = true;
1511 }
1512 }
Caroline Tice649116c2011-05-11 16:07:06 +00001513 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001514 {
1515 if (quote_char)
1516 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1517 else
1518 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1519 done = true;
1520 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001521 }
1522
1523 if (cmd_obj == NULL)
1524 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001525 uint32_t num_matches = matches.GetSize();
1526 if (matches.GetSize() > 1) {
1527 std::string error_msg;
1528 error_msg.assign ("Ambiguous command '");
1529 error_msg.append(next_word.c_str());
1530 error_msg.append ("'.");
1531
1532 error_msg.append (" Possible matches:");
1533
1534 for (uint32_t i = 0; i < num_matches; ++i) {
1535 error_msg.append ("\n\t");
1536 error_msg.append (matches.GetStringAtIndex(i));
1537 }
1538 error_msg.append ("\n");
1539 result.AppendRawError (error_msg.c_str(), error_msg.size());
1540 } else {
1541 // We didn't have only one match, otherwise we wouldn't get here.
1542 assert(num_matches == 0);
1543 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1544 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001545 result.SetStatus (eReturnStatusFailed);
1546 return false;
1547 }
1548
Greg Clayton7268b4c2011-10-28 21:38:01 +00001549 if (cmd_obj->IsMultiwordObject ())
1550 {
1551 if (!suffix.empty())
1552 {
1553
1554 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1555 next_word.c_str(),
1556 suffix.c_str());
1557 result.SetStatus (eReturnStatusFailed);
1558 return false;
1559 }
1560 }
1561 else
1562 {
1563 // If we found a normal command, we are done
1564 done = true;
1565 if (!suffix.empty())
1566 {
1567 switch (suffix[0])
1568 {
1569 case '/':
1570 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001571 {
1572 Options *command_options = cmd_obj->GetOptions();
1573 if (command_options && command_options->SupportsLongOption("gdb-format"))
1574 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001575 std::string gdb_format_option ("--gdb-format=");
1576 gdb_format_option += (suffix.c_str() + 1);
1577
1578 bool inserted = false;
1579 std::string &cmd = revised_command_line.GetString();
1580 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1581 if (arg_terminator_idx != std::string::npos)
1582 {
1583 // Insert the gdb format option before the "--" that terminates options
1584 gdb_format_option.append(1,' ');
1585 cmd.insert(arg_terminator_idx, gdb_format_option);
1586 inserted = true;
1587 }
1588
1589 if (!inserted)
1590 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1591
1592 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1593 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001594 }
1595 else
1596 {
1597 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1598 cmd_obj->GetCommandName());
1599 result.SetStatus (eReturnStatusFailed);
1600 return false;
1601 }
1602 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001603 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001604
1605 default:
1606 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1607 suffix.c_str());
1608 result.SetStatus (eReturnStatusFailed);
1609 return false;
1610
Greg Clayton7268b4c2011-10-28 21:38:01 +00001611 }
1612 }
1613 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001614 if (command_string.length() == 0)
1615 done = true;
1616
Chris Lattner24943d22010-06-08 16:52:24 +00001617 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001618
Greg Clayton7268b4c2011-10-28 21:38:01 +00001619 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001620 revised_command_line.Printf (" %s", command_string.c_str());
1621
1622 // End of Phase 1.
1623 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1624 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1625 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1626 // wants_raw_input specifies whether the Execute method expects raw input or not.
1627
1628
1629 if (log)
1630 {
1631 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1632 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1633 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1634 }
1635
1636 // Phase 2.
1637 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1638 // CommandObject, with the appropriate arguments.
1639
1640 if (cmd_obj != NULL)
1641 {
1642 if (add_to_history)
1643 {
1644 Args command_args (revised_command_line.GetData());
1645 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1646 if (repeat_command != NULL)
1647 m_repeat_command.assign(repeat_command);
1648 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001649 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001650
Jim Ingham6247dbe2011-07-12 03:12:18 +00001651 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001652 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001653 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001654 }
1655
1656 command_string = revised_command_line.GetData();
1657 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001658 std::string remainder;
1659 if (actual_cmd_name_len < command_string.length())
1660 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1661 // than cmd_obj->GetCommandName(), because name completion
1662 // allows users to enter short versions of the names,
1663 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001664
1665 // Remove any initial spaces
1666 std::string white_space (" \t\v");
1667 size_t pos = remainder.find_first_not_of (white_space);
1668 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001669 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001670
1671 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001672 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001673
Jim Inghamda26bd22012-06-08 21:56:10 +00001674 cmd_obj->Execute (remainder.c_str(), result);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001675 }
1676 else
1677 {
1678 // We didn't find the first command object, so complete the first argument.
1679 Args command_args (revised_command_line.GetData());
1680 StringList matches;
1681 int num_matches;
1682 int cursor_index = 0;
1683 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1684 bool word_complete;
1685 num_matches = HandleCompletionMatches (command_args,
1686 cursor_index,
1687 cursor_char_position,
1688 0,
1689 -1,
1690 word_complete,
1691 matches);
1692
1693 if (num_matches > 0)
1694 {
1695 std::string error_msg;
1696 error_msg.assign ("ambiguous command '");
1697 error_msg.append(command_args.GetArgumentAtIndex(0));
1698 error_msg.append ("'.");
1699
1700 error_msg.append (" Possible completions:");
1701 for (int i = 0; i < num_matches; i++)
1702 {
1703 error_msg.append ("\n\t");
1704 error_msg.append (matches.GetStringAtIndex (i));
1705 }
1706 error_msg.append ("\n");
1707 result.AppendRawError (error_msg.c_str(), error_msg.size());
1708 }
1709 else
1710 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1711
1712 result.SetStatus (eReturnStatusFailed);
1713 }
1714
Jason Molenda24c991c2011-08-25 00:20:04 +00001715 if (log)
1716 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1717
Chris Lattner24943d22010-06-08 16:52:24 +00001718 return result.Succeeded();
1719}
1720
1721int
1722CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1723 int &cursor_index,
1724 int &cursor_char_position,
1725 int match_start_point,
1726 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001727 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001728 StringList &matches)
1729{
1730 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001731 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001732
1733 // For any of the command completions a unique match will be a complete word.
1734 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001735
1736 if (cursor_index == -1)
1737 {
1738 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001739 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001740 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1741 }
1742 else if (cursor_index == 0)
1743 {
1744 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001745 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001746 num_command_matches = matches.GetSize();
1747
1748 if (num_command_matches == 1
1749 && cmd_obj && cmd_obj->IsMultiwordObject()
1750 && matches.GetStringAtIndex(0) != NULL
1751 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1752 {
1753 look_for_subcommand = true;
1754 num_command_matches = 0;
1755 matches.DeleteStringAtIndex(0);
1756 parsed_line.AppendArgument ("");
1757 cursor_index++;
1758 cursor_char_position = 0;
1759 }
1760 }
1761
1762 if (cursor_index > 0 || look_for_subcommand)
1763 {
1764 // We are completing further on into a commands arguments, so find the command and tell it
1765 // to complete the command.
1766 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001767 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001768 if (command_object == NULL)
1769 {
1770 return 0;
1771 }
1772 else
1773 {
1774 parsed_line.Shift();
1775 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001776 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001777 cursor_index,
1778 cursor_char_position,
1779 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001780 max_return_elements,
1781 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001782 matches);
1783 }
1784 }
1785
1786 return num_command_matches;
1787
1788}
1789
1790int
1791CommandInterpreter::HandleCompletion (const char *current_line,
1792 const char *cursor,
1793 const char *last_char,
1794 int match_start_point,
1795 int max_return_elements,
1796 StringList &matches)
1797{
1798 // We parse the argument up to the cursor, so the last argument in parsed_line is
1799 // the one containing the cursor, and the cursor is after the last character.
1800
1801 Args parsed_line(current_line, last_char - current_line);
1802 Args partial_parsed_line(current_line, cursor - current_line);
1803
Jim Ingham6247dbe2011-07-12 03:12:18 +00001804 // Don't complete comments, and if the line we are completing is just the history repeat character,
1805 // substitute the appropriate history line.
1806 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1807 if (first_arg)
1808 {
1809 if (first_arg[0] == m_comment_char)
1810 return 0;
1811 else if (first_arg[0] == m_repeat_char)
1812 {
1813 const char *history_string = FindHistoryString (first_arg);
1814 if (history_string != NULL)
1815 {
1816 matches.Clear();
1817 matches.InsertStringAtIndex(0, history_string);
1818 return -2;
1819 }
1820 else
1821 return 0;
1822
1823 }
1824 }
1825
1826
Chris Lattner24943d22010-06-08 16:52:24 +00001827 int num_args = partial_parsed_line.GetArgumentCount();
1828 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1829 int cursor_char_position;
1830
1831 if (cursor_index == -1)
1832 cursor_char_position = 0;
1833 else
1834 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001835
1836 if (cursor > current_line && cursor[-1] == ' ')
1837 {
1838 // We are just after a space. If we are in an argument, then we will continue
1839 // parsing, but if we are between arguments, then we have to complete whatever the next
1840 // element would be.
1841 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1842 // protected by a quote) then the space will also be in the parsed argument...
1843
1844 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1845 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1846 {
1847 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1848 cursor_index++;
1849 cursor_char_position = 0;
1850 }
1851 }
Chris Lattner24943d22010-06-08 16:52:24 +00001852
1853 int num_command_matches;
1854
1855 matches.Clear();
1856
1857 // Only max_return_elements == -1 is supported at present:
1858 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001859 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001860 num_command_matches = HandleCompletionMatches (parsed_line,
1861 cursor_index,
1862 cursor_char_position,
1863 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001864 max_return_elements,
1865 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001866 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001867
1868 if (num_command_matches <= 0)
1869 return num_command_matches;
1870
1871 if (num_args == 0)
1872 {
1873 // If we got an empty string, insert nothing.
1874 matches.InsertStringAtIndex(0, "");
1875 }
1876 else
1877 {
1878 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1879 // put an empty string in element 0.
1880 std::string command_partial_str;
1881 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001882 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1883 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001884
1885 std::string common_prefix;
1886 matches.LongestCommonPrefix (common_prefix);
1887 int partial_name_len = command_partial_str.size();
1888
1889 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001890 // Only do this if the completer told us this was a complete word, however...
1891 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001892 {
1893 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1894 if (quote_char != '\0')
1895 common_prefix.push_back(quote_char);
1896
1897 common_prefix.push_back(' ');
1898 }
1899 common_prefix.erase (0, partial_name_len);
1900 matches.InsertStringAtIndex(0, common_prefix.c_str());
1901 }
1902 return num_command_matches;
1903}
1904
Chris Lattner24943d22010-06-08 16:52:24 +00001905
1906CommandInterpreter::~CommandInterpreter ()
1907{
1908}
1909
1910const char *
1911CommandInterpreter::GetPrompt ()
1912{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001913 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001914}
1915
1916void
1917CommandInterpreter::SetPrompt (const char *new_prompt)
1918{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001919 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001920}
1921
Jim Ingham5e16ef52010-10-04 19:49:29 +00001922size_t
Greg Clayton58928562011-02-09 01:08:52 +00001923CommandInterpreter::GetConfirmationInputReaderCallback
1924(
1925 void *baton,
1926 InputReader &reader,
1927 lldb::InputReaderAction action,
1928 const char *bytes,
1929 size_t bytes_len
1930)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001931{
Greg Clayton58928562011-02-09 01:08:52 +00001932 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001933 bool *response_ptr = (bool *) baton;
1934
1935 switch (action)
1936 {
1937 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001938 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001939 {
1940 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001941 {
Greg Clayton58928562011-02-09 01:08:52 +00001942 out_file.Printf ("%s", reader.GetPrompt());
1943 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001944 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001945 }
1946 break;
1947
1948 case eInputReaderDeactivate:
1949 break;
1950
1951 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001952 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001953 {
Greg Clayton58928562011-02-09 01:08:52 +00001954 out_file.Printf ("%s", reader.GetPrompt());
1955 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001956 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001957 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001958
1959 case eInputReaderAsynchronousOutputWritten:
1960 break;
1961
Jim Ingham5e16ef52010-10-04 19:49:29 +00001962 case eInputReaderGotToken:
1963 if (bytes_len == 0)
1964 {
1965 reader.SetIsDone(true);
1966 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001967 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001968 {
1969 *response_ptr = true;
1970 reader.SetIsDone(true);
1971 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001972 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001973 {
1974 *response_ptr = false;
1975 reader.SetIsDone(true);
1976 }
1977 else
1978 {
Greg Clayton58928562011-02-09 01:08:52 +00001979 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001980 {
Jim Ingham26183802011-11-17 01:22:00 +00001981 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00001982 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001983 }
1984 }
1985 break;
1986
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001987 case eInputReaderInterrupt:
1988 case eInputReaderEndOfFile:
1989 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1990 reader.SetIsDone (true);
1991 break;
1992
Jim Ingham5e16ef52010-10-04 19:49:29 +00001993 case eInputReaderDone:
1994 break;
1995 }
1996
1997 return bytes_len;
1998
1999}
2000
2001bool
2002CommandInterpreter::Confirm (const char *message, bool default_answer)
2003{
Jim Ingham93057472010-10-04 22:44:14 +00002004 // Check AutoConfirm first:
2005 if (m_debugger.GetAutoConfirm())
2006 return default_answer;
2007
Jim Ingham5e16ef52010-10-04 19:49:29 +00002008 InputReaderSP reader_sp (new InputReader(GetDebugger()));
2009 bool response = default_answer;
2010 if (reader_sp)
2011 {
2012 std::string prompt(message);
2013 prompt.append(": [");
2014 if (default_answer)
2015 prompt.append ("Y/n] ");
2016 else
2017 prompt.append ("y/N] ");
2018
2019 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
2020 &response, // baton
2021 eInputReaderGranularityLine, // token size, to pass to callback function
2022 NULL, // end token
2023 prompt.c_str(), // prompt
2024 true)); // echo input
2025 if (err.Success())
2026 {
2027 GetDebugger().PushInputReader (reader_sp);
2028 }
2029 reader_sp->WaitOnReaderIsDone();
2030 }
2031 return response;
2032}
2033
2034
Chris Lattner24943d22010-06-08 16:52:24 +00002035void
2036CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
2037{
Jim Inghamd40f8a62010-07-06 22:46:59 +00002038 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00002039
Sean Callananb386d822012-08-09 00:50:26 +00002040 if (cmd_obj_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002041 {
2042 CommandObject *cmd_obj = cmd_obj_sp.get();
2043 if (cmd_obj->IsCrossRefObject ())
2044 cmd_obj->AddObject (object_type);
2045 }
2046}
2047
Chris Lattner24943d22010-06-08 16:52:24 +00002048OptionArgVectorSP
2049CommandInterpreter::GetAliasOptions (const char *alias_name)
2050{
2051 OptionArgMap::iterator pos;
2052 OptionArgVectorSP ret_val;
2053
2054 std::string alias (alias_name);
2055
2056 if (HasAliasOptions())
2057 {
2058 pos = m_alias_options.find (alias);
2059 if (pos != m_alias_options.end())
2060 ret_val = pos->second;
2061 }
2062
2063 return ret_val;
2064}
2065
2066void
2067CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2068{
2069 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2070 if (pos != m_alias_options.end())
2071 {
2072 m_alias_options.erase (pos);
2073 }
2074}
2075
2076void
2077CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2078{
2079 m_alias_options[alias_name] = option_arg_vector_sp;
2080}
2081
2082bool
2083CommandInterpreter::HasCommands ()
2084{
2085 return (!m_command_dict.empty());
2086}
2087
2088bool
2089CommandInterpreter::HasAliases ()
2090{
2091 return (!m_alias_dict.empty());
2092}
2093
2094bool
2095CommandInterpreter::HasUserCommands ()
2096{
2097 return (!m_user_dict.empty());
2098}
2099
2100bool
2101CommandInterpreter::HasAliasOptions ()
2102{
2103 return (!m_alias_options.empty());
2104}
2105
Chris Lattner24943d22010-06-08 16:52:24 +00002106void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002107CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2108 const char *alias_name,
2109 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00002110 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002111 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00002112{
2113 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00002114
2115 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00002116
Caroline Tice44c841d2010-12-07 19:58:26 +00002117 // Make sure that the alias name is the 0th element in cmd_args
2118 std::string alias_name_str = alias_name;
2119 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2120 cmd_args.Unshift (alias_name);
2121
2122 Args new_args (alias_cmd_obj->GetCommandName());
2123 if (new_args.GetArgumentCount() == 2)
2124 new_args.Shift();
2125
Chris Lattner24943d22010-06-08 16:52:24 +00002126 if (option_arg_vector_sp.get())
2127 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002128 if (wants_raw_input)
2129 {
2130 // We have a command that both has command options and takes raw input. Make *sure* it has a
2131 // " -- " in the right place in the raw_input_string.
2132 size_t pos = raw_input_string.find(" -- ");
2133 if (pos == std::string::npos)
2134 {
2135 // None found; assume it goes at the beginning of the raw input string
2136 raw_input_string.insert (0, " -- ");
2137 }
2138 }
Chris Lattner24943d22010-06-08 16:52:24 +00002139
2140 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2141 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002142 std::vector<bool> used (old_size + 1, false);
2143
2144 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002145
2146 for (int i = 0; i < option_arg_vector->size(); ++i)
2147 {
2148 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00002149 OptionArgValue value_pair = option_pair.second;
2150 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00002151 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00002152 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00002153 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002154 {
2155 if (!wants_raw_input
2156 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2157 new_args.AppendArgument (value.c_str());
2158 }
Chris Lattner24943d22010-06-08 16:52:24 +00002159 else
2160 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002161 if (value_type != optional_argument)
2162 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002163 if (value.compare ("<no-argument>") != 0)
2164 {
2165 int index = GetOptionArgumentPosition (value.c_str());
2166 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002167 {
Chris Lattner24943d22010-06-08 16:52:24 +00002168 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002169 if (value_type != optional_argument)
2170 new_args.AppendArgument (value.c_str());
2171 else
2172 {
2173 char buffer[255];
2174 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2175 new_args.AppendArgument (buffer);
2176 }
2177
2178 }
Chris Lattner24943d22010-06-08 16:52:24 +00002179 else if (index >= cmd_args.GetArgumentCount())
2180 {
2181 result.AppendErrorWithFormat
2182 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2183 index);
2184 result.SetStatus (eReturnStatusFailed);
2185 return;
2186 }
2187 else
2188 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002189 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2190 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2191 if (strpos != std::string::npos)
2192 {
2193 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2194 }
2195
2196 if (value_type != optional_argument)
2197 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2198 else
2199 {
2200 char buffer[255];
2201 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2202 cmd_args.GetArgumentAtIndex (index));
2203 new_args.AppendArgument (buffer);
2204 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002205 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002206 }
2207 }
2208 }
2209 }
2210
2211 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2212 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002213 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002214 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2215 }
2216
2217 cmd_args.Clear();
2218 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2219 }
2220 else
2221 {
2222 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002223 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2224 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2225 // input string.
2226 if (wants_raw_input)
2227 {
2228 cmd_args.Clear();
2229 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2230 }
Chris Lattner24943d22010-06-08 16:52:24 +00002231 return;
2232 }
2233
2234 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2235 return;
2236}
2237
2238
2239int
2240CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2241{
2242 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2243 // of zero.
2244
2245 char *cptr = (char *) in_string;
2246
2247 // Does it start with '%'
2248 if (cptr[0] == '%')
2249 {
2250 ++cptr;
2251
2252 // Is the rest of it entirely digits?
2253 if (isdigit (cptr[0]))
2254 {
2255 const char *start = cptr;
2256 while (isdigit (cptr[0]))
2257 ++cptr;
2258
2259 // We've gotten to the end of the digits; are we at the end of the string?
2260 if (cptr[0] == '\0')
2261 position = atoi (start);
2262 }
2263 }
2264
2265 return position;
2266}
2267
2268void
2269CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2270{
Jim Ingham574c3d62011-08-12 23:34:31 +00002271 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002272 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002273 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002274 // In the current working directory we don't load any program specific
2275 // .lldbinit files, we only look for a "./.lldbinit" file.
2276 if (m_skip_lldbinit_files)
2277 return;
2278
2279 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002280 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002281 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002282 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002283 // If we aren't looking in the current working directory we are looking
2284 // in the home directory. We will first see if there is an application
2285 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2286 // "-" and the name of the program. If this file doesn't exist, we fall
2287 // back to just the "~/.lldbinit" file. We also obey any requests to not
2288 // load the init files.
2289 const char *init_file_path = "~/.lldbinit";
2290
2291 if (m_skip_app_init_files == false)
2292 {
2293 FileSpec program_file_spec (Host::GetProgramFileSpec());
2294 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002295
Greg Claytond6edcb52011-09-11 00:01:44 +00002296 if (program_name)
2297 {
2298 char program_init_file_name[PATH_MAX];
2299 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2300 init_file.SetFile (program_init_file_name, true);
2301 if (!init_file.Exists())
2302 init_file.Clear();
2303 }
2304 }
2305
2306 if (!init_file && !m_skip_lldbinit_files)
2307 init_file.SetFile (init_file_path, true);
2308 }
2309
Chris Lattner24943d22010-06-08 16:52:24 +00002310 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2311 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2312
2313 if (init_file.Exists())
2314 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002315 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2316 bool stop_on_continue = true;
2317 bool stop_on_error = false;
2318 bool echo_commands = false;
2319 bool print_results = false;
2320
Enrico Granata01bc2d42012-05-31 01:09:06 +00002321 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002322 }
2323 else
2324 {
2325 // nothing to be done if the file doesn't exist
2326 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2327 }
2328}
2329
Greg Claytonb72d0f02011-04-12 05:54:46 +00002330PlatformSP
2331CommandInterpreter::GetPlatform (bool prefer_target_platform)
2332{
2333 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002334 if (prefer_target_platform)
2335 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002336 ExecutionContext exe_ctx(GetExecutionContext());
2337 Target *target = exe_ctx.GetTargetPtr();
Greg Clayton567e7f32011-09-22 04:58:26 +00002338 if (target)
2339 platform_sp = target->GetPlatform();
2340 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002341
2342 if (!platform_sp)
2343 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2344 return platform_sp;
2345}
2346
Jim Ingham949d5ac2011-02-18 00:54:25 +00002347void
Jim Inghama4fede32011-03-11 01:51:49 +00002348CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002349 ExecutionContext *override_context,
2350 bool stop_on_continue,
2351 bool stop_on_error,
2352 bool echo_commands,
2353 bool print_results,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002354 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002355 CommandReturnObject &result)
2356{
2357 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002358
2359 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2360 // Make sure you reset this value anywhere you return from the function.
2361
2362 bool old_async_execution = m_debugger.GetAsyncExecution();
2363
2364 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2365 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2366
2367 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002368 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002369
2370 if (!stop_on_continue)
2371 {
2372 m_debugger.SetAsyncExecution (false);
2373 }
2374
2375 for (int idx = 0; idx < num_lines; idx++)
2376 {
2377 const char *cmd = commands.GetStringAtIndex(idx);
2378 if (cmd[0] == '\0')
2379 continue;
2380
Jim Ingham949d5ac2011-02-18 00:54:25 +00002381 if (echo_commands)
2382 {
2383 result.AppendMessageWithFormat ("%s %s\n",
2384 GetPrompt(),
2385 cmd);
2386 }
2387
Greg Claytonaa378b12011-02-20 02:15:07 +00002388 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002389 // If override_context is not NULL, pass no_context_switching = true for
2390 // HandleCommand() since we updated our context already.
Enrico Granata01bc2d42012-05-31 01:09:06 +00002391 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002392 NULL, /* override_context */
2393 true, /* repeat_on_empty_command */
2394 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002395
2396 if (print_results)
2397 {
2398 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002399 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002400 }
2401
2402 if (!success || !tmp_result.Succeeded())
2403 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002404 const char *error_msg = tmp_result.GetErrorData();
2405 if (error_msg == NULL || error_msg[0] == '\0')
2406 error_msg = "<unknown error>.\n";
Jim Ingham949d5ac2011-02-18 00:54:25 +00002407 if (stop_on_error)
2408 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002409 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2410 idx, cmd, error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002411 result.SetStatus (eReturnStatusFailed);
2412 m_debugger.SetAsyncExecution (old_async_execution);
2413 return;
2414 }
2415 else if (print_results)
2416 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002417 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Ingham949d5ac2011-02-18 00:54:25 +00002418 idx + 1,
2419 cmd,
Jim Ingham862fd5c2012-04-24 02:25:07 +00002420 error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002421 }
2422 }
2423
Caroline Tice4a348082011-05-02 20:41:46 +00002424 if (result.GetImmediateOutputStream())
2425 result.GetImmediateOutputStream()->Flush();
2426
2427 if (result.GetImmediateErrorStream())
2428 result.GetImmediateErrorStream()->Flush();
2429
Jim Ingham949d5ac2011-02-18 00:54:25 +00002430 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2431 // could be running (for instance in Breakpoint Commands.
2432 // So we check the return value to see if it is has running in it.
2433 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2434 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2435 {
2436 if (stop_on_continue)
2437 {
2438 // If we caused the target to proceed, and we're going to stop in that case, set the
2439 // status in our real result before returning. This is an error if the continue was not the
2440 // last command in the set of commands to be run.
2441 if (idx != num_lines - 1)
2442 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2443 idx + 1, cmd);
2444 else
2445 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2446
2447 result.SetStatus(tmp_result.GetStatus());
2448 m_debugger.SetAsyncExecution (old_async_execution);
2449
2450 return;
2451 }
2452 }
2453
2454 }
2455
2456 result.SetStatus (eReturnStatusSuccessFinishResult);
2457 m_debugger.SetAsyncExecution (old_async_execution);
2458
2459 return;
2460}
2461
2462void
2463CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2464 ExecutionContext *context,
2465 bool stop_on_continue,
2466 bool stop_on_error,
2467 bool echo_command,
2468 bool print_result,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002469 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002470 CommandReturnObject &result)
2471{
2472 if (cmd_file.Exists())
2473 {
2474 bool success;
2475 StringList commands;
2476 success = commands.ReadFileLines(cmd_file);
2477 if (!success)
2478 {
2479 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2480 result.SetStatus (eReturnStatusFailed);
2481 return;
2482 }
Enrico Granata01bc2d42012-05-31 01:09:06 +00002483 m_command_source_depth++;
2484 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2485 m_command_source_depth--;
Jim Ingham949d5ac2011-02-18 00:54:25 +00002486 }
2487 else
2488 {
2489 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2490 cmd_file.GetFilename().AsCString());
2491 result.SetStatus (eReturnStatusFailed);
2492 return;
2493 }
2494}
2495
Chris Lattner24943d22010-06-08 16:52:24 +00002496ScriptInterpreter *
2497CommandInterpreter::GetScriptInterpreter ()
2498{
Enrico Granatac5c10a42012-07-10 18:23:48 +00002499 // <rdar://problem/11751427>
2500 // we need to protect the initialization of the script interpreter
2501 // otherwise we could end up with two threads both trying to create
2502 // their instance of it, and for some languages (e.g. Python)
2503 // this is a bulletproof recipe for disaster!
2504 // this needs to be a function-level static because multiple Debugger instances living in the same process
2505 // still need to be isolated and not try to initialize Python concurrently
Enrico Granatab88c0a92012-07-10 19:04:14 +00002506 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2507 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granatac5c10a42012-07-10 18:23:48 +00002508
Caroline Tice0aa2e552011-01-14 00:29:16 +00002509 if (m_script_interpreter_ap.get() != NULL)
2510 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002511
Caroline Tice0aa2e552011-01-14 00:29:16 +00002512 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2513 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002514 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002515 case eScriptLanguagePython:
2516#ifndef LLDB_DISABLE_PYTHON
2517 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2518 break;
2519#else
2520 // Fall through to the None case when python is disabled
2521#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002522 case eScriptLanguageNone:
2523 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2524 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002525 default:
2526 break;
2527 };
2528
2529 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002530}
2531
2532
2533
2534bool
2535CommandInterpreter::GetSynchronous ()
2536{
2537 return m_synchronous_execution;
2538}
2539
2540void
2541CommandInterpreter::SetSynchronous (bool value)
2542{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002543 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002544}
2545
2546void
2547CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2548 const char *word_text,
2549 const char *separator,
2550 const char *help_text,
2551 uint32_t max_word_len)
2552{
Greg Clayton238c0a12010-09-18 01:14:36 +00002553 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2554
Chris Lattner24943d22010-06-08 16:52:24 +00002555 int indent_size = max_word_len + strlen (separator) + 2;
2556
2557 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002558
2559 StreamString text_strm;
2560 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2561
2562 size_t len = text_strm.GetSize();
2563 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002564 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002565 {
2566 text_strm.EOL();
2567 len = text_strm.GetSize();
2568 }
Chris Lattner24943d22010-06-08 16:52:24 +00002569
2570 if (len < max_columns)
2571 {
2572 // Output it as a single line.
2573 strm.Printf ("%s", text);
2574 }
2575 else
2576 {
2577 // We need to break it up into multiple lines.
2578 bool first_line = true;
2579 int text_width;
2580 int start = 0;
2581 int end = start;
2582 int final_end = strlen (text);
2583 int sub_len;
2584
2585 while (end < final_end)
2586 {
2587 if (first_line)
2588 text_width = max_columns - 1;
2589 else
2590 text_width = max_columns - indent_size - 1;
2591
2592 // Don't start the 'text' on a space, since we're already outputting the indentation.
2593 if (!first_line)
2594 {
2595 while ((start < final_end) && (text[start] == ' '))
2596 start++;
2597 }
2598
2599 end = start + text_width;
2600 if (end > final_end)
2601 end = final_end;
2602 else
2603 {
2604 // If we're not at the end of the text, make sure we break the line on white space.
2605 while (end > start
2606 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2607 end--;
Greg Clayton73844aa2012-08-22 17:17:09 +00002608 assert (end > 0);
Chris Lattner24943d22010-06-08 16:52:24 +00002609 }
2610
2611 sub_len = end - start;
2612 if (start != 0)
2613 strm.EOL();
2614 if (!first_line)
2615 strm.Indent();
2616 else
2617 first_line = false;
2618 assert (start <= final_end);
2619 assert (start + sub_len <= final_end);
2620 if (sub_len > 0)
2621 strm.Write (text + start, sub_len);
2622 start = end + 1;
2623 }
2624 }
2625 strm.EOL();
2626 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002627}
2628
2629void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002630CommandInterpreter::OutputHelpText (Stream &strm,
2631 const char *word_text,
2632 const char *separator,
2633 const char *help_text,
2634 uint32_t max_word_len)
2635{
2636 int indent_size = max_word_len + strlen (separator) + 2;
2637
2638 strm.IndentMore (indent_size);
2639
2640 StreamString text_strm;
2641 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2642
2643 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata1bba6e52011-07-07 00:38:40 +00002644
2645 size_t len = text_strm.GetSize();
2646 const char *text = text_strm.GetData();
2647
2648 uint32_t chars_left = max_columns;
2649
2650 for (uint32_t i = 0; i < len; i++)
2651 {
2652 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2653 {
Enrico Granata1bba6e52011-07-07 00:38:40 +00002654 chars_left = max_columns - indent_size;
2655 strm.EOL();
2656 strm.Indent();
2657 }
2658 else
2659 {
2660 strm.PutChar(text[i]);
2661 chars_left--;
2662 }
2663
2664 }
2665
2666 strm.EOL();
2667 strm.IndentLess(indent_size);
2668}
2669
2670void
Chris Lattner24943d22010-06-08 16:52:24 +00002671CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2672 StringList &commands_found, StringList &commands_help)
2673{
2674 CommandObject::CommandMap::const_iterator pos;
2675 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2676 CommandObject *sub_cmd_obj;
2677
2678 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2679 {
2680 const char * command_name = pos->first.c_str();
2681 sub_cmd_obj = pos->second.get();
2682 StreamString complete_command_name;
2683
2684 complete_command_name.Printf ("%s %s", prefix, command_name);
2685
Greg Clayton238c0a12010-09-18 01:14:36 +00002686 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002687 {
2688 commands_found.AppendString (complete_command_name.GetData());
2689 commands_help.AppendString (sub_cmd_obj->GetHelp());
2690 }
2691
2692 if (sub_cmd_obj->IsMultiwordObject())
2693 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2694 commands_help);
2695 }
2696
2697}
2698
2699void
2700CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2701 StringList &commands_help)
2702{
2703 CommandObject::CommandMap::const_iterator pos;
2704
2705 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2706 {
2707 const char *command_name = pos->first.c_str();
2708 CommandObject *cmd_obj = pos->second.get();
2709
Greg Clayton238c0a12010-09-18 01:14:36 +00002710 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002711 {
2712 commands_found.AppendString (command_name);
2713 commands_help.AppendString (cmd_obj->GetHelp());
2714 }
2715
2716 if (cmd_obj->IsMultiwordObject())
2717 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2718
2719 }
2720}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002721
2722
2723void
2724CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2725{
Greg Claytonb72d0f02011-04-12 05:54:46 +00002726 if (override_context != NULL)
2727 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002728 m_exe_ctx_ref = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002729 }
2730 else
2731 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002732 const bool adopt_selected = true;
2733 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002734 }
2735}
2736
Jim Ingham6247dbe2011-07-12 03:12:18 +00002737void
2738CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2739{
2740 DumpHistory (stream, 0, count - 1);
2741}
2742
2743void
2744CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2745{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002746 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2747 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002748 {
2749 if (!m_command_history[i].empty())
2750 {
2751 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002752 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002753 }
2754 }
2755}
2756
2757const char *
2758CommandInterpreter::FindHistoryString (const char *input_str) const
2759{
2760 if (input_str[0] != m_repeat_char)
2761 return NULL;
2762 if (input_str[1] == '-')
2763 {
2764 bool success;
2765 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2766 if (!success)
2767 return NULL;
2768 if (idx > m_command_history.size())
2769 return NULL;
2770 idx = m_command_history.size() - idx;
2771 return m_command_history[idx].c_str();
2772
2773 }
2774 else if (input_str[1] == m_repeat_char)
2775 {
2776 if (m_command_history.empty())
2777 return NULL;
2778 else
2779 return m_command_history.back().c_str();
2780 }
2781 else
2782 {
2783 bool success;
2784 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2785 if (!success)
2786 return NULL;
2787 if (idx >= m_command_history.size())
2788 return NULL;
2789 return m_command_history[idx].c_str();
2790 }
2791}