blob: b707ed9e61109b2c6072999ede53af8a130ba736 [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
Daniel Malead891f9b2012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner24943d22010-06-08 16:52:24 +000012#include <string>
Caroline Ticebd5c63e2010-10-12 21:57:09 +000013#include <vector>
Chris Lattner24943d22010-06-08 16:52:24 +000014
15#include <getopt.h>
16#include <stdlib.h>
17
Greg Clayton5c28dd12011-06-23 17:59:56 +000018#include "CommandObjectScript.h"
Peter Collingbourne921fac02011-06-23 20:37:26 +000019#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton5c28dd12011-06-23 17:59:56 +000020
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000021#include "../Commands/CommandObjectApropos.h"
22#include "../Commands/CommandObjectArgs.h"
23#include "../Commands/CommandObjectBreakpoint.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000024#include "../Commands/CommandObjectDisassemble.h"
25#include "../Commands/CommandObjectExpression.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectFrame.h"
27#include "../Commands/CommandObjectHelp.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000028#include "../Commands/CommandObjectLog.h"
29#include "../Commands/CommandObjectMemory.h"
Greg Claytonb1888f22011-03-19 01:12:21 +000030#include "../Commands/CommandObjectPlatform.h"
Enrico Granata6d101882012-09-28 23:57:51 +000031#include "../Commands/CommandObjectPlugin.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000032#include "../Commands/CommandObjectProcess.h"
33#include "../Commands/CommandObjectQuit.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectRegister.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSettings.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000036#include "../Commands/CommandObjectSource.h"
Jim Ingham767af882010-07-07 03:36:20 +000037#include "../Commands/CommandObjectCommands.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000038#include "../Commands/CommandObjectSyntax.h"
39#include "../Commands/CommandObjectTarget.h"
40#include "../Commands/CommandObjectThread.h"
Greg Clayton5c28dd12011-06-23 17:59:56 +000041#include "../Commands/CommandObjectType.h"
Johnny Chen902e0182010-12-23 20:21:44 +000042#include "../Commands/CommandObjectVersion.h"
Johnny Chen01acfa72011-09-22 18:04:58 +000043#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044
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"
Enrico Granatadb054912012-10-29 21:18:03 +000047#include "lldb/Core/Log.h"
Chris Lattner24943d22010-06-08 16:52:24 +000048#include "lldb/Core/Stream.h"
49#include "lldb/Core/Timer.h"
Enrico Granatadb054912012-10-29 21:18:03 +000050
Greg Claytoncd548032011-02-01 01:31:41 +000051#include "lldb/Host/Host.h"
Enrico Granatadb054912012-10-29 21:18:03 +000052
53#include "lldb/Interpreter/Args.h"
54#include "lldb/Interpreter/CommandReturnObject.h"
55#include "lldb/Interpreter/CommandInterpreter.h"
56#include "lldb/Interpreter/Options.h"
57#include "lldb/Interpreter/ScriptInterpreterNone.h"
58#include "lldb/Interpreter/ScriptInterpreterPython.h"
59
60
Chris Lattner24943d22010-06-08 16:52:24 +000061#include "lldb/Target/Process.h"
62#include "lldb/Target/Thread.h"
63#include "lldb/Target/TargetList.h"
64
Enrico Granatadb054912012-10-29 21:18:03 +000065#include "lldb/Utility/CleanUp.h"
Chris Lattner24943d22010-06-08 16:52:24 +000066
67using namespace lldb;
68using namespace lldb_private;
69
Greg Clayton9f282852012-08-23 00:22:02 +000070
71static PropertyDefinition
72g_properties[] =
73{
74 { "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." },
75 { NULL , OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL }
76};
77
78enum
79{
80 ePropertyExpandRegexAliases = 0
81};
82
Jim Ingham5a15e692012-02-16 06:50:00 +000083ConstString &
84CommandInterpreter::GetStaticBroadcasterClass ()
85{
86 static ConstString class_name ("lldb.commandInterpreter");
87 return class_name;
88}
89
Chris Lattner24943d22010-06-08 16:52:24 +000090CommandInterpreter::CommandInterpreter
91(
Greg Clayton63094e02010-06-23 01:19:29 +000092 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000093 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000094 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000095) :
Jim Ingham5a15e692012-02-16 06:50:00 +000096 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton9f282852012-08-23 00:22:02 +000097 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton63094e02010-06-23 01:19:29 +000098 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000099 m_synchronous_execution (synchronous_execution),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000100 m_skip_lldbinit_files (false),
Jim Ingham574c3d62011-08-12 23:34:31 +0000101 m_skip_app_init_files (false),
Jim Ingham949d5ac2011-02-18 00:54:25 +0000102 m_script_interpreter_ap (),
Caroline Tice892fadd2011-06-16 16:27:19 +0000103 m_comment_char ('#'),
Jim Ingham6247dbe2011-07-12 03:12:18 +0000104 m_repeat_char ('!'),
Johnny Chen3908bb12012-08-09 22:06:10 +0000105 m_batch_command_mode (false),
Enrico Granata01bc2d42012-05-31 01:09:06 +0000106 m_truncation_warning(eNoTruncation),
107 m_command_source_depth (0)
Chris Lattner24943d22010-06-08 16:52:24 +0000108{
Greg Clayton73844aa2012-08-22 17:17:09 +0000109 debugger.SetScriptLanguage (script_language);
Greg Clayton49ce6822010-10-31 03:01:06 +0000110 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
111 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton73844aa2012-08-22 17:17:09 +0000112 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham5a15e692012-02-16 06:50:00 +0000113 CheckInWithManager ();
Greg Clayton9f282852012-08-23 00:22:02 +0000114 m_collection_sp->Initialize (g_properties);
Chris Lattner24943d22010-06-08 16:52:24 +0000115}
116
Greg Clayton9f282852012-08-23 00:22:02 +0000117bool
118CommandInterpreter::GetExpandRegexAliases () const
119{
120 const uint32_t idx = ePropertyExpandRegexAliases;
121 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
122}
123
124
125
Chris Lattner24943d22010-06-08 16:52:24 +0000126void
127CommandInterpreter::Initialize ()
128{
129 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
130
131 CommandReturnObject result;
132
133 LoadCommandDictionary ();
134
Chris Lattner24943d22010-06-08 16:52:24 +0000135 // Set up some initial aliases.
Caroline Tice5ddbe212011-05-06 21:37:15 +0000136 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
137 if (cmd_obj_sp)
138 {
139 AddAlias ("q", cmd_obj_sp);
140 AddAlias ("exit", cmd_obj_sp);
141 }
Sean Callananfc58af22012-05-04 23:15:02 +0000142
Johnny Chena47e44b2012-08-24 18:15:45 +0000143 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callananfc58af22012-05-04 23:15:02 +0000144 if (cmd_obj_sp)
145 {
146 AddAlias ("attach", cmd_obj_sp);
147 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000148
Johnny Chena47e44b2012-08-24 18:15:45 +0000149 cmd_obj_sp = GetCommandSPExact ("process detach",false);
150 if (cmd_obj_sp)
151 {
152 AddAlias ("detach", cmd_obj_sp);
153 }
154
Caroline Tice5ddbe212011-05-06 21:37:15 +0000155 cmd_obj_sp = GetCommandSPExact ("process continue", false);
156 if (cmd_obj_sp)
157 {
158 AddAlias ("c", cmd_obj_sp);
159 AddAlias ("continue", cmd_obj_sp);
160 }
161
162 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
163 if (cmd_obj_sp)
164 AddAlias ("b", cmd_obj_sp);
165
Jim Ingham2753a022012-10-05 19:16:31 +0000166 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
167 if (cmd_obj_sp)
168 AddAlias ("tbreak", cmd_obj_sp);
169
Caroline Tice5ddbe212011-05-06 21:37:15 +0000170 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
171 if (cmd_obj_sp)
Jason Molenda47eb00e2011-10-22 00:47:41 +0000172 {
173 AddAlias ("stepi", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000174 AddAlias ("si", cmd_obj_sp);
Jason Molenda47eb00e2011-10-22 00:47:41 +0000175 }
176
177 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
178 if (cmd_obj_sp)
179 {
180 AddAlias ("nexti", cmd_obj_sp);
181 AddAlias ("ni", cmd_obj_sp);
182 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000183
184 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
185 if (cmd_obj_sp)
186 {
187 AddAlias ("s", cmd_obj_sp);
188 AddAlias ("step", cmd_obj_sp);
189 }
190
191 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
192 if (cmd_obj_sp)
193 {
194 AddAlias ("n", cmd_obj_sp);
195 AddAlias ("next", cmd_obj_sp);
196 }
197
198 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
199 if (cmd_obj_sp)
200 {
Caroline Tice5ddbe212011-05-06 21:37:15 +0000201 AddAlias ("finish", cmd_obj_sp);
202 }
203
Jim Ingham59355252011-12-02 01:12:59 +0000204 cmd_obj_sp = GetCommandSPExact ("frame select", false);
205 if (cmd_obj_sp)
206 {
207 AddAlias ("f", cmd_obj_sp);
208 }
209
Jim Ingham2753a022012-10-05 19:16:31 +0000210 cmd_obj_sp = GetCommandSPExact ("thread select", false);
211 if (cmd_obj_sp)
212 {
213 AddAlias ("t", cmd_obj_sp);
214 }
215
Caroline Tice5ddbe212011-05-06 21:37:15 +0000216 cmd_obj_sp = GetCommandSPExact ("source list", false);
217 if (cmd_obj_sp)
218 {
219 AddAlias ("l", cmd_obj_sp);
220 AddAlias ("list", cmd_obj_sp);
221 }
222
223 cmd_obj_sp = GetCommandSPExact ("memory read", false);
224 if (cmd_obj_sp)
225 AddAlias ("x", cmd_obj_sp);
226
227 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
228 if (cmd_obj_sp)
229 AddAlias ("up", cmd_obj_sp);
230
231 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
232 if (cmd_obj_sp)
233 AddAlias ("down", cmd_obj_sp);
234
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000235 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000236 if (cmd_obj_sp)
237 AddAlias ("display", cmd_obj_sp);
Jim Ingham9d1acc12011-10-24 18:37:00 +0000238
239 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
240 if (cmd_obj_sp)
241 AddAlias ("dis", cmd_obj_sp);
242
243 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
244 if (cmd_obj_sp)
245 AddAlias ("di", cmd_obj_sp);
246
247
Jason Molenda730cae02011-10-22 01:30:52 +0000248
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000249 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000250 if (cmd_obj_sp)
251 AddAlias ("undisplay", cmd_obj_sp);
252
Jim Inghamf190a412012-10-10 16:51:31 +0000253 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
254 if (cmd_obj_sp)
255 AddAlias ("bt", cmd_obj_sp);
256
Caroline Tice5ddbe212011-05-06 21:37:15 +0000257 cmd_obj_sp = GetCommandSPExact ("target create", false);
258 if (cmd_obj_sp)
259 AddAlias ("file", cmd_obj_sp);
260
261 cmd_obj_sp = GetCommandSPExact ("target modules", false);
262 if (cmd_obj_sp)
263 AddAlias ("image", cmd_obj_sp);
264
265
266 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000267
Caroline Tice5ddbe212011-05-06 21:37:15 +0000268 cmd_obj_sp = GetCommandSPExact ("expression", false);
269 if (cmd_obj_sp)
270 {
271 AddAlias ("expr", cmd_obj_sp);
272
273 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
274 AddAlias ("p", cmd_obj_sp);
275 AddAlias ("print", cmd_obj_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000276 AddAlias ("call", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000277 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
278 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000279 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000280
281 alias_arguments_vector_sp.reset (new OptionArgVector);
282 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
283 AddAlias ("po", cmd_obj_sp);
284 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
285 }
286
Sean Callananee301fa2012-06-01 23:29:32 +0000287 cmd_obj_sp = GetCommandSPExact ("process kill", false);
288 if (cmd_obj_sp)
Greg Claytonf2e53a52012-09-27 00:02:27 +0000289 {
Sean Callananee301fa2012-06-01 23:29:32 +0000290 AddAlias ("kill", cmd_obj_sp);
Greg Claytonf2e53a52012-09-27 00:02:27 +0000291 }
Sean Callananee301fa2012-06-01 23:29:32 +0000292
Caroline Tice5ddbe212011-05-06 21:37:15 +0000293 cmd_obj_sp = GetCommandSPExact ("process launch", false);
294 if (cmd_obj_sp)
295 {
296 alias_arguments_vector_sp.reset (new OptionArgVector);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000297#if defined (__arm__)
298 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
299#else
Greg Clayton86c50d72012-05-18 00:04:38 +0000300 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000301#endif
Caroline Tice5ddbe212011-05-06 21:37:15 +0000302 AddAlias ("r", cmd_obj_sp);
303 AddAlias ("run", cmd_obj_sp);
304 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
305 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
306 }
Greg Claytonc84623f2012-03-29 21:47:51 +0000307
308 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
309 if (cmd_obj_sp)
310 {
311 AddAlias ("add-dsym", cmd_obj_sp);
312 }
Sean Callanan7b71b172012-05-21 18:25:19 +0000313
314 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
315 if (cmd_obj_sp)
316 {
317 alias_arguments_vector_sp.reset (new OptionArgVector);
318 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
Jim Ingham2657b6b2012-10-18 23:24:12 +0000319 AddAlias ("rbreak", cmd_obj_sp);
320 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
Sean Callanan7b71b172012-05-21 18:25:19 +0000321 }
Chris Lattner24943d22010-06-08 16:52:24 +0000322}
323
Chris Lattner24943d22010-06-08 16:52:24 +0000324const char *
325CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
326{
327 // This function has not yet been implemented.
328
329 // Look for any embedded script command
330 // If found,
331 // get interpreter object from the command dictionary,
332 // call execute_one_command on it,
333 // get the results as a string,
334 // substitute that string for current stuff.
335
336 return arg;
337}
338
339
340void
341CommandInterpreter::LoadCommandDictionary ()
342{
343 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
344
345 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
346 //
347 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
348 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
349 // the cross-referencing stuff) are created!!!
350 //
351 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
352
353
354 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
355 // are created. This is so that when another command is created that needs to go into a crossref object,
356 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
357 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
358
Chris Lattner24943d22010-06-08 16:52:24 +0000359 // Non-CommandObjectCrossref commands can now be created.
360
Caroline Tice5bc8c972010-09-20 20:44:43 +0000361 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000362
Greg Clayton238c0a12010-09-18 01:14:36 +0000363 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000364 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000365 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000366 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000367 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
368 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000369// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000370 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000371 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000372 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000373 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
374 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000375 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata6d101882012-09-28 23:57:51 +0000376 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000377 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000378 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000379 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000380 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000381 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000382 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000383 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
384 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000385 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000386 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000387 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000388
Jim Ingham2753a022012-10-05 19:16:31 +0000389 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
390 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
391 {"^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
392 {"^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
393 {"^(-.*)$", "breakpoint set %1"},
394 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
395 {"^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"}};
396
397 size_t num_regexes = sizeof break_regexes/sizeof(char *[2]);
398
Chris Lattner24943d22010-06-08 16:52:24 +0000399 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000400 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000401 "_regexp-break",
Johnny Chen58edac32012-08-23 00:32:22 +0000402 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
403 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Jim Ingham2753a022012-10-05 19:16:31 +0000404
Chris Lattner24943d22010-06-08 16:52:24 +0000405 if (break_regex_cmd_ap.get())
406 {
Jim Ingham2753a022012-10-05 19:16:31 +0000407 bool success = true;
408 for (size_t i = 0; i < num_regexes; i++)
409 {
410 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
411 if (!success)
412 break;
413 }
414 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
415
416 if (success)
Chris Lattner24943d22010-06-08 16:52:24 +0000417 {
418 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
419 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
420 }
421 }
Jim Inghame56493f2011-03-22 02:29:32 +0000422
423 std::auto_ptr<CommandObjectRegexCommand>
Jim Ingham2753a022012-10-05 19:16:31 +0000424 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
425 "_regexp-tbreak",
426 "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
427 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
428
429 if (tbreak_regex_cmd_ap.get())
430 {
431 bool success = true;
432 for (size_t i = 0; i < num_regexes; i++)
433 {
434 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
435 char buffer[1024];
436 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
437 assert (num_printed < 1024);
438 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
439 if (!success)
440 break;
441 }
442 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
443
444 if (success)
445 {
446 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
447 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
448 }
449 }
450
451 std::auto_ptr<CommandObjectRegexCommand>
Johnny Chena47e44b2012-08-24 18:15:45 +0000452 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
453 "_regexp-attach",
454 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.",
455 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]", 2));
456 if (attach_regex_cmd_ap.get())
457 {
458 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "process attach --pid %1") &&
459 attach_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "process attach --name '%1'"))
460 {
461 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
462 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
463 }
464 }
465
466 std::auto_ptr<CommandObjectRegexCommand>
Jim Inghame56493f2011-03-22 02:29:32 +0000467 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000468 "_regexp-down",
469 "Go down \"n\" frames in the stack (1 frame by default).",
470 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000471 if (down_regex_cmd_ap.get())
472 {
473 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
474 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
475 {
476 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
477 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
478 }
479 }
480
481 std::auto_ptr<CommandObjectRegexCommand>
482 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000483 "_regexp-up",
484 "Go up \"n\" frames in the stack (1 frame by default).",
485 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000486 if (up_regex_cmd_ap.get())
487 {
488 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
489 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
490 {
491 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
492 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
493 }
494 }
Jason Molenda730cae02011-10-22 01:30:52 +0000495
496 std::auto_ptr<CommandObjectRegexCommand>
497 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000498 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000499 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000500 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000501 if (display_regex_cmd_ap.get())
502 {
503 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
504 {
505 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
506 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
507 }
508 }
509
510 std::auto_ptr<CommandObjectRegexCommand>
511 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000512 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000513 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000514 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000515 if (undisplay_regex_cmd_ap.get())
516 {
517 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
518 {
519 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
520 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
521 }
522 }
523
Greg Claytonc3750432012-09-26 22:26:47 +0000524 std::auto_ptr<CommandObjectRegexCommand>
525 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
526 "gdb-remote",
Jason Molendade1edce2012-10-23 03:05:16 +0000527 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
528 "gdb-remote [<hostname>:]<portnum>", 2));
Greg Claytonc3750432012-09-26 22:26:47 +0000529 if (connect_gdb_remote_cmd_ap.get())
530 {
531 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
532 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
533 {
534 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
535 m_command_dict[command_sp->GetCommandName ()] = command_sp;
536 }
537 }
538
539 std::auto_ptr<CommandObjectRegexCommand>
540 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
541 "kdp-remote",
Jason Molendade1edce2012-10-23 03:05:16 +0000542 "Connect to a remote KDP server. udp port 41139 is the default port number.",
543 "kdp-remote <hostname>[:<portnum>]", 2));
Greg Claytonc3750432012-09-26 22:26:47 +0000544 if (connect_kdp_remote_cmd_ap.get())
545 {
546 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molenda73feea42012-09-27 02:47:55 +0000547 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Claytonc3750432012-09-26 22:26:47 +0000548 {
549 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
550 m_command_dict[command_sp->GetCommandName ()] = command_sp;
551 }
552 }
553
Jason Molenda1a48cb72012-10-05 05:29:32 +0000554 std::auto_ptr<CommandObjectRegexCommand>
555 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jim Inghamf190a412012-10-10 16:51:31 +0000556 "_regexp-bt",
Jason Molenda1a48cb72012-10-05 05:29:32 +0000557 "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.",
558 "bt [<digit>|all]", 2));
559 if (bt_regex_cmd_ap.get())
560 {
561 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
562 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
563 // so now "bt 3" is the preferred form, in line with gdb.
564 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
565 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
566 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
567 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
568 {
569 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
570 m_command_dict[command_sp->GetCommandName ()] = command_sp;
571 }
572 }
573
Chris Lattner24943d22010-06-08 16:52:24 +0000574}
575
576int
577CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
578 StringList &matches)
579{
580 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
581
582 if (include_aliases)
583 {
584 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
585 }
586
587 return matches.GetSize();
588}
589
590CommandObjectSP
591CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
592{
593 CommandObject::CommandMap::iterator pos;
594 CommandObjectSP ret_val;
595
596 std::string cmd(cmd_cstr);
597
598 if (HasCommands())
599 {
600 pos = m_command_dict.find(cmd);
601 if (pos != m_command_dict.end())
602 ret_val = pos->second;
603 }
604
605 if (include_aliases && HasAliases())
606 {
607 pos = m_alias_dict.find(cmd);
608 if (pos != m_alias_dict.end())
609 ret_val = pos->second;
610 }
611
612 if (HasUserCommands())
613 {
614 pos = m_user_dict.find(cmd);
615 if (pos != m_user_dict.end())
616 ret_val = pos->second;
617 }
618
Sean Callananb386d822012-08-09 00:50:26 +0000619 if (!exact && !ret_val)
Chris Lattner24943d22010-06-08 16:52:24 +0000620 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000621 // We will only get into here if we didn't find any exact matches.
622
623 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
624
Chris Lattner24943d22010-06-08 16:52:24 +0000625 StringList local_matches;
626 if (matches == NULL)
627 matches = &local_matches;
628
Jim Inghamd40f8a62010-07-06 22:46:59 +0000629 unsigned int num_cmd_matches = 0;
630 unsigned int num_alias_matches = 0;
631 unsigned int num_user_matches = 0;
632
633 // Look through the command dictionaries one by one, and if we get only one match from any of
634 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
635
Chris Lattner24943d22010-06-08 16:52:24 +0000636 if (HasCommands())
637 {
638 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
639 }
640
641 if (num_cmd_matches == 1)
642 {
643 cmd.assign(matches->GetStringAtIndex(0));
644 pos = m_command_dict.find(cmd);
645 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000646 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000647 }
648
Jim Ingham9a574172010-06-24 20:28:42 +0000649 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000650 {
651 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
652
653 }
654
Jim Inghamd40f8a62010-07-06 22:46:59 +0000655 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000656 {
657 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
658 pos = m_alias_dict.find(cmd);
659 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000660 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000661 }
662
Jim Ingham9a574172010-06-24 20:28:42 +0000663 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000664 {
665 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
666 }
667
Jim Inghamd40f8a62010-07-06 22:46:59 +0000668 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000669 {
670 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
671
672 pos = m_user_dict.find (cmd);
673 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000674 user_match_sp = pos->second;
675 }
676
677 // If we got exactly one match, return that, otherwise return the match list.
678
679 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
680 {
681 if (num_cmd_matches)
682 return real_match_sp;
683 else if (num_alias_matches)
684 return alias_match_sp;
685 else
686 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000687 }
688 }
Sean Callananb386d822012-08-09 00:50:26 +0000689 else if (matches && ret_val)
Jim Inghamd40f8a62010-07-06 22:46:59 +0000690 {
691 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000692 }
693
694
695 return ret_val;
696}
697
Greg Claytond12aeab2011-04-20 16:37:46 +0000698bool
699CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
700{
701 if (name && name[0])
702 {
703 std::string name_sstr(name);
Enrico Granata2f1014b2012-10-01 17:19:37 +0000704 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
705 if (found && !can_replace)
706 return false;
707 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata6d101882012-09-28 23:57:51 +0000708 return false;
Greg Claytond12aeab2011-04-20 16:37:46 +0000709 m_command_dict[name_sstr] = cmd_sp;
710 return true;
711 }
712 return false;
713}
714
Enrico Granata6b1596d2011-08-16 23:24:13 +0000715bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000716CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000717 const lldb::CommandObjectSP &cmd_sp,
718 bool can_replace)
719{
Enrico Granata6010ace2011-11-07 22:57:04 +0000720 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000721 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000722
723 const char* name_cstr = name.c_str();
724
725 // do not allow replacement of internal commands
726 if (CommandExists(name_cstr))
Enrico Granata6d101882012-09-28 23:57:51 +0000727 {
728 if (can_replace == false)
729 return false;
730 if (m_command_dict[name]->IsRemovable() == false)
731 return false;
732 }
Enrico Granata6010ace2011-11-07 22:57:04 +0000733
Enrico Granata6d101882012-09-28 23:57:51 +0000734 if (UserCommandExists(name_cstr))
735 {
736 if (can_replace == false)
737 return false;
738 if (m_user_dict[name]->IsRemovable() == false)
739 return false;
740 }
741
Enrico Granata6010ace2011-11-07 22:57:04 +0000742 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000743 return true;
744 }
745 return false;
746}
Greg Claytond12aeab2011-04-20 16:37:46 +0000747
Jim Inghamd40f8a62010-07-06 22:46:59 +0000748CommandObjectSP
749CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000750{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000751 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
752 CommandObjectSP ret_val; // Possibly empty return value.
753
754 if (cmd_cstr == NULL)
755 return ret_val;
756
757 if (cmd_words.GetArgumentCount() == 1)
758 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
759 else
760 {
761 // We have a multi-word command (seemingly), so we need to do more work.
762 // First, get the cmd_obj_sp for the first word in the command.
763 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
764 if (cmd_obj_sp.get() != NULL)
765 {
766 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
767 // command name), and find the appropriate sub-command SP for each command word....
768 size_t end = cmd_words.GetArgumentCount();
769 for (size_t j= 1; j < end; ++j)
770 {
771 if (cmd_obj_sp->IsMultiwordObject())
772 {
Greg Clayton13193d52012-10-13 02:07:45 +0000773 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Caroline Tice56d2fc42010-12-14 18:51:39 +0000774 if (cmd_obj_sp.get() == NULL)
775 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
776 return ret_val;
777 }
778 else
779 // We have more words in the command name, but we don't have a multiword object. Fail and return
780 // empty 'ret_val'.
781 return ret_val;
782 }
783 // We successfully looped through all the command words and got valid command objects for them. Assign the
784 // last object retrieved to 'ret_val'.
785 ret_val = cmd_obj_sp;
786 }
787 }
788 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000789}
790
791CommandObject *
792CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
793{
794 return GetCommandSPExact (cmd_cstr, include_aliases).get();
795}
796
797CommandObject *
798CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
799{
800 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
801
802 // If we didn't find an exact match to the command string in the commands, look in
803 // the aliases.
804
805 if (command_obj == NULL)
806 {
807 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
808 }
809
810 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
811 // in both the commands and the aliases.
812
813 if (command_obj == NULL)
814 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
815
816 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000817}
818
819bool
820CommandInterpreter::CommandExists (const char *cmd)
821{
822 return m_command_dict.find(cmd) != m_command_dict.end();
823}
824
825bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000826CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
827 const char *options_args,
828 OptionArgVectorSP &option_arg_vector_sp)
829{
830 bool success = true;
831 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
832
833 if (!options_args || (strlen (options_args) < 1))
834 return true;
835
836 std::string options_string (options_args);
837 Args args (options_args);
838 CommandReturnObject result;
839 // Check to see if the command being aliased can take any command options.
840 Options *options = cmd_obj_sp->GetOptions ();
841 if (options)
842 {
843 // See if any options were specified as part of the alias; if so, handle them appropriately.
844 options->NotifyOptionParsingStarting ();
845 args.Unshift ("dummy_arg");
846 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
847 args.Shift ();
848 if (result.Succeeded())
849 options->VerifyPartialOptions (result);
850 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
851 {
852 result.AppendError ("Unable to create requested alias.\n");
853 return false;
854 }
855 }
856
Greg Clayton7268b4c2011-10-28 21:38:01 +0000857 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000858 {
859 if (cmd_obj_sp->WantsRawCommandString ())
860 option_arg_vector->push_back (OptionArgPair ("<argument>",
861 OptionArgValue (-1,
862 options_string)));
863 else
864 {
865 int argc = args.GetArgumentCount();
866 for (size_t i = 0; i < argc; ++i)
867 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
868 option_arg_vector->push_back
869 (OptionArgPair ("<argument>",
870 OptionArgValue (-1,
871 std::string (args.GetArgumentAtIndex (i)))));
872 }
873 }
874
875 return success;
876}
877
878bool
Chris Lattner24943d22010-06-08 16:52:24 +0000879CommandInterpreter::AliasExists (const char *cmd)
880{
881 return m_alias_dict.find(cmd) != m_alias_dict.end();
882}
883
884bool
885CommandInterpreter::UserCommandExists (const char *cmd)
886{
887 return m_user_dict.find(cmd) != m_user_dict.end();
888}
889
890void
891CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
892{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000893 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000894 m_alias_dict[alias_name] = command_obj_sp;
895}
896
897bool
898CommandInterpreter::RemoveAlias (const char *alias_name)
899{
900 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
901 if (pos != m_alias_dict.end())
902 {
903 m_alias_dict.erase(pos);
904 return true;
905 }
906 return false;
907}
908bool
909CommandInterpreter::RemoveUser (const char *alias_name)
910{
911 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
912 if (pos != m_user_dict.end())
913 {
914 m_user_dict.erase(pos);
915 return true;
916 }
917 return false;
918}
919
Chris Lattner24943d22010-06-08 16:52:24 +0000920void
921CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
922{
923 help_string.Printf ("'%s", command_name);
924 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
925
Sean Callananb386d822012-08-09 00:50:26 +0000926 if (option_arg_vector_sp)
Chris Lattner24943d22010-06-08 16:52:24 +0000927 {
928 OptionArgVector *options = option_arg_vector_sp.get();
929 for (int i = 0; i < options->size(); ++i)
930 {
931 OptionArgPair cur_option = (*options)[i];
932 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000933 OptionArgValue value_pair = cur_option.second;
934 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000935 if (opt.compare("<argument>") == 0)
936 {
937 help_string.Printf (" %s", value.c_str());
938 }
939 else
940 {
941 help_string.Printf (" %s", opt.c_str());
942 if ((value.compare ("<no-argument>") != 0)
943 && (value.compare ("<need-argument") != 0))
944 {
945 help_string.Printf (" %s", value.c_str());
946 }
947 }
948 }
949 }
950
951 help_string.Printf ("'");
952}
953
Greg Clayton65124ea2010-08-26 22:05:43 +0000954size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000955CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
956{
957 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000958 CommandObject::CommandMap::const_iterator end = dict.end();
959 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000960
Greg Clayton65124ea2010-08-26 22:05:43 +0000961 for (pos = dict.begin(); pos != end; ++pos)
962 {
963 size_t len = pos->first.size();
964 if (max_len < len)
965 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000966 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000967 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000968}
969
970void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000971CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000972 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000973{
974 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000975 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000976
977 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000978 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000979
980 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
981 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000982
Enrico Granata6b1596d2011-08-16 23:24:13 +0000983 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
984 {
985 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
986 max_len);
987 }
988 result.AppendMessage("");
989
990 }
991
Greg Clayton7268b4c2011-10-28 21:38:01 +0000992 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000993 {
Jim Inghame3663e82010-10-22 18:47:16 +0000994 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000995 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000996 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000997 max_len = FindLongestCommandWord (m_alias_dict);
998
Chris Lattner24943d22010-06-08 16:52:24 +0000999 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1000 {
1001 StreamString sstr;
1002 StreamString translation_and_help;
1003 std::string entry_name = pos->first;
1004 std::string second_entry = pos->second.get()->GetCommandName();
1005 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1006
1007 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1008 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1009 translation_and_help.GetData(), max_len);
1010 }
1011 result.AppendMessage("");
1012 }
1013
Greg Clayton7268b4c2011-10-28 21:38:01 +00001014 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +00001015 {
1016 result.AppendMessage ("The following is a list of your current user-defined commands:");
1017 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +00001018 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +00001019 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1020 {
Enrico Granata6b1596d2011-08-16 23:24:13 +00001021 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1022 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +00001023 }
1024 result.AppendMessage("");
1025 }
1026
1027 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1028}
1029
Caroline Ticee0da7a52010-12-09 22:52:49 +00001030CommandObject *
1031CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +00001032{
Caroline Ticee0da7a52010-12-09 22:52:49 +00001033 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1034 // eventually be invoked by the given command line.
1035
1036 CommandObject *cmd_obj = NULL;
1037 std::string white_space (" \t\v");
1038 size_t start = command_string.find_first_not_of (white_space);
1039 size_t end = 0;
1040 bool done = false;
1041 while (!done)
1042 {
1043 if (start != std::string::npos)
1044 {
1045 // Get the next word from command_string.
1046 end = command_string.find_first_of (white_space, start);
1047 if (end == std::string::npos)
1048 end = command_string.size();
1049 std::string cmd_word = command_string.substr (start, end - start);
1050
1051 if (cmd_obj == NULL)
1052 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1053 // command or alias.
1054 cmd_obj = GetCommandObject (cmd_word.c_str());
1055 else if (cmd_obj->IsMultiwordObject ())
1056 {
1057 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
Greg Clayton13193d52012-10-13 02:07:45 +00001058 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001059 if (sub_cmd_obj)
1060 cmd_obj = sub_cmd_obj;
1061 else // cmd_word was not a valid sub-command word, so we are donee
1062 done = true;
1063 }
1064 else
1065 // We have a cmd_obj and it is not a multi-word object, so we are done.
1066 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001067
Caroline Ticee0da7a52010-12-09 22:52:49 +00001068 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1069 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1070 // next word.
1071
1072 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1073 done = true;
1074 else
1075 start = command_string.find_first_not_of (white_space, end);
1076 }
1077 else
1078 // Unable to find any more words.
1079 done = true;
1080 }
1081
1082 if (end == command_string.size())
1083 command_string.clear();
1084 else
1085 command_string = command_string.substr(end);
1086
1087 return cmd_obj;
1088}
1089
Greg Clayton9d855c62011-10-25 00:36:27 +00001090static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +00001091static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +00001092static void
1093StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001094{
Greg Clayton9d855c62011-10-25 00:36:27 +00001095 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001096 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001097 size_t pos = s.find_first_not_of (k_white_space);
1098 if (pos == std::string::npos)
1099 s.clear();
1100 else if (pos == 0)
1101 return;
1102 s.erase (0, pos);
1103 }
1104}
1105
Greg Clayton3840cd72011-11-09 23:25:03 +00001106static size_t
1107FindArgumentTerminator (const std::string &s)
1108{
Greg Clayton3840cd72011-11-09 23:25:03 +00001109 const size_t s_len = s.size();
1110 size_t offset = 0;
1111 while (offset < s_len)
1112 {
1113 size_t pos = s.find ("--", offset);
1114 if (pos == std::string::npos)
1115 break;
1116 if (pos > 0)
1117 {
1118 if (isspace(s[pos-1]))
1119 {
1120 // Check if the string ends "\s--" (where \s is a space character)
1121 // or if we have "\s--\s".
1122 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1123 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001124 return pos;
1125 }
1126 }
1127 }
1128 offset = pos + 2;
1129 }
Greg Clayton3840cd72011-11-09 23:25:03 +00001130 return std::string::npos;
1131}
1132
Greg Clayton9d855c62011-10-25 00:36:27 +00001133static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +00001134ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +00001135{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001136 command.clear();
1137 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +00001138 StripLeadingSpaces (command_string);
1139
1140 bool result = false;
1141 quote_char = '\0';
1142
1143 if (!command_string.empty())
1144 {
1145 const char first_char = command_string[0];
1146 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +00001147 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001148 quote_char = first_char;
1149 const size_t end_quote_pos = command_string.find (quote_char, 1);
1150 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001151 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001152 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001153 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001154 }
1155 else
1156 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001157 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +00001158 if (end_quote_pos + 1 < command_string.size())
1159 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1160 else
1161 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001162 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001163 }
1164 else
1165 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001166 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1167 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001168 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001169 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001170 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +00001171 }
1172 else
1173 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001174 command.assign (command_string, 0, first_space_pos);
1175 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +00001176 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001177 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001178 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001179 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001180
1181
1182 if (!command.empty())
1183 {
1184 // actual commands can't start with '-' or '_'
1185 if (command[0] != '-' && command[0] != '_')
1186 {
1187 size_t pos = command.find_first_not_of(k_valid_command_chars);
1188 if (pos > 0 && pos != std::string::npos)
1189 {
1190 suffix.assign (command.begin() + pos, command.end());
1191 command.erase (pos);
1192 }
1193 }
1194 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001195
1196 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001197}
1198
Greg Clayton7268b4c2011-10-28 21:38:01 +00001199CommandObject *
1200CommandInterpreter::BuildAliasResult (const char *alias_name,
1201 std::string &raw_input_string,
1202 std::string &alias_result,
1203 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001204{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001205 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001206 Args cmd_args (raw_input_string.c_str());
1207 alias_cmd_obj = GetCommandObject (alias_name);
1208 StreamString result_str;
1209
1210 if (alias_cmd_obj)
1211 {
1212 std::string alias_name_str = alias_name;
1213 if ((cmd_args.GetArgumentCount() == 0)
1214 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1215 cmd_args.Unshift (alias_name);
1216
1217 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1218 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1219
1220 if (option_arg_vector_sp.get())
1221 {
1222 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1223
1224 for (int i = 0; i < option_arg_vector->size(); ++i)
1225 {
1226 OptionArgPair option_pair = (*option_arg_vector)[i];
1227 OptionArgValue value_pair = option_pair.second;
1228 int value_type = value_pair.first;
1229 std::string option = option_pair.first;
1230 std::string value = value_pair.second;
1231 if (option.compare ("<argument>") == 0)
1232 result_str.Printf (" %s", value.c_str());
1233 else
1234 {
1235 result_str.Printf (" %s", option.c_str());
1236 if (value_type != optional_argument)
1237 result_str.Printf (" ");
1238 if (value.compare ("<no_argument>") != 0)
1239 {
1240 int index = GetOptionArgumentPosition (value.c_str());
1241 if (index == 0)
1242 result_str.Printf ("%s", value.c_str());
1243 else if (index >= cmd_args.GetArgumentCount())
1244 {
1245
1246 result.AppendErrorWithFormat
1247 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1248 index);
1249 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001250 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001251 }
1252 else
1253 {
1254 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1255 if (strpos != std::string::npos)
1256 raw_input_string = raw_input_string.erase (strpos,
1257 strlen (cmd_args.GetArgumentAtIndex (index)));
1258 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1259 }
1260 }
1261 }
1262 }
1263 }
1264
1265 alias_result = result_str.GetData();
1266 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001267 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001268}
1269
Greg Claytonf5c0c722011-10-14 07:41:33 +00001270Error
1271CommandInterpreter::PreprocessCommand (std::string &command)
1272{
1273 // The command preprocessor needs to do things to the command
1274 // line before any parsing of arguments or anything else is done.
1275 // The only current stuff that gets proprocessed is anyting enclosed
1276 // in backtick ('`') characters is evaluated as an expression and
1277 // the result of the expression must be a scalar that can be substituted
1278 // into the command. An example would be:
1279 // (lldb) memory read `$rsp + 20`
1280 Error error; // Error for any expressions that might not evaluate
1281 size_t start_backtick;
1282 size_t pos = 0;
1283 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1284 {
1285 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1286 {
1287 // The backtick was preceeded by a '\' character, remove the slash
1288 // and don't treat the backtick as the start of an expression
1289 command.erase(start_backtick-1, 1);
1290 // No need to add one to start_backtick since we just deleted a char
1291 pos = start_backtick;
1292 }
1293 else
1294 {
1295 const size_t expr_content_start = start_backtick + 1;
1296 const size_t end_backtick = command.find ('`', expr_content_start);
1297 if (end_backtick == std::string::npos)
1298 return error;
1299 else if (end_backtick == expr_content_start)
1300 {
1301 // Empty expression (two backticks in a row)
1302 command.erase (start_backtick, 2);
1303 }
1304 else
1305 {
1306 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1307
Greg Claytonbcaf99a2012-07-12 20:32:19 +00001308 ExecutionContext exe_ctx(GetExecutionContext());
1309 Target *target = exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001310 // Get a dummy target to allow for calculator mode while processing backticks.
1311 // This also helps break the infinite loop caused when target is null.
1312 if (!target)
1313 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001314 if (target)
1315 {
Greg Claytonf5c0c722011-10-14 07:41:33 +00001316 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad27026e2012-09-05 20:41:26 +00001317
Jim Ingham47beabb2012-10-16 21:41:58 +00001318 EvaluateExpressionOptions options;
Enrico Granatad27026e2012-09-05 20:41:26 +00001319 options.SetCoerceToId(false)
1320 .SetUnwindOnError(true)
1321 .SetKeepInMemory(false)
Jim Ingham47beabb2012-10-16 21:41:58 +00001322 .SetRunOthers(true)
1323 .SetTimeoutUsec(0);
Enrico Granatad27026e2012-09-05 20:41:26 +00001324
Greg Claytonf5c0c722011-10-14 07:41:33 +00001325 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad27026e2012-09-05 20:41:26 +00001326 exe_ctx.GetFramePtr(),
Enrico Granata6cca9692012-07-16 23:10:35 +00001327 expr_result_valobj_sp,
Enrico Granatad27026e2012-09-05 20:41:26 +00001328 options);
1329
Greg Claytonf5c0c722011-10-14 07:41:33 +00001330 if (expr_result == eExecutionCompleted)
1331 {
1332 Scalar scalar;
1333 if (expr_result_valobj_sp->ResolveValue (scalar))
1334 {
1335 command.erase (start_backtick, end_backtick - start_backtick + 1);
1336 StreamString value_strm;
1337 const bool show_type = false;
1338 scalar.GetValue (&value_strm, show_type);
1339 size_t value_string_size = value_strm.GetSize();
1340 if (value_string_size)
1341 {
1342 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1343 pos = start_backtick + value_string_size;
1344 continue;
1345 }
1346 else
1347 {
1348 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1349 }
1350 }
1351 else
1352 {
1353 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1354 }
1355 }
1356 else
1357 {
1358 if (expr_result_valobj_sp)
1359 error = expr_result_valobj_sp->GetError();
1360 if (error.Success())
1361 {
1362
1363 switch (expr_result)
1364 {
1365 case eExecutionSetupError:
1366 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1367 break;
1368 case eExecutionCompleted:
1369 break;
1370 case eExecutionDiscarded:
1371 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1372 break;
1373 case eExecutionInterrupted:
1374 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1375 break;
1376 case eExecutionTimedOut:
1377 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1378 break;
1379 }
1380 }
1381 }
1382 }
1383 }
1384 if (error.Fail())
1385 break;
1386 }
1387 }
1388 return error;
1389}
1390
1391
Caroline Ticee0da7a52010-12-09 22:52:49 +00001392bool
1393CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata01bc2d42012-05-31 01:09:06 +00001394 LazyBool lazy_add_to_history,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001395 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001396 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001397 bool repeat_on_empty_command,
1398 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001399
Caroline Ticee0da7a52010-12-09 22:52:49 +00001400{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001401
Caroline Ticee0da7a52010-12-09 22:52:49 +00001402 bool done = false;
1403 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001404 bool wants_raw_input = false;
1405 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001406 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001407
1408 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001409 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1410
1411 // Make a scoped cleanup object that will clear the crash description string
1412 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001413 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001414
Caroline Ticee0da7a52010-12-09 22:52:49 +00001415 if (log)
1416 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001417
Jim Inghamabab14b2010-11-04 23:08:45 +00001418 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1419
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001420 if (!no_context_switching)
1421 UpdateExecutionContext (override_context);
Enrico Granata01bc2d42012-05-31 01:09:06 +00001422
1423 // <rdar://problem/11328896>
1424 bool add_to_history;
1425 if (lazy_add_to_history == eLazyBoolCalculate)
1426 add_to_history = (m_command_source_depth == 0);
1427 else
1428 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1429
Jim Ingham949d5ac2011-02-18 00:54:25 +00001430 bool empty_command = false;
1431 bool comment_command = false;
1432 if (command_string.empty())
1433 empty_command = true;
1434 else
Chris Lattner24943d22010-06-08 16:52:24 +00001435 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001436 const char *k_space_characters = "\t\n\v\f\r ";
1437
1438 size_t non_space = command_string.find_first_not_of (k_space_characters);
1439 // Check for empty line or comment line (lines whose first
1440 // non-space character is the comment character for this interpreter)
1441 if (non_space == std::string::npos)
1442 empty_command = true;
1443 else if (command_string[non_space] == m_comment_char)
1444 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001445 else if (command_string[non_space] == m_repeat_char)
1446 {
1447 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1448 if (history_string == NULL)
1449 {
1450 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1451 result.SetStatus(eReturnStatusFailed);
1452 return false;
1453 }
1454 add_to_history = false;
1455 command_string = history_string;
1456 original_command_string = history_string;
1457 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001458 }
1459
1460 if (empty_command)
1461 {
1462 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001463 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001464 if (m_command_history.empty())
1465 {
1466 result.AppendError ("empty command");
1467 result.SetStatus(eReturnStatusFailed);
1468 return false;
1469 }
1470 else
1471 {
1472 command_line = m_repeat_command.c_str();
1473 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001474 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001475 if (m_repeat_command.empty())
1476 {
1477 result.AppendErrorWithFormat("No auto repeat.\n");
1478 result.SetStatus (eReturnStatusFailed);
1479 return false;
1480 }
1481 }
1482 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001483 }
1484 else
1485 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001486 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1487 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001488 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001489 }
1490 else if (comment_command)
1491 {
1492 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1493 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001494 }
Caroline Tice649116c2011-05-11 16:07:06 +00001495
Greg Claytonf5c0c722011-10-14 07:41:33 +00001496
1497 Error error (PreprocessCommand (command_string));
1498
1499 if (error.Fail())
1500 {
1501 result.AppendError (error.AsCString());
1502 result.SetStatus(eReturnStatusFailed);
1503 return false;
1504 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001505 // Phase 1.
1506
1507 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1508 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1509 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1510 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1511 // 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 +00001512 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001513 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001514
Caroline Ticee0da7a52010-12-09 22:52:49 +00001515 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001516 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001517 std::string next_word;
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001518 StringList matches;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001519 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001520 {
Caroline Tice649116c2011-05-11 16:07:06 +00001521 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001522 std::string suffix;
1523 ExtractCommand (command_string, next_word, suffix, quote_char);
1524 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001525 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001526 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001527 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001528 std::string alias_result;
1529 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1530 revised_command_line.Printf ("%s", alias_result.c_str());
1531 if (cmd_obj)
1532 {
1533 wants_raw_input = cmd_obj->WantsRawCommandString ();
1534 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1535 }
Chris Lattner24943d22010-06-08 16:52:24 +00001536 }
1537 else
1538 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001539 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001540 if (cmd_obj)
1541 {
1542 actual_cmd_name_len += next_word.length();
1543 revised_command_line.Printf ("%s", next_word.c_str());
1544 wants_raw_input = cmd_obj->WantsRawCommandString ();
1545 }
Caroline Tice649116c2011-05-11 16:07:06 +00001546 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001547 {
1548 revised_command_line.Printf ("%s", next_word.c_str());
1549 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001550 }
1551 }
1552 else
1553 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001554 if (cmd_obj->IsMultiwordObject ())
1555 {
Greg Clayton13193d52012-10-13 02:07:45 +00001556 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
Greg Clayton7268b4c2011-10-28 21:38:01 +00001557 if (sub_cmd_obj)
1558 {
1559 actual_cmd_name_len += next_word.length() + 1;
1560 revised_command_line.Printf (" %s", next_word.c_str());
1561 cmd_obj = sub_cmd_obj;
1562 wants_raw_input = cmd_obj->WantsRawCommandString ();
1563 }
1564 else
1565 {
1566 if (quote_char)
1567 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1568 else
1569 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1570 done = true;
1571 }
1572 }
Caroline Tice649116c2011-05-11 16:07:06 +00001573 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001574 {
1575 if (quote_char)
1576 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1577 else
1578 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1579 done = true;
1580 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001581 }
1582
1583 if (cmd_obj == NULL)
1584 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001585 uint32_t num_matches = matches.GetSize();
1586 if (matches.GetSize() > 1) {
1587 std::string error_msg;
1588 error_msg.assign ("Ambiguous command '");
1589 error_msg.append(next_word.c_str());
1590 error_msg.append ("'.");
1591
1592 error_msg.append (" Possible matches:");
1593
1594 for (uint32_t i = 0; i < num_matches; ++i) {
1595 error_msg.append ("\n\t");
1596 error_msg.append (matches.GetStringAtIndex(i));
1597 }
1598 error_msg.append ("\n");
1599 result.AppendRawError (error_msg.c_str(), error_msg.size());
1600 } else {
1601 // We didn't have only one match, otherwise we wouldn't get here.
1602 assert(num_matches == 0);
1603 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1604 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001605 result.SetStatus (eReturnStatusFailed);
1606 return false;
1607 }
1608
Greg Clayton7268b4c2011-10-28 21:38:01 +00001609 if (cmd_obj->IsMultiwordObject ())
1610 {
1611 if (!suffix.empty())
1612 {
1613
1614 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1615 next_word.c_str(),
1616 suffix.c_str());
1617 result.SetStatus (eReturnStatusFailed);
1618 return false;
1619 }
1620 }
1621 else
1622 {
1623 // If we found a normal command, we are done
1624 done = true;
1625 if (!suffix.empty())
1626 {
1627 switch (suffix[0])
1628 {
1629 case '/':
1630 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001631 {
1632 Options *command_options = cmd_obj->GetOptions();
1633 if (command_options && command_options->SupportsLongOption("gdb-format"))
1634 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001635 std::string gdb_format_option ("--gdb-format=");
1636 gdb_format_option += (suffix.c_str() + 1);
1637
1638 bool inserted = false;
1639 std::string &cmd = revised_command_line.GetString();
1640 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1641 if (arg_terminator_idx != std::string::npos)
1642 {
1643 // Insert the gdb format option before the "--" that terminates options
1644 gdb_format_option.append(1,' ');
1645 cmd.insert(arg_terminator_idx, gdb_format_option);
1646 inserted = true;
1647 }
1648
1649 if (!inserted)
1650 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1651
1652 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1653 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001654 }
1655 else
1656 {
1657 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1658 cmd_obj->GetCommandName());
1659 result.SetStatus (eReturnStatusFailed);
1660 return false;
1661 }
1662 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001663 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001664
1665 default:
1666 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1667 suffix.c_str());
1668 result.SetStatus (eReturnStatusFailed);
1669 return false;
1670
Greg Clayton7268b4c2011-10-28 21:38:01 +00001671 }
1672 }
1673 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001674 if (command_string.length() == 0)
1675 done = true;
1676
Chris Lattner24943d22010-06-08 16:52:24 +00001677 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001678
Greg Clayton7268b4c2011-10-28 21:38:01 +00001679 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001680 revised_command_line.Printf (" %s", command_string.c_str());
1681
1682 // End of Phase 1.
1683 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1684 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1685 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1686 // wants_raw_input specifies whether the Execute method expects raw input or not.
1687
1688
1689 if (log)
1690 {
1691 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1692 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1693 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1694 }
1695
1696 // Phase 2.
1697 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1698 // CommandObject, with the appropriate arguments.
1699
1700 if (cmd_obj != NULL)
1701 {
1702 if (add_to_history)
1703 {
1704 Args command_args (revised_command_line.GetData());
1705 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1706 if (repeat_command != NULL)
1707 m_repeat_command.assign(repeat_command);
1708 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001709 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001710
Jim Ingham6247dbe2011-07-12 03:12:18 +00001711 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001712 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001713 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001714 }
1715
1716 command_string = revised_command_line.GetData();
1717 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001718 std::string remainder;
1719 if (actual_cmd_name_len < command_string.length())
1720 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1721 // than cmd_obj->GetCommandName(), because name completion
1722 // allows users to enter short versions of the names,
1723 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001724
1725 // Remove any initial spaces
1726 std::string white_space (" \t\v");
1727 size_t pos = remainder.find_first_not_of (white_space);
1728 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001729 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001730
1731 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001732 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001733
Jim Inghamda26bd22012-06-08 21:56:10 +00001734 cmd_obj->Execute (remainder.c_str(), result);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001735 }
1736 else
1737 {
1738 // We didn't find the first command object, so complete the first argument.
1739 Args command_args (revised_command_line.GetData());
1740 StringList matches;
1741 int num_matches;
1742 int cursor_index = 0;
1743 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1744 bool word_complete;
1745 num_matches = HandleCompletionMatches (command_args,
1746 cursor_index,
1747 cursor_char_position,
1748 0,
1749 -1,
1750 word_complete,
1751 matches);
1752
1753 if (num_matches > 0)
1754 {
1755 std::string error_msg;
1756 error_msg.assign ("ambiguous command '");
1757 error_msg.append(command_args.GetArgumentAtIndex(0));
1758 error_msg.append ("'.");
1759
1760 error_msg.append (" Possible completions:");
1761 for (int i = 0; i < num_matches; i++)
1762 {
1763 error_msg.append ("\n\t");
1764 error_msg.append (matches.GetStringAtIndex (i));
1765 }
1766 error_msg.append ("\n");
1767 result.AppendRawError (error_msg.c_str(), error_msg.size());
1768 }
1769 else
1770 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1771
1772 result.SetStatus (eReturnStatusFailed);
1773 }
1774
Jason Molenda24c991c2011-08-25 00:20:04 +00001775 if (log)
1776 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1777
Chris Lattner24943d22010-06-08 16:52:24 +00001778 return result.Succeeded();
1779}
1780
1781int
1782CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1783 int &cursor_index,
1784 int &cursor_char_position,
1785 int match_start_point,
1786 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001787 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001788 StringList &matches)
1789{
1790 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001791 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001792
1793 // For any of the command completions a unique match will be a complete word.
1794 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001795
1796 if (cursor_index == -1)
1797 {
1798 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001799 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001800 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1801 }
1802 else if (cursor_index == 0)
1803 {
1804 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001805 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001806 num_command_matches = matches.GetSize();
1807
1808 if (num_command_matches == 1
1809 && cmd_obj && cmd_obj->IsMultiwordObject()
1810 && matches.GetStringAtIndex(0) != NULL
1811 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1812 {
1813 look_for_subcommand = true;
1814 num_command_matches = 0;
1815 matches.DeleteStringAtIndex(0);
1816 parsed_line.AppendArgument ("");
1817 cursor_index++;
1818 cursor_char_position = 0;
1819 }
1820 }
1821
1822 if (cursor_index > 0 || look_for_subcommand)
1823 {
1824 // We are completing further on into a commands arguments, so find the command and tell it
1825 // to complete the command.
1826 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001827 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001828 if (command_object == NULL)
1829 {
1830 return 0;
1831 }
1832 else
1833 {
1834 parsed_line.Shift();
1835 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001836 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001837 cursor_index,
1838 cursor_char_position,
1839 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001840 max_return_elements,
1841 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001842 matches);
1843 }
1844 }
1845
1846 return num_command_matches;
1847
1848}
1849
1850int
1851CommandInterpreter::HandleCompletion (const char *current_line,
1852 const char *cursor,
1853 const char *last_char,
1854 int match_start_point,
1855 int max_return_elements,
1856 StringList &matches)
1857{
1858 // We parse the argument up to the cursor, so the last argument in parsed_line is
1859 // the one containing the cursor, and the cursor is after the last character.
1860
1861 Args parsed_line(current_line, last_char - current_line);
1862 Args partial_parsed_line(current_line, cursor - current_line);
1863
Jim Ingham6247dbe2011-07-12 03:12:18 +00001864 // Don't complete comments, and if the line we are completing is just the history repeat character,
1865 // substitute the appropriate history line.
1866 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1867 if (first_arg)
1868 {
1869 if (first_arg[0] == m_comment_char)
1870 return 0;
1871 else if (first_arg[0] == m_repeat_char)
1872 {
1873 const char *history_string = FindHistoryString (first_arg);
1874 if (history_string != NULL)
1875 {
1876 matches.Clear();
1877 matches.InsertStringAtIndex(0, history_string);
1878 return -2;
1879 }
1880 else
1881 return 0;
1882
1883 }
1884 }
1885
1886
Chris Lattner24943d22010-06-08 16:52:24 +00001887 int num_args = partial_parsed_line.GetArgumentCount();
1888 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1889 int cursor_char_position;
1890
1891 if (cursor_index == -1)
1892 cursor_char_position = 0;
1893 else
1894 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001895
1896 if (cursor > current_line && cursor[-1] == ' ')
1897 {
1898 // We are just after a space. If we are in an argument, then we will continue
1899 // parsing, but if we are between arguments, then we have to complete whatever the next
1900 // element would be.
1901 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1902 // protected by a quote) then the space will also be in the parsed argument...
1903
1904 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1905 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1906 {
1907 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1908 cursor_index++;
1909 cursor_char_position = 0;
1910 }
1911 }
Chris Lattner24943d22010-06-08 16:52:24 +00001912
1913 int num_command_matches;
1914
1915 matches.Clear();
1916
1917 // Only max_return_elements == -1 is supported at present:
1918 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001919 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001920 num_command_matches = HandleCompletionMatches (parsed_line,
1921 cursor_index,
1922 cursor_char_position,
1923 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001924 max_return_elements,
1925 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001926 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001927
1928 if (num_command_matches <= 0)
1929 return num_command_matches;
1930
1931 if (num_args == 0)
1932 {
1933 // If we got an empty string, insert nothing.
1934 matches.InsertStringAtIndex(0, "");
1935 }
1936 else
1937 {
1938 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1939 // put an empty string in element 0.
1940 std::string command_partial_str;
1941 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001942 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1943 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001944
1945 std::string common_prefix;
1946 matches.LongestCommonPrefix (common_prefix);
1947 int partial_name_len = command_partial_str.size();
1948
1949 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001950 // Only do this if the completer told us this was a complete word, however...
1951 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001952 {
1953 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1954 if (quote_char != '\0')
1955 common_prefix.push_back(quote_char);
1956
1957 common_prefix.push_back(' ');
1958 }
1959 common_prefix.erase (0, partial_name_len);
1960 matches.InsertStringAtIndex(0, common_prefix.c_str());
1961 }
1962 return num_command_matches;
1963}
1964
Chris Lattner24943d22010-06-08 16:52:24 +00001965
1966CommandInterpreter::~CommandInterpreter ()
1967{
1968}
1969
1970const char *
1971CommandInterpreter::GetPrompt ()
1972{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001973 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001974}
1975
1976void
1977CommandInterpreter::SetPrompt (const char *new_prompt)
1978{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001979 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001980}
1981
Jim Ingham5e16ef52010-10-04 19:49:29 +00001982size_t
Greg Clayton58928562011-02-09 01:08:52 +00001983CommandInterpreter::GetConfirmationInputReaderCallback
1984(
1985 void *baton,
1986 InputReader &reader,
1987 lldb::InputReaderAction action,
1988 const char *bytes,
1989 size_t bytes_len
1990)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001991{
Greg Clayton58928562011-02-09 01:08:52 +00001992 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001993 bool *response_ptr = (bool *) baton;
1994
1995 switch (action)
1996 {
1997 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001998 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001999 {
2000 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00002001 {
Greg Clayton58928562011-02-09 01:08:52 +00002002 out_file.Printf ("%s", reader.GetPrompt());
2003 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00002004 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00002005 }
2006 break;
2007
2008 case eInputReaderDeactivate:
2009 break;
2010
2011 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00002012 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00002013 {
Greg Clayton58928562011-02-09 01:08:52 +00002014 out_file.Printf ("%s", reader.GetPrompt());
2015 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00002016 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00002017 break;
Caroline Tice4a348082011-05-02 20:41:46 +00002018
2019 case eInputReaderAsynchronousOutputWritten:
2020 break;
2021
Jim Ingham5e16ef52010-10-04 19:49:29 +00002022 case eInputReaderGotToken:
2023 if (bytes_len == 0)
2024 {
2025 reader.SetIsDone(true);
2026 }
Jim Ingham36fe9912011-11-14 20:02:01 +00002027 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00002028 {
2029 *response_ptr = true;
2030 reader.SetIsDone(true);
2031 }
Jim Ingham36fe9912011-11-14 20:02:01 +00002032 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00002033 {
2034 *response_ptr = false;
2035 reader.SetIsDone(true);
2036 }
2037 else
2038 {
Greg Clayton58928562011-02-09 01:08:52 +00002039 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00002040 {
Jim Ingham26183802011-11-17 01:22:00 +00002041 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00002042 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00002043 }
2044 }
2045 break;
2046
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002047 case eInputReaderInterrupt:
2048 case eInputReaderEndOfFile:
2049 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
2050 reader.SetIsDone (true);
2051 break;
2052
Jim Ingham5e16ef52010-10-04 19:49:29 +00002053 case eInputReaderDone:
2054 break;
2055 }
2056
2057 return bytes_len;
2058
2059}
2060
2061bool
2062CommandInterpreter::Confirm (const char *message, bool default_answer)
2063{
Jim Ingham93057472010-10-04 22:44:14 +00002064 // Check AutoConfirm first:
2065 if (m_debugger.GetAutoConfirm())
2066 return default_answer;
2067
Jim Ingham5e16ef52010-10-04 19:49:29 +00002068 InputReaderSP reader_sp (new InputReader(GetDebugger()));
2069 bool response = default_answer;
2070 if (reader_sp)
2071 {
2072 std::string prompt(message);
2073 prompt.append(": [");
2074 if (default_answer)
2075 prompt.append ("Y/n] ");
2076 else
2077 prompt.append ("y/N] ");
2078
2079 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
2080 &response, // baton
2081 eInputReaderGranularityLine, // token size, to pass to callback function
2082 NULL, // end token
2083 prompt.c_str(), // prompt
2084 true)); // echo input
2085 if (err.Success())
2086 {
2087 GetDebugger().PushInputReader (reader_sp);
2088 }
2089 reader_sp->WaitOnReaderIsDone();
2090 }
2091 return response;
2092}
2093
2094
Chris Lattner24943d22010-06-08 16:52:24 +00002095void
2096CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
2097{
Jim Inghamd40f8a62010-07-06 22:46:59 +00002098 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00002099
Sean Callananb386d822012-08-09 00:50:26 +00002100 if (cmd_obj_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002101 {
2102 CommandObject *cmd_obj = cmd_obj_sp.get();
2103 if (cmd_obj->IsCrossRefObject ())
2104 cmd_obj->AddObject (object_type);
2105 }
2106}
2107
Chris Lattner24943d22010-06-08 16:52:24 +00002108OptionArgVectorSP
2109CommandInterpreter::GetAliasOptions (const char *alias_name)
2110{
2111 OptionArgMap::iterator pos;
2112 OptionArgVectorSP ret_val;
2113
2114 std::string alias (alias_name);
2115
2116 if (HasAliasOptions())
2117 {
2118 pos = m_alias_options.find (alias);
2119 if (pos != m_alias_options.end())
2120 ret_val = pos->second;
2121 }
2122
2123 return ret_val;
2124}
2125
2126void
2127CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2128{
2129 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2130 if (pos != m_alias_options.end())
2131 {
2132 m_alias_options.erase (pos);
2133 }
2134}
2135
2136void
2137CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2138{
2139 m_alias_options[alias_name] = option_arg_vector_sp;
2140}
2141
2142bool
2143CommandInterpreter::HasCommands ()
2144{
2145 return (!m_command_dict.empty());
2146}
2147
2148bool
2149CommandInterpreter::HasAliases ()
2150{
2151 return (!m_alias_dict.empty());
2152}
2153
2154bool
2155CommandInterpreter::HasUserCommands ()
2156{
2157 return (!m_user_dict.empty());
2158}
2159
2160bool
2161CommandInterpreter::HasAliasOptions ()
2162{
2163 return (!m_alias_options.empty());
2164}
2165
Chris Lattner24943d22010-06-08 16:52:24 +00002166void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002167CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2168 const char *alias_name,
2169 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00002170 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002171 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00002172{
2173 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00002174
2175 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00002176
Caroline Tice44c841d2010-12-07 19:58:26 +00002177 // Make sure that the alias name is the 0th element in cmd_args
2178 std::string alias_name_str = alias_name;
2179 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2180 cmd_args.Unshift (alias_name);
2181
2182 Args new_args (alias_cmd_obj->GetCommandName());
2183 if (new_args.GetArgumentCount() == 2)
2184 new_args.Shift();
2185
Chris Lattner24943d22010-06-08 16:52:24 +00002186 if (option_arg_vector_sp.get())
2187 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002188 if (wants_raw_input)
2189 {
2190 // We have a command that both has command options and takes raw input. Make *sure* it has a
2191 // " -- " in the right place in the raw_input_string.
2192 size_t pos = raw_input_string.find(" -- ");
2193 if (pos == std::string::npos)
2194 {
2195 // None found; assume it goes at the beginning of the raw input string
2196 raw_input_string.insert (0, " -- ");
2197 }
2198 }
Chris Lattner24943d22010-06-08 16:52:24 +00002199
2200 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2201 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002202 std::vector<bool> used (old_size + 1, false);
2203
2204 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002205
2206 for (int i = 0; i < option_arg_vector->size(); ++i)
2207 {
2208 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00002209 OptionArgValue value_pair = option_pair.second;
2210 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00002211 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00002212 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00002213 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002214 {
2215 if (!wants_raw_input
2216 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2217 new_args.AppendArgument (value.c_str());
2218 }
Chris Lattner24943d22010-06-08 16:52:24 +00002219 else
2220 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002221 if (value_type != optional_argument)
2222 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002223 if (value.compare ("<no-argument>") != 0)
2224 {
2225 int index = GetOptionArgumentPosition (value.c_str());
2226 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002227 {
Chris Lattner24943d22010-06-08 16:52:24 +00002228 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002229 if (value_type != optional_argument)
2230 new_args.AppendArgument (value.c_str());
2231 else
2232 {
2233 char buffer[255];
2234 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2235 new_args.AppendArgument (buffer);
2236 }
2237
2238 }
Chris Lattner24943d22010-06-08 16:52:24 +00002239 else if (index >= cmd_args.GetArgumentCount())
2240 {
2241 result.AppendErrorWithFormat
2242 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2243 index);
2244 result.SetStatus (eReturnStatusFailed);
2245 return;
2246 }
2247 else
2248 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002249 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2250 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2251 if (strpos != std::string::npos)
2252 {
2253 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2254 }
2255
2256 if (value_type != optional_argument)
2257 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2258 else
2259 {
2260 char buffer[255];
2261 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2262 cmd_args.GetArgumentAtIndex (index));
2263 new_args.AppendArgument (buffer);
2264 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002265 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002266 }
2267 }
2268 }
2269 }
2270
2271 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2272 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002273 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002274 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2275 }
2276
2277 cmd_args.Clear();
2278 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2279 }
2280 else
2281 {
2282 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002283 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2284 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2285 // input string.
2286 if (wants_raw_input)
2287 {
2288 cmd_args.Clear();
2289 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2290 }
Chris Lattner24943d22010-06-08 16:52:24 +00002291 return;
2292 }
2293
2294 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2295 return;
2296}
2297
2298
2299int
2300CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2301{
2302 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2303 // of zero.
2304
2305 char *cptr = (char *) in_string;
2306
2307 // Does it start with '%'
2308 if (cptr[0] == '%')
2309 {
2310 ++cptr;
2311
2312 // Is the rest of it entirely digits?
2313 if (isdigit (cptr[0]))
2314 {
2315 const char *start = cptr;
2316 while (isdigit (cptr[0]))
2317 ++cptr;
2318
2319 // We've gotten to the end of the digits; are we at the end of the string?
2320 if (cptr[0] == '\0')
2321 position = atoi (start);
2322 }
2323 }
2324
2325 return position;
2326}
2327
2328void
2329CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2330{
Jim Ingham574c3d62011-08-12 23:34:31 +00002331 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002332 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002333 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002334 // In the current working directory we don't load any program specific
2335 // .lldbinit files, we only look for a "./.lldbinit" file.
2336 if (m_skip_lldbinit_files)
2337 return;
2338
2339 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002340 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002341 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002342 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002343 // If we aren't looking in the current working directory we are looking
2344 // in the home directory. We will first see if there is an application
2345 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2346 // "-" and the name of the program. If this file doesn't exist, we fall
2347 // back to just the "~/.lldbinit" file. We also obey any requests to not
2348 // load the init files.
2349 const char *init_file_path = "~/.lldbinit";
2350
2351 if (m_skip_app_init_files == false)
2352 {
2353 FileSpec program_file_spec (Host::GetProgramFileSpec());
2354 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002355
Greg Claytond6edcb52011-09-11 00:01:44 +00002356 if (program_name)
2357 {
2358 char program_init_file_name[PATH_MAX];
2359 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2360 init_file.SetFile (program_init_file_name, true);
2361 if (!init_file.Exists())
2362 init_file.Clear();
2363 }
2364 }
2365
2366 if (!init_file && !m_skip_lldbinit_files)
2367 init_file.SetFile (init_file_path, true);
2368 }
2369
Chris Lattner24943d22010-06-08 16:52:24 +00002370 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2371 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2372
2373 if (init_file.Exists())
2374 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002375 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2376 bool stop_on_continue = true;
2377 bool stop_on_error = false;
2378 bool echo_commands = false;
2379 bool print_results = false;
2380
Enrico Granata01bc2d42012-05-31 01:09:06 +00002381 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002382 }
2383 else
2384 {
2385 // nothing to be done if the file doesn't exist
2386 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2387 }
2388}
2389
Greg Claytonb72d0f02011-04-12 05:54:46 +00002390PlatformSP
2391CommandInterpreter::GetPlatform (bool prefer_target_platform)
2392{
2393 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002394 if (prefer_target_platform)
2395 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002396 ExecutionContext exe_ctx(GetExecutionContext());
2397 Target *target = exe_ctx.GetTargetPtr();
Greg Clayton567e7f32011-09-22 04:58:26 +00002398 if (target)
2399 platform_sp = target->GetPlatform();
2400 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002401
2402 if (!platform_sp)
2403 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2404 return platform_sp;
2405}
2406
Jim Ingham949d5ac2011-02-18 00:54:25 +00002407void
Jim Inghama4fede32011-03-11 01:51:49 +00002408CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002409 ExecutionContext *override_context,
2410 bool stop_on_continue,
2411 bool stop_on_error,
2412 bool echo_commands,
2413 bool print_results,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002414 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002415 CommandReturnObject &result)
2416{
2417 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002418
2419 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2420 // Make sure you reset this value anywhere you return from the function.
2421
2422 bool old_async_execution = m_debugger.GetAsyncExecution();
2423
2424 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2425 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2426
2427 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002428 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002429
2430 if (!stop_on_continue)
2431 {
2432 m_debugger.SetAsyncExecution (false);
2433 }
2434
2435 for (int idx = 0; idx < num_lines; idx++)
2436 {
2437 const char *cmd = commands.GetStringAtIndex(idx);
2438 if (cmd[0] == '\0')
2439 continue;
2440
Jim Ingham949d5ac2011-02-18 00:54:25 +00002441 if (echo_commands)
2442 {
2443 result.AppendMessageWithFormat ("%s %s\n",
2444 GetPrompt(),
2445 cmd);
2446 }
2447
Greg Claytonaa378b12011-02-20 02:15:07 +00002448 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002449 // If override_context is not NULL, pass no_context_switching = true for
2450 // HandleCommand() since we updated our context already.
Enrico Granata01bc2d42012-05-31 01:09:06 +00002451 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002452 NULL, /* override_context */
2453 true, /* repeat_on_empty_command */
2454 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002455
2456 if (print_results)
2457 {
2458 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002459 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002460 }
2461
2462 if (!success || !tmp_result.Succeeded())
2463 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002464 const char *error_msg = tmp_result.GetErrorData();
2465 if (error_msg == NULL || error_msg[0] == '\0')
2466 error_msg = "<unknown error>.\n";
Jim Ingham949d5ac2011-02-18 00:54:25 +00002467 if (stop_on_error)
2468 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002469 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2470 idx, cmd, error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002471 result.SetStatus (eReturnStatusFailed);
2472 m_debugger.SetAsyncExecution (old_async_execution);
2473 return;
2474 }
2475 else if (print_results)
2476 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002477 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Ingham949d5ac2011-02-18 00:54:25 +00002478 idx + 1,
2479 cmd,
Jim Ingham862fd5c2012-04-24 02:25:07 +00002480 error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002481 }
2482 }
2483
Caroline Tice4a348082011-05-02 20:41:46 +00002484 if (result.GetImmediateOutputStream())
2485 result.GetImmediateOutputStream()->Flush();
2486
2487 if (result.GetImmediateErrorStream())
2488 result.GetImmediateErrorStream()->Flush();
2489
Jim Ingham949d5ac2011-02-18 00:54:25 +00002490 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2491 // could be running (for instance in Breakpoint Commands.
2492 // So we check the return value to see if it is has running in it.
2493 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2494 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2495 {
2496 if (stop_on_continue)
2497 {
2498 // If we caused the target to proceed, and we're going to stop in that case, set the
2499 // status in our real result before returning. This is an error if the continue was not the
2500 // last command in the set of commands to be run.
2501 if (idx != num_lines - 1)
2502 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2503 idx + 1, cmd);
2504 else
2505 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2506
2507 result.SetStatus(tmp_result.GetStatus());
2508 m_debugger.SetAsyncExecution (old_async_execution);
2509
2510 return;
2511 }
2512 }
2513
2514 }
2515
2516 result.SetStatus (eReturnStatusSuccessFinishResult);
2517 m_debugger.SetAsyncExecution (old_async_execution);
2518
2519 return;
2520}
2521
2522void
2523CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2524 ExecutionContext *context,
2525 bool stop_on_continue,
2526 bool stop_on_error,
2527 bool echo_command,
2528 bool print_result,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002529 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002530 CommandReturnObject &result)
2531{
2532 if (cmd_file.Exists())
2533 {
2534 bool success;
2535 StringList commands;
2536 success = commands.ReadFileLines(cmd_file);
2537 if (!success)
2538 {
2539 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2540 result.SetStatus (eReturnStatusFailed);
2541 return;
2542 }
Enrico Granata01bc2d42012-05-31 01:09:06 +00002543 m_command_source_depth++;
2544 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2545 m_command_source_depth--;
Jim Ingham949d5ac2011-02-18 00:54:25 +00002546 }
2547 else
2548 {
2549 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2550 cmd_file.GetFilename().AsCString());
2551 result.SetStatus (eReturnStatusFailed);
2552 return;
2553 }
2554}
2555
Chris Lattner24943d22010-06-08 16:52:24 +00002556ScriptInterpreter *
Enrico Granatadb054912012-10-29 21:18:03 +00002557CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner24943d22010-06-08 16:52:24 +00002558{
Enrico Granatadb054912012-10-29 21:18:03 +00002559 if (m_script_interpreter_ap.get() != NULL)
2560 return m_script_interpreter_ap.get();
2561
2562 if (!can_create)
2563 return NULL;
2564
Enrico Granatac5c10a42012-07-10 18:23:48 +00002565 // <rdar://problem/11751427>
2566 // we need to protect the initialization of the script interpreter
2567 // otherwise we could end up with two threads both trying to create
2568 // their instance of it, and for some languages (e.g. Python)
2569 // this is a bulletproof recipe for disaster!
2570 // this needs to be a function-level static because multiple Debugger instances living in the same process
2571 // still need to be isolated and not try to initialize Python concurrently
Enrico Granatab88c0a92012-07-10 19:04:14 +00002572 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2573 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granatac5c10a42012-07-10 18:23:48 +00002574
Enrico Granatadb054912012-10-29 21:18:03 +00002575 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
2576 if (log)
2577 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton63094e02010-06-23 01:19:29 +00002578
Caroline Tice0aa2e552011-01-14 00:29:16 +00002579 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2580 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002581 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002582 case eScriptLanguagePython:
2583#ifndef LLDB_DISABLE_PYTHON
2584 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2585 break;
2586#else
2587 // Fall through to the None case when python is disabled
2588#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002589 case eScriptLanguageNone:
2590 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2591 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002592 };
2593
2594 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002595}
2596
2597
2598
2599bool
2600CommandInterpreter::GetSynchronous ()
2601{
2602 return m_synchronous_execution;
2603}
2604
2605void
2606CommandInterpreter::SetSynchronous (bool value)
2607{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002608 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002609}
2610
2611void
2612CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2613 const char *word_text,
2614 const char *separator,
2615 const char *help_text,
2616 uint32_t max_word_len)
2617{
Greg Clayton238c0a12010-09-18 01:14:36 +00002618 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2619
Chris Lattner24943d22010-06-08 16:52:24 +00002620 int indent_size = max_word_len + strlen (separator) + 2;
2621
2622 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002623
2624 StreamString text_strm;
2625 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2626
2627 size_t len = text_strm.GetSize();
2628 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002629 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002630 {
2631 text_strm.EOL();
2632 len = text_strm.GetSize();
2633 }
Chris Lattner24943d22010-06-08 16:52:24 +00002634
2635 if (len < max_columns)
2636 {
2637 // Output it as a single line.
2638 strm.Printf ("%s", text);
2639 }
2640 else
2641 {
2642 // We need to break it up into multiple lines.
2643 bool first_line = true;
2644 int text_width;
2645 int start = 0;
2646 int end = start;
2647 int final_end = strlen (text);
2648 int sub_len;
2649
2650 while (end < final_end)
2651 {
2652 if (first_line)
2653 text_width = max_columns - 1;
2654 else
2655 text_width = max_columns - indent_size - 1;
2656
2657 // Don't start the 'text' on a space, since we're already outputting the indentation.
2658 if (!first_line)
2659 {
2660 while ((start < final_end) && (text[start] == ' '))
2661 start++;
2662 }
2663
2664 end = start + text_width;
2665 if (end > final_end)
2666 end = final_end;
2667 else
2668 {
2669 // If we're not at the end of the text, make sure we break the line on white space.
2670 while (end > start
2671 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2672 end--;
Greg Clayton73844aa2012-08-22 17:17:09 +00002673 assert (end > 0);
Chris Lattner24943d22010-06-08 16:52:24 +00002674 }
2675
2676 sub_len = end - start;
2677 if (start != 0)
2678 strm.EOL();
2679 if (!first_line)
2680 strm.Indent();
2681 else
2682 first_line = false;
2683 assert (start <= final_end);
2684 assert (start + sub_len <= final_end);
2685 if (sub_len > 0)
2686 strm.Write (text + start, sub_len);
2687 start = end + 1;
2688 }
2689 }
2690 strm.EOL();
2691 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002692}
2693
2694void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002695CommandInterpreter::OutputHelpText (Stream &strm,
2696 const char *word_text,
2697 const char *separator,
2698 const char *help_text,
2699 uint32_t max_word_len)
2700{
2701 int indent_size = max_word_len + strlen (separator) + 2;
2702
2703 strm.IndentMore (indent_size);
2704
2705 StreamString text_strm;
2706 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2707
2708 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata1bba6e52011-07-07 00:38:40 +00002709
2710 size_t len = text_strm.GetSize();
2711 const char *text = text_strm.GetData();
2712
2713 uint32_t chars_left = max_columns;
2714
2715 for (uint32_t i = 0; i < len; i++)
2716 {
2717 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2718 {
Enrico Granata1bba6e52011-07-07 00:38:40 +00002719 chars_left = max_columns - indent_size;
2720 strm.EOL();
2721 strm.Indent();
2722 }
2723 else
2724 {
2725 strm.PutChar(text[i]);
2726 chars_left--;
2727 }
2728
2729 }
2730
2731 strm.EOL();
2732 strm.IndentLess(indent_size);
2733}
2734
2735void
Chris Lattner24943d22010-06-08 16:52:24 +00002736CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2737 StringList &commands_help)
2738{
2739 CommandObject::CommandMap::const_iterator pos;
2740
2741 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2742 {
2743 const char *command_name = pos->first.c_str();
2744 CommandObject *cmd_obj = pos->second.get();
2745
Greg Clayton238c0a12010-09-18 01:14:36 +00002746 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002747 {
2748 commands_found.AppendString (command_name);
2749 commands_help.AppendString (cmd_obj->GetHelp());
2750 }
2751
2752 if (cmd_obj->IsMultiwordObject())
Greg Clayton13193d52012-10-13 02:07:45 +00002753 cmd_obj->AproposAllSubCommands (command_name,
2754 search_word,
2755 commands_found,
2756 commands_help);
Chris Lattner24943d22010-06-08 16:52:24 +00002757
2758 }
2759}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002760
2761
2762void
2763CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2764{
Greg Claytonb72d0f02011-04-12 05:54:46 +00002765 if (override_context != NULL)
2766 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002767 m_exe_ctx_ref = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002768 }
2769 else
2770 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002771 const bool adopt_selected = true;
2772 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002773 }
2774}
2775
Jim Ingham6247dbe2011-07-12 03:12:18 +00002776void
2777CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2778{
2779 DumpHistory (stream, 0, count - 1);
2780}
2781
2782void
2783CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2784{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002785 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2786 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002787 {
2788 if (!m_command_history[i].empty())
2789 {
2790 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002791 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002792 }
2793 }
2794}
2795
2796const char *
2797CommandInterpreter::FindHistoryString (const char *input_str) const
2798{
2799 if (input_str[0] != m_repeat_char)
2800 return NULL;
2801 if (input_str[1] == '-')
2802 {
2803 bool success;
2804 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2805 if (!success)
2806 return NULL;
2807 if (idx > m_command_history.size())
2808 return NULL;
2809 idx = m_command_history.size() - idx;
2810 return m_command_history[idx].c_str();
2811
2812 }
2813 else if (input_str[1] == m_repeat_char)
2814 {
2815 if (m_command_history.empty())
2816 return NULL;
2817 else
2818 return m_command_history.back().c_str();
2819 }
2820 else
2821 {
2822 bool success;
2823 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2824 if (!success)
2825 return NULL;
2826 if (idx >= m_command_history.size())
2827 return NULL;
2828 return m_command_history[idx].c_str();
2829 }
2830}