blob: 7ea69a320cfa1db9fede2b1994dcb690b505da76 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include <string>
Caroline Ticebd5c63e2010-10-12 21:57:09 +000011#include <vector>
Chris Lattner24943d22010-06-08 16:52:24 +000012
13#include <getopt.h>
14#include <stdlib.h>
15
Greg Clayton5c28dd12011-06-23 17:59:56 +000016#include "CommandObjectScript.h"
Peter Collingbourne921fac02011-06-23 20:37:26 +000017#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton5c28dd12011-06-23 17:59:56 +000018
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000019#include "../Commands/CommandObjectApropos.h"
20#include "../Commands/CommandObjectArgs.h"
21#include "../Commands/CommandObjectBreakpoint.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000022#include "../Commands/CommandObjectDisassemble.h"
23#include "../Commands/CommandObjectExpression.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000024#include "../Commands/CommandObjectFrame.h"
25#include "../Commands/CommandObjectHelp.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectLog.h"
27#include "../Commands/CommandObjectMemory.h"
Greg Claytonb1888f22011-03-19 01:12:21 +000028#include "../Commands/CommandObjectPlatform.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000029#include "../Commands/CommandObjectProcess.h"
30#include "../Commands/CommandObjectQuit.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000031#include "../Commands/CommandObjectRegister.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000032#include "../Commands/CommandObjectSettings.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectSource.h"
Jim Ingham767af882010-07-07 03:36:20 +000034#include "../Commands/CommandObjectCommands.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSyntax.h"
36#include "../Commands/CommandObjectTarget.h"
37#include "../Commands/CommandObjectThread.h"
Greg Clayton5c28dd12011-06-23 17:59:56 +000038#include "../Commands/CommandObjectType.h"
Johnny Chen902e0182010-12-23 20:21:44 +000039#include "../Commands/CommandObjectVersion.h"
Johnny Chen01acfa72011-09-22 18:04:58 +000040#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041
Jim Ingham84cdc152010-06-15 19:49:27 +000042#include "lldb/Interpreter/Args.h"
Caroline Tice5ddbe212011-05-06 21:37:15 +000043#include "lldb/Interpreter/Options.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "lldb/Core/Debugger.h"
Jim Ingham5e16ef52010-10-04 19:49:29 +000045#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000046#include "lldb/Core/Stream.h"
47#include "lldb/Core/Timer.h"
Greg Claytoncd548032011-02-01 01:31:41 +000048#include "lldb/Host/Host.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049#include "lldb/Target/Process.h"
50#include "lldb/Target/Thread.h"
51#include "lldb/Target/TargetList.h"
Greg Claytone98ac252010-11-10 04:57:04 +000052#include "lldb/Utility/CleanUp.h"
Chris Lattner24943d22010-06-08 16:52:24 +000053
54#include "lldb/Interpreter/CommandReturnObject.h"
55#include "lldb/Interpreter/CommandInterpreter.h"
Caroline Tice0aa2e552011-01-14 00:29:16 +000056#include "lldb/Interpreter/ScriptInterpreterNone.h"
57#include "lldb/Interpreter/ScriptInterpreterPython.h"
Chris Lattner24943d22010-06-08 16:52:24 +000058
59using namespace lldb;
60using namespace lldb_private;
61
Greg Clayton9f282852012-08-23 00:22:02 +000062
63static PropertyDefinition
64g_properties[] =
65{
66 { "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." },
67 { NULL , OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL }
68};
69
70enum
71{
72 ePropertyExpandRegexAliases = 0
73};
74
Jim Ingham5a15e692012-02-16 06:50:00 +000075ConstString &
76CommandInterpreter::GetStaticBroadcasterClass ()
77{
78 static ConstString class_name ("lldb.commandInterpreter");
79 return class_name;
80}
81
Chris Lattner24943d22010-06-08 16:52:24 +000082CommandInterpreter::CommandInterpreter
83(
Greg Clayton63094e02010-06-23 01:19:29 +000084 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000085 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000086 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000087) :
Jim Ingham5a15e692012-02-16 06:50:00 +000088 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton9f282852012-08-23 00:22:02 +000089 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton63094e02010-06-23 01:19:29 +000090 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000091 m_synchronous_execution (synchronous_execution),
Caroline Tice0aa2e552011-01-14 00:29:16 +000092 m_skip_lldbinit_files (false),
Jim Ingham574c3d62011-08-12 23:34:31 +000093 m_skip_app_init_files (false),
Jim Ingham949d5ac2011-02-18 00:54:25 +000094 m_script_interpreter_ap (),
Caroline Tice892fadd2011-06-16 16:27:19 +000095 m_comment_char ('#'),
Jim Ingham6247dbe2011-07-12 03:12:18 +000096 m_repeat_char ('!'),
Johnny Chen3908bb12012-08-09 22:06:10 +000097 m_batch_command_mode (false),
Enrico Granata01bc2d42012-05-31 01:09:06 +000098 m_truncation_warning(eNoTruncation),
99 m_command_source_depth (0)
Chris Lattner24943d22010-06-08 16:52:24 +0000100{
Greg Clayton73844aa2012-08-22 17:17:09 +0000101 debugger.SetScriptLanguage (script_language);
Greg Clayton49ce6822010-10-31 03:01:06 +0000102 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
103 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton73844aa2012-08-22 17:17:09 +0000104 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham5a15e692012-02-16 06:50:00 +0000105 CheckInWithManager ();
Greg Clayton9f282852012-08-23 00:22:02 +0000106 m_collection_sp->Initialize (g_properties);
Chris Lattner24943d22010-06-08 16:52:24 +0000107}
108
Greg Clayton9f282852012-08-23 00:22:02 +0000109bool
110CommandInterpreter::GetExpandRegexAliases () const
111{
112 const uint32_t idx = ePropertyExpandRegexAliases;
113 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
114}
115
116
117
Chris Lattner24943d22010-06-08 16:52:24 +0000118void
119CommandInterpreter::Initialize ()
120{
121 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
122
123 CommandReturnObject result;
124
125 LoadCommandDictionary ();
126
Chris Lattner24943d22010-06-08 16:52:24 +0000127 // Set up some initial aliases.
Caroline Tice5ddbe212011-05-06 21:37:15 +0000128 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
129 if (cmd_obj_sp)
130 {
131 AddAlias ("q", cmd_obj_sp);
132 AddAlias ("exit", cmd_obj_sp);
133 }
Sean Callananfc58af22012-05-04 23:15:02 +0000134
135 cmd_obj_sp = GetCommandSPExact ("process attach", false);
136 if (cmd_obj_sp)
137 {
138 AddAlias ("attach", cmd_obj_sp);
139 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000140
141 cmd_obj_sp = GetCommandSPExact ("process continue", false);
142 if (cmd_obj_sp)
143 {
144 AddAlias ("c", cmd_obj_sp);
145 AddAlias ("continue", cmd_obj_sp);
146 }
147
148 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
149 if (cmd_obj_sp)
150 AddAlias ("b", cmd_obj_sp);
151
152 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
153 if (cmd_obj_sp)
154 AddAlias ("bt", cmd_obj_sp);
155
156 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
157 if (cmd_obj_sp)
Jason Molenda47eb00e2011-10-22 00:47:41 +0000158 {
159 AddAlias ("stepi", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000160 AddAlias ("si", cmd_obj_sp);
Jason Molenda47eb00e2011-10-22 00:47:41 +0000161 }
162
163 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
164 if (cmd_obj_sp)
165 {
166 AddAlias ("nexti", cmd_obj_sp);
167 AddAlias ("ni", cmd_obj_sp);
168 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000169
170 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
171 if (cmd_obj_sp)
172 {
173 AddAlias ("s", cmd_obj_sp);
174 AddAlias ("step", cmd_obj_sp);
175 }
176
177 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
178 if (cmd_obj_sp)
179 {
180 AddAlias ("n", cmd_obj_sp);
181 AddAlias ("next", cmd_obj_sp);
182 }
183
184 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
185 if (cmd_obj_sp)
186 {
Caroline Tice5ddbe212011-05-06 21:37:15 +0000187 AddAlias ("finish", cmd_obj_sp);
188 }
189
Jim Ingham59355252011-12-02 01:12:59 +0000190 cmd_obj_sp = GetCommandSPExact ("frame select", false);
191 if (cmd_obj_sp)
192 {
193 AddAlias ("f", cmd_obj_sp);
194 }
195
Caroline Tice5ddbe212011-05-06 21:37:15 +0000196 cmd_obj_sp = GetCommandSPExact ("source list", false);
197 if (cmd_obj_sp)
198 {
199 AddAlias ("l", cmd_obj_sp);
200 AddAlias ("list", cmd_obj_sp);
201 }
202
203 cmd_obj_sp = GetCommandSPExact ("memory read", false);
204 if (cmd_obj_sp)
205 AddAlias ("x", cmd_obj_sp);
206
207 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
208 if (cmd_obj_sp)
209 AddAlias ("up", cmd_obj_sp);
210
211 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
212 if (cmd_obj_sp)
213 AddAlias ("down", cmd_obj_sp);
214
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000215 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000216 if (cmd_obj_sp)
217 AddAlias ("display", cmd_obj_sp);
Jim Ingham9d1acc12011-10-24 18:37:00 +0000218
219 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
220 if (cmd_obj_sp)
221 AddAlias ("dis", cmd_obj_sp);
222
223 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
224 if (cmd_obj_sp)
225 AddAlias ("di", cmd_obj_sp);
226
227
Jason Molenda730cae02011-10-22 01:30:52 +0000228
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000229 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000230 if (cmd_obj_sp)
231 AddAlias ("undisplay", cmd_obj_sp);
232
Caroline Tice5ddbe212011-05-06 21:37:15 +0000233 cmd_obj_sp = GetCommandSPExact ("target create", false);
234 if (cmd_obj_sp)
235 AddAlias ("file", cmd_obj_sp);
236
237 cmd_obj_sp = GetCommandSPExact ("target modules", false);
238 if (cmd_obj_sp)
239 AddAlias ("image", cmd_obj_sp);
240
241
242 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000243
Caroline Tice5ddbe212011-05-06 21:37:15 +0000244 cmd_obj_sp = GetCommandSPExact ("expression", false);
245 if (cmd_obj_sp)
246 {
247 AddAlias ("expr", cmd_obj_sp);
248
249 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
250 AddAlias ("p", cmd_obj_sp);
251 AddAlias ("print", cmd_obj_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000252 AddAlias ("call", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000253 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
254 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000255 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000256
257 alias_arguments_vector_sp.reset (new OptionArgVector);
258 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
259 AddAlias ("po", cmd_obj_sp);
260 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
261 }
262
Sean Callananee301fa2012-06-01 23:29:32 +0000263 cmd_obj_sp = GetCommandSPExact ("process kill", false);
264 if (cmd_obj_sp)
265 AddAlias ("kill", cmd_obj_sp);
266
Caroline Tice5ddbe212011-05-06 21:37:15 +0000267 cmd_obj_sp = GetCommandSPExact ("process launch", false);
268 if (cmd_obj_sp)
269 {
270 alias_arguments_vector_sp.reset (new OptionArgVector);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000271#if defined (__arm__)
272 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
273#else
Greg Clayton86c50d72012-05-18 00:04:38 +0000274 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000275#endif
Caroline Tice5ddbe212011-05-06 21:37:15 +0000276 AddAlias ("r", cmd_obj_sp);
277 AddAlias ("run", cmd_obj_sp);
278 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
279 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
280 }
Greg Claytonc84623f2012-03-29 21:47:51 +0000281
282 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
283 if (cmd_obj_sp)
284 {
285 AddAlias ("add-dsym", cmd_obj_sp);
286 }
Sean Callanan7b71b172012-05-21 18:25:19 +0000287
288 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
289 if (cmd_obj_sp)
290 {
291 alias_arguments_vector_sp.reset (new OptionArgVector);
292 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
293 AddAlias ("rb", cmd_obj_sp);
294 AddOrReplaceAliasOptions("rb", alias_arguments_vector_sp);
295 }
Chris Lattner24943d22010-06-08 16:52:24 +0000296}
297
Chris Lattner24943d22010-06-08 16:52:24 +0000298const char *
299CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
300{
301 // This function has not yet been implemented.
302
303 // Look for any embedded script command
304 // If found,
305 // get interpreter object from the command dictionary,
306 // call execute_one_command on it,
307 // get the results as a string,
308 // substitute that string for current stuff.
309
310 return arg;
311}
312
313
314void
315CommandInterpreter::LoadCommandDictionary ()
316{
317 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
318
319 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
320 //
321 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
322 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
323 // the cross-referencing stuff) are created!!!
324 //
325 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
326
327
328 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
329 // are created. This is so that when another command is created that needs to go into a crossref object,
330 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
331 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
332
Chris Lattner24943d22010-06-08 16:52:24 +0000333 // Non-CommandObjectCrossref commands can now be created.
334
Caroline Tice5bc8c972010-09-20 20:44:43 +0000335 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000336
Greg Clayton238c0a12010-09-18 01:14:36 +0000337 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000338 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000339 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000340 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000341 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
342 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000343// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000344 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000345 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000346 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000347 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
348 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000349 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000350 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000351 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000352 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000353 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000354 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000355 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000356 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
357 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000358 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000359 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000360 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000361
362 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000363 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000364 "_regexp-break",
Johnny Chen58edac32012-08-23 00:32:22 +0000365 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
366 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000367 if (break_regex_cmd_ap.get())
368 {
369 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
Johnny Chen58edac32012-08-23 00:32:22 +0000370 break_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000371 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
372 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000373 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000374 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000375 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000376 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
377 {
378 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
379 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
380 }
381 }
Jim Inghame56493f2011-03-22 02:29:32 +0000382
383 std::auto_ptr<CommandObjectRegexCommand>
384 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000385 "_regexp-down",
386 "Go down \"n\" frames in the stack (1 frame by default).",
387 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000388 if (down_regex_cmd_ap.get())
389 {
390 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
391 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
392 {
393 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
394 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
395 }
396 }
397
398 std::auto_ptr<CommandObjectRegexCommand>
399 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000400 "_regexp-up",
401 "Go up \"n\" frames in the stack (1 frame by default).",
402 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000403 if (up_regex_cmd_ap.get())
404 {
405 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
406 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
407 {
408 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
409 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
410 }
411 }
Jason Molenda730cae02011-10-22 01:30:52 +0000412
413 std::auto_ptr<CommandObjectRegexCommand>
414 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000415 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000416 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000417 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000418 if (display_regex_cmd_ap.get())
419 {
420 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
421 {
422 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
423 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
424 }
425 }
426
427 std::auto_ptr<CommandObjectRegexCommand>
428 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000429 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000430 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000431 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000432 if (undisplay_regex_cmd_ap.get())
433 {
434 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
435 {
436 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
437 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
438 }
439 }
440
Chris Lattner24943d22010-06-08 16:52:24 +0000441}
442
443int
444CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
445 StringList &matches)
446{
447 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
448
449 if (include_aliases)
450 {
451 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
452 }
453
454 return matches.GetSize();
455}
456
457CommandObjectSP
458CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
459{
460 CommandObject::CommandMap::iterator pos;
461 CommandObjectSP ret_val;
462
463 std::string cmd(cmd_cstr);
464
465 if (HasCommands())
466 {
467 pos = m_command_dict.find(cmd);
468 if (pos != m_command_dict.end())
469 ret_val = pos->second;
470 }
471
472 if (include_aliases && HasAliases())
473 {
474 pos = m_alias_dict.find(cmd);
475 if (pos != m_alias_dict.end())
476 ret_val = pos->second;
477 }
478
479 if (HasUserCommands())
480 {
481 pos = m_user_dict.find(cmd);
482 if (pos != m_user_dict.end())
483 ret_val = pos->second;
484 }
485
Sean Callananb386d822012-08-09 00:50:26 +0000486 if (!exact && !ret_val)
Chris Lattner24943d22010-06-08 16:52:24 +0000487 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000488 // We will only get into here if we didn't find any exact matches.
489
490 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
491
Chris Lattner24943d22010-06-08 16:52:24 +0000492 StringList local_matches;
493 if (matches == NULL)
494 matches = &local_matches;
495
Jim Inghamd40f8a62010-07-06 22:46:59 +0000496 unsigned int num_cmd_matches = 0;
497 unsigned int num_alias_matches = 0;
498 unsigned int num_user_matches = 0;
499
500 // Look through the command dictionaries one by one, and if we get only one match from any of
501 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
502
Chris Lattner24943d22010-06-08 16:52:24 +0000503 if (HasCommands())
504 {
505 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
506 }
507
508 if (num_cmd_matches == 1)
509 {
510 cmd.assign(matches->GetStringAtIndex(0));
511 pos = m_command_dict.find(cmd);
512 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000513 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000514 }
515
Jim Ingham9a574172010-06-24 20:28:42 +0000516 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000517 {
518 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
519
520 }
521
Jim Inghamd40f8a62010-07-06 22:46:59 +0000522 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000523 {
524 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
525 pos = m_alias_dict.find(cmd);
526 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000527 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000528 }
529
Jim Ingham9a574172010-06-24 20:28:42 +0000530 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000531 {
532 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
533 }
534
Jim Inghamd40f8a62010-07-06 22:46:59 +0000535 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000536 {
537 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
538
539 pos = m_user_dict.find (cmd);
540 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000541 user_match_sp = pos->second;
542 }
543
544 // If we got exactly one match, return that, otherwise return the match list.
545
546 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
547 {
548 if (num_cmd_matches)
549 return real_match_sp;
550 else if (num_alias_matches)
551 return alias_match_sp;
552 else
553 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000554 }
555 }
Sean Callananb386d822012-08-09 00:50:26 +0000556 else if (matches && ret_val)
Jim Inghamd40f8a62010-07-06 22:46:59 +0000557 {
558 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000559 }
560
561
562 return ret_val;
563}
564
Greg Claytond12aeab2011-04-20 16:37:46 +0000565bool
566CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
567{
568 if (name && name[0])
569 {
570 std::string name_sstr(name);
571 if (!can_replace)
572 {
573 if (m_command_dict.find (name_sstr) != m_command_dict.end())
574 return false;
575 }
576 m_command_dict[name_sstr] = cmd_sp;
577 return true;
578 }
579 return false;
580}
581
Enrico Granata6b1596d2011-08-16 23:24:13 +0000582bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000583CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000584 const lldb::CommandObjectSP &cmd_sp,
585 bool can_replace)
586{
Enrico Granata6010ace2011-11-07 22:57:04 +0000587 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000588 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000589
590 const char* name_cstr = name.c_str();
591
592 // do not allow replacement of internal commands
593 if (CommandExists(name_cstr))
594 return false;
595
596 if (can_replace == false && UserCommandExists(name_cstr))
597 return false;
598
599 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000600 return true;
601 }
602 return false;
603}
Greg Claytond12aeab2011-04-20 16:37:46 +0000604
Jim Inghamd40f8a62010-07-06 22:46:59 +0000605CommandObjectSP
606CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000607{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000608 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
609 CommandObjectSP ret_val; // Possibly empty return value.
610
611 if (cmd_cstr == NULL)
612 return ret_val;
613
614 if (cmd_words.GetArgumentCount() == 1)
615 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
616 else
617 {
618 // We have a multi-word command (seemingly), so we need to do more work.
619 // First, get the cmd_obj_sp for the first word in the command.
620 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
621 if (cmd_obj_sp.get() != NULL)
622 {
623 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
624 // command name), and find the appropriate sub-command SP for each command word....
625 size_t end = cmd_words.GetArgumentCount();
626 for (size_t j= 1; j < end; ++j)
627 {
628 if (cmd_obj_sp->IsMultiwordObject())
629 {
630 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
631 (cmd_words.GetArgumentAtIndex (j));
632 if (cmd_obj_sp.get() == NULL)
633 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
634 return ret_val;
635 }
636 else
637 // We have more words in the command name, but we don't have a multiword object. Fail and return
638 // empty 'ret_val'.
639 return ret_val;
640 }
641 // We successfully looped through all the command words and got valid command objects for them. Assign the
642 // last object retrieved to 'ret_val'.
643 ret_val = cmd_obj_sp;
644 }
645 }
646 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000647}
648
649CommandObject *
650CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
651{
652 return GetCommandSPExact (cmd_cstr, include_aliases).get();
653}
654
655CommandObject *
656CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
657{
658 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
659
660 // If we didn't find an exact match to the command string in the commands, look in
661 // the aliases.
662
663 if (command_obj == NULL)
664 {
665 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
666 }
667
668 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
669 // in both the commands and the aliases.
670
671 if (command_obj == NULL)
672 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
673
674 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000675}
676
677bool
678CommandInterpreter::CommandExists (const char *cmd)
679{
680 return m_command_dict.find(cmd) != m_command_dict.end();
681}
682
683bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000684CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
685 const char *options_args,
686 OptionArgVectorSP &option_arg_vector_sp)
687{
688 bool success = true;
689 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
690
691 if (!options_args || (strlen (options_args) < 1))
692 return true;
693
694 std::string options_string (options_args);
695 Args args (options_args);
696 CommandReturnObject result;
697 // Check to see if the command being aliased can take any command options.
698 Options *options = cmd_obj_sp->GetOptions ();
699 if (options)
700 {
701 // See if any options were specified as part of the alias; if so, handle them appropriately.
702 options->NotifyOptionParsingStarting ();
703 args.Unshift ("dummy_arg");
704 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
705 args.Shift ();
706 if (result.Succeeded())
707 options->VerifyPartialOptions (result);
708 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
709 {
710 result.AppendError ("Unable to create requested alias.\n");
711 return false;
712 }
713 }
714
Greg Clayton7268b4c2011-10-28 21:38:01 +0000715 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000716 {
717 if (cmd_obj_sp->WantsRawCommandString ())
718 option_arg_vector->push_back (OptionArgPair ("<argument>",
719 OptionArgValue (-1,
720 options_string)));
721 else
722 {
723 int argc = args.GetArgumentCount();
724 for (size_t i = 0; i < argc; ++i)
725 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
726 option_arg_vector->push_back
727 (OptionArgPair ("<argument>",
728 OptionArgValue (-1,
729 std::string (args.GetArgumentAtIndex (i)))));
730 }
731 }
732
733 return success;
734}
735
736bool
Chris Lattner24943d22010-06-08 16:52:24 +0000737CommandInterpreter::AliasExists (const char *cmd)
738{
739 return m_alias_dict.find(cmd) != m_alias_dict.end();
740}
741
742bool
743CommandInterpreter::UserCommandExists (const char *cmd)
744{
745 return m_user_dict.find(cmd) != m_user_dict.end();
746}
747
748void
749CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
750{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000751 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000752 m_alias_dict[alias_name] = command_obj_sp;
753}
754
755bool
756CommandInterpreter::RemoveAlias (const char *alias_name)
757{
758 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
759 if (pos != m_alias_dict.end())
760 {
761 m_alias_dict.erase(pos);
762 return true;
763 }
764 return false;
765}
766bool
767CommandInterpreter::RemoveUser (const char *alias_name)
768{
769 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
770 if (pos != m_user_dict.end())
771 {
772 m_user_dict.erase(pos);
773 return true;
774 }
775 return false;
776}
777
Chris Lattner24943d22010-06-08 16:52:24 +0000778void
779CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
780{
781 help_string.Printf ("'%s", command_name);
782 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
783
Sean Callananb386d822012-08-09 00:50:26 +0000784 if (option_arg_vector_sp)
Chris Lattner24943d22010-06-08 16:52:24 +0000785 {
786 OptionArgVector *options = option_arg_vector_sp.get();
787 for (int i = 0; i < options->size(); ++i)
788 {
789 OptionArgPair cur_option = (*options)[i];
790 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000791 OptionArgValue value_pair = cur_option.second;
792 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000793 if (opt.compare("<argument>") == 0)
794 {
795 help_string.Printf (" %s", value.c_str());
796 }
797 else
798 {
799 help_string.Printf (" %s", opt.c_str());
800 if ((value.compare ("<no-argument>") != 0)
801 && (value.compare ("<need-argument") != 0))
802 {
803 help_string.Printf (" %s", value.c_str());
804 }
805 }
806 }
807 }
808
809 help_string.Printf ("'");
810}
811
Greg Clayton65124ea2010-08-26 22:05:43 +0000812size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000813CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
814{
815 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000816 CommandObject::CommandMap::const_iterator end = dict.end();
817 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000818
Greg Clayton65124ea2010-08-26 22:05:43 +0000819 for (pos = dict.begin(); pos != end; ++pos)
820 {
821 size_t len = pos->first.size();
822 if (max_len < len)
823 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000824 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000825 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000826}
827
828void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000829CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000830 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000831{
832 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000833 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000834
835 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000836 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000837
838 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
839 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000840
Enrico Granata6b1596d2011-08-16 23:24:13 +0000841 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
842 {
843 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
844 max_len);
845 }
846 result.AppendMessage("");
847
848 }
849
Greg Clayton7268b4c2011-10-28 21:38:01 +0000850 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000851 {
Jim Inghame3663e82010-10-22 18:47:16 +0000852 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000853 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000854 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000855 max_len = FindLongestCommandWord (m_alias_dict);
856
Chris Lattner24943d22010-06-08 16:52:24 +0000857 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
858 {
859 StreamString sstr;
860 StreamString translation_and_help;
861 std::string entry_name = pos->first;
862 std::string second_entry = pos->second.get()->GetCommandName();
863 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
864
865 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
866 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
867 translation_and_help.GetData(), max_len);
868 }
869 result.AppendMessage("");
870 }
871
Greg Clayton7268b4c2011-10-28 21:38:01 +0000872 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000873 {
874 result.AppendMessage ("The following is a list of your current user-defined commands:");
875 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000876 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000877 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
878 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000879 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
880 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000881 }
882 result.AppendMessage("");
883 }
884
885 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
886}
887
Caroline Ticee0da7a52010-12-09 22:52:49 +0000888CommandObject *
889CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000890{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000891 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
892 // eventually be invoked by the given command line.
893
894 CommandObject *cmd_obj = NULL;
895 std::string white_space (" \t\v");
896 size_t start = command_string.find_first_not_of (white_space);
897 size_t end = 0;
898 bool done = false;
899 while (!done)
900 {
901 if (start != std::string::npos)
902 {
903 // Get the next word from command_string.
904 end = command_string.find_first_of (white_space, start);
905 if (end == std::string::npos)
906 end = command_string.size();
907 std::string cmd_word = command_string.substr (start, end - start);
908
909 if (cmd_obj == NULL)
910 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
911 // command or alias.
912 cmd_obj = GetCommandObject (cmd_word.c_str());
913 else if (cmd_obj->IsMultiwordObject ())
914 {
915 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
916 CommandObject *sub_cmd_obj =
917 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
918 if (sub_cmd_obj)
919 cmd_obj = sub_cmd_obj;
920 else // cmd_word was not a valid sub-command word, so we are donee
921 done = true;
922 }
923 else
924 // We have a cmd_obj and it is not a multi-word object, so we are done.
925 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000926
Caroline Ticee0da7a52010-12-09 22:52:49 +0000927 // If we didn't find a valid command object, or our command object is not a multi-word object, or
928 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
929 // next word.
930
931 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
932 done = true;
933 else
934 start = command_string.find_first_not_of (white_space, end);
935 }
936 else
937 // Unable to find any more words.
938 done = true;
939 }
940
941 if (end == command_string.size())
942 command_string.clear();
943 else
944 command_string = command_string.substr(end);
945
946 return cmd_obj;
947}
948
Greg Clayton9d855c62011-10-25 00:36:27 +0000949static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +0000950static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +0000951static void
952StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000953{
Greg Clayton9d855c62011-10-25 00:36:27 +0000954 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +0000955 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000956 size_t pos = s.find_first_not_of (k_white_space);
957 if (pos == std::string::npos)
958 s.clear();
959 else if (pos == 0)
960 return;
961 s.erase (0, pos);
962 }
963}
964
Greg Clayton3840cd72011-11-09 23:25:03 +0000965static size_t
966FindArgumentTerminator (const std::string &s)
967{
Greg Clayton3840cd72011-11-09 23:25:03 +0000968 const size_t s_len = s.size();
969 size_t offset = 0;
970 while (offset < s_len)
971 {
972 size_t pos = s.find ("--", offset);
973 if (pos == std::string::npos)
974 break;
975 if (pos > 0)
976 {
977 if (isspace(s[pos-1]))
978 {
979 // Check if the string ends "\s--" (where \s is a space character)
980 // or if we have "\s--\s".
981 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
982 {
Greg Clayton3840cd72011-11-09 23:25:03 +0000983 return pos;
984 }
985 }
986 }
987 offset = pos + 2;
988 }
Greg Clayton3840cd72011-11-09 23:25:03 +0000989 return std::string::npos;
990}
991
Greg Clayton9d855c62011-10-25 00:36:27 +0000992static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +0000993ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +0000994{
Greg Clayton7268b4c2011-10-28 21:38:01 +0000995 command.clear();
996 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +0000997 StripLeadingSpaces (command_string);
998
999 bool result = false;
1000 quote_char = '\0';
1001
1002 if (!command_string.empty())
1003 {
1004 const char first_char = command_string[0];
1005 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +00001006 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001007 quote_char = first_char;
1008 const size_t end_quote_pos = command_string.find (quote_char, 1);
1009 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001010 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001011 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001012 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001013 }
1014 else
1015 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001016 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +00001017 if (end_quote_pos + 1 < command_string.size())
1018 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1019 else
1020 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001021 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001022 }
1023 else
1024 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001025 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1026 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001027 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001028 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001029 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +00001030 }
1031 else
1032 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001033 command.assign (command_string, 0, first_space_pos);
1034 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +00001035 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001036 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001037 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001038 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001039
1040
1041 if (!command.empty())
1042 {
1043 // actual commands can't start with '-' or '_'
1044 if (command[0] != '-' && command[0] != '_')
1045 {
1046 size_t pos = command.find_first_not_of(k_valid_command_chars);
1047 if (pos > 0 && pos != std::string::npos)
1048 {
1049 suffix.assign (command.begin() + pos, command.end());
1050 command.erase (pos);
1051 }
1052 }
1053 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001054
1055 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001056}
1057
Greg Clayton7268b4c2011-10-28 21:38:01 +00001058CommandObject *
1059CommandInterpreter::BuildAliasResult (const char *alias_name,
1060 std::string &raw_input_string,
1061 std::string &alias_result,
1062 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001063{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001064 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001065 Args cmd_args (raw_input_string.c_str());
1066 alias_cmd_obj = GetCommandObject (alias_name);
1067 StreamString result_str;
1068
1069 if (alias_cmd_obj)
1070 {
1071 std::string alias_name_str = alias_name;
1072 if ((cmd_args.GetArgumentCount() == 0)
1073 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1074 cmd_args.Unshift (alias_name);
1075
1076 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1077 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1078
1079 if (option_arg_vector_sp.get())
1080 {
1081 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1082
1083 for (int i = 0; i < option_arg_vector->size(); ++i)
1084 {
1085 OptionArgPair option_pair = (*option_arg_vector)[i];
1086 OptionArgValue value_pair = option_pair.second;
1087 int value_type = value_pair.first;
1088 std::string option = option_pair.first;
1089 std::string value = value_pair.second;
1090 if (option.compare ("<argument>") == 0)
1091 result_str.Printf (" %s", value.c_str());
1092 else
1093 {
1094 result_str.Printf (" %s", option.c_str());
1095 if (value_type != optional_argument)
1096 result_str.Printf (" ");
1097 if (value.compare ("<no_argument>") != 0)
1098 {
1099 int index = GetOptionArgumentPosition (value.c_str());
1100 if (index == 0)
1101 result_str.Printf ("%s", value.c_str());
1102 else if (index >= cmd_args.GetArgumentCount())
1103 {
1104
1105 result.AppendErrorWithFormat
1106 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1107 index);
1108 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001109 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001110 }
1111 else
1112 {
1113 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1114 if (strpos != std::string::npos)
1115 raw_input_string = raw_input_string.erase (strpos,
1116 strlen (cmd_args.GetArgumentAtIndex (index)));
1117 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1118 }
1119 }
1120 }
1121 }
1122 }
1123
1124 alias_result = result_str.GetData();
1125 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001126 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001127}
1128
Greg Claytonf5c0c722011-10-14 07:41:33 +00001129Error
1130CommandInterpreter::PreprocessCommand (std::string &command)
1131{
1132 // The command preprocessor needs to do things to the command
1133 // line before any parsing of arguments or anything else is done.
1134 // The only current stuff that gets proprocessed is anyting enclosed
1135 // in backtick ('`') characters is evaluated as an expression and
1136 // the result of the expression must be a scalar that can be substituted
1137 // into the command. An example would be:
1138 // (lldb) memory read `$rsp + 20`
1139 Error error; // Error for any expressions that might not evaluate
1140 size_t start_backtick;
1141 size_t pos = 0;
1142 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1143 {
1144 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1145 {
1146 // The backtick was preceeded by a '\' character, remove the slash
1147 // and don't treat the backtick as the start of an expression
1148 command.erase(start_backtick-1, 1);
1149 // No need to add one to start_backtick since we just deleted a char
1150 pos = start_backtick;
1151 }
1152 else
1153 {
1154 const size_t expr_content_start = start_backtick + 1;
1155 const size_t end_backtick = command.find ('`', expr_content_start);
1156 if (end_backtick == std::string::npos)
1157 return error;
1158 else if (end_backtick == expr_content_start)
1159 {
1160 // Empty expression (two backticks in a row)
1161 command.erase (start_backtick, 2);
1162 }
1163 else
1164 {
1165 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1166
Greg Claytonbcaf99a2012-07-12 20:32:19 +00001167 ExecutionContext exe_ctx(GetExecutionContext());
1168 Target *target = exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001169 // Get a dummy target to allow for calculator mode while processing backticks.
1170 // This also helps break the infinite loop caused when target is null.
1171 if (!target)
1172 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001173 if (target)
1174 {
Sean Callanandaa6efe2011-12-21 22:22:58 +00001175 const bool coerce_to_id = false;
Greg Claytonf5c0c722011-10-14 07:41:33 +00001176 const bool unwind_on_error = true;
1177 const bool keep_in_memory = false;
1178 ValueObjectSP expr_result_valobj_sp;
1179 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Greg Claytonbcaf99a2012-07-12 20:32:19 +00001180 exe_ctx.GetFramePtr(),
Greg Claytonf5c0c722011-10-14 07:41:33 +00001181 eExecutionPolicyOnlyWhenNeeded,
Sean Callanandaa6efe2011-12-21 22:22:58 +00001182 coerce_to_id,
1183 unwind_on_error,
1184 keep_in_memory,
Greg Claytonf5c0c722011-10-14 07:41:33 +00001185 eNoDynamicValues,
Enrico Granata6cca9692012-07-16 23:10:35 +00001186 expr_result_valobj_sp,
1187 0 /* no timeout */);
Greg Claytonf5c0c722011-10-14 07:41:33 +00001188 if (expr_result == eExecutionCompleted)
1189 {
1190 Scalar scalar;
1191 if (expr_result_valobj_sp->ResolveValue (scalar))
1192 {
1193 command.erase (start_backtick, end_backtick - start_backtick + 1);
1194 StreamString value_strm;
1195 const bool show_type = false;
1196 scalar.GetValue (&value_strm, show_type);
1197 size_t value_string_size = value_strm.GetSize();
1198 if (value_string_size)
1199 {
1200 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1201 pos = start_backtick + value_string_size;
1202 continue;
1203 }
1204 else
1205 {
1206 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1207 }
1208 }
1209 else
1210 {
1211 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1212 }
1213 }
1214 else
1215 {
1216 if (expr_result_valobj_sp)
1217 error = expr_result_valobj_sp->GetError();
1218 if (error.Success())
1219 {
1220
1221 switch (expr_result)
1222 {
1223 case eExecutionSetupError:
1224 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1225 break;
1226 case eExecutionCompleted:
1227 break;
1228 case eExecutionDiscarded:
1229 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1230 break;
1231 case eExecutionInterrupted:
1232 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1233 break;
1234 case eExecutionTimedOut:
1235 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1236 break;
1237 }
1238 }
1239 }
1240 }
1241 }
1242 if (error.Fail())
1243 break;
1244 }
1245 }
1246 return error;
1247}
1248
1249
Caroline Ticee0da7a52010-12-09 22:52:49 +00001250bool
1251CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata01bc2d42012-05-31 01:09:06 +00001252 LazyBool lazy_add_to_history,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001253 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001254 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001255 bool repeat_on_empty_command,
1256 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001257
Caroline Ticee0da7a52010-12-09 22:52:49 +00001258{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001259
Caroline Ticee0da7a52010-12-09 22:52:49 +00001260 bool done = false;
1261 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001262 bool wants_raw_input = false;
1263 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001264 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001265
1266 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001267 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1268
1269 // Make a scoped cleanup object that will clear the crash description string
1270 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001271 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001272
Caroline Ticee0da7a52010-12-09 22:52:49 +00001273 if (log)
1274 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001275
Jim Inghamabab14b2010-11-04 23:08:45 +00001276 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1277
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001278 if (!no_context_switching)
1279 UpdateExecutionContext (override_context);
Enrico Granata01bc2d42012-05-31 01:09:06 +00001280
1281 // <rdar://problem/11328896>
1282 bool add_to_history;
1283 if (lazy_add_to_history == eLazyBoolCalculate)
1284 add_to_history = (m_command_source_depth == 0);
1285 else
1286 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1287
Jim Ingham949d5ac2011-02-18 00:54:25 +00001288 bool empty_command = false;
1289 bool comment_command = false;
1290 if (command_string.empty())
1291 empty_command = true;
1292 else
Chris Lattner24943d22010-06-08 16:52:24 +00001293 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001294 const char *k_space_characters = "\t\n\v\f\r ";
1295
1296 size_t non_space = command_string.find_first_not_of (k_space_characters);
1297 // Check for empty line or comment line (lines whose first
1298 // non-space character is the comment character for this interpreter)
1299 if (non_space == std::string::npos)
1300 empty_command = true;
1301 else if (command_string[non_space] == m_comment_char)
1302 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001303 else if (command_string[non_space] == m_repeat_char)
1304 {
1305 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1306 if (history_string == NULL)
1307 {
1308 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1309 result.SetStatus(eReturnStatusFailed);
1310 return false;
1311 }
1312 add_to_history = false;
1313 command_string = history_string;
1314 original_command_string = history_string;
1315 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001316 }
1317
1318 if (empty_command)
1319 {
1320 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001321 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001322 if (m_command_history.empty())
1323 {
1324 result.AppendError ("empty command");
1325 result.SetStatus(eReturnStatusFailed);
1326 return false;
1327 }
1328 else
1329 {
1330 command_line = m_repeat_command.c_str();
1331 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001332 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001333 if (m_repeat_command.empty())
1334 {
1335 result.AppendErrorWithFormat("No auto repeat.\n");
1336 result.SetStatus (eReturnStatusFailed);
1337 return false;
1338 }
1339 }
1340 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001341 }
1342 else
1343 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001344 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1345 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001346 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001347 }
1348 else if (comment_command)
1349 {
1350 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1351 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001352 }
Caroline Tice649116c2011-05-11 16:07:06 +00001353
Greg Claytonf5c0c722011-10-14 07:41:33 +00001354
1355 Error error (PreprocessCommand (command_string));
1356
1357 if (error.Fail())
1358 {
1359 result.AppendError (error.AsCString());
1360 result.SetStatus(eReturnStatusFailed);
1361 return false;
1362 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001363 // Phase 1.
1364
1365 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1366 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1367 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1368 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1369 // 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 +00001370 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001371 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001372
Caroline Ticee0da7a52010-12-09 22:52:49 +00001373 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001374 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001375 std::string next_word;
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001376 StringList matches;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001377 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001378 {
Caroline Tice649116c2011-05-11 16:07:06 +00001379 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001380 std::string suffix;
1381 ExtractCommand (command_string, next_word, suffix, quote_char);
1382 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001383 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001384 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001385 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001386 std::string alias_result;
1387 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1388 revised_command_line.Printf ("%s", alias_result.c_str());
1389 if (cmd_obj)
1390 {
1391 wants_raw_input = cmd_obj->WantsRawCommandString ();
1392 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1393 }
Chris Lattner24943d22010-06-08 16:52:24 +00001394 }
1395 else
1396 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001397 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001398 if (cmd_obj)
1399 {
1400 actual_cmd_name_len += next_word.length();
1401 revised_command_line.Printf ("%s", next_word.c_str());
1402 wants_raw_input = cmd_obj->WantsRawCommandString ();
1403 }
Caroline Tice649116c2011-05-11 16:07:06 +00001404 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001405 {
1406 revised_command_line.Printf ("%s", next_word.c_str());
1407 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001408 }
1409 }
1410 else
1411 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001412 if (cmd_obj->IsMultiwordObject ())
1413 {
1414 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1415 if (sub_cmd_obj)
1416 {
1417 actual_cmd_name_len += next_word.length() + 1;
1418 revised_command_line.Printf (" %s", next_word.c_str());
1419 cmd_obj = sub_cmd_obj;
1420 wants_raw_input = cmd_obj->WantsRawCommandString ();
1421 }
1422 else
1423 {
1424 if (quote_char)
1425 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1426 else
1427 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1428 done = true;
1429 }
1430 }
Caroline Tice649116c2011-05-11 16:07:06 +00001431 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001432 {
1433 if (quote_char)
1434 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1435 else
1436 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1437 done = true;
1438 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001439 }
1440
1441 if (cmd_obj == NULL)
1442 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001443 uint32_t num_matches = matches.GetSize();
1444 if (matches.GetSize() > 1) {
1445 std::string error_msg;
1446 error_msg.assign ("Ambiguous command '");
1447 error_msg.append(next_word.c_str());
1448 error_msg.append ("'.");
1449
1450 error_msg.append (" Possible matches:");
1451
1452 for (uint32_t i = 0; i < num_matches; ++i) {
1453 error_msg.append ("\n\t");
1454 error_msg.append (matches.GetStringAtIndex(i));
1455 }
1456 error_msg.append ("\n");
1457 result.AppendRawError (error_msg.c_str(), error_msg.size());
1458 } else {
1459 // We didn't have only one match, otherwise we wouldn't get here.
1460 assert(num_matches == 0);
1461 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1462 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001463 result.SetStatus (eReturnStatusFailed);
1464 return false;
1465 }
1466
Greg Clayton7268b4c2011-10-28 21:38:01 +00001467 if (cmd_obj->IsMultiwordObject ())
1468 {
1469 if (!suffix.empty())
1470 {
1471
1472 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1473 next_word.c_str(),
1474 suffix.c_str());
1475 result.SetStatus (eReturnStatusFailed);
1476 return false;
1477 }
1478 }
1479 else
1480 {
1481 // If we found a normal command, we are done
1482 done = true;
1483 if (!suffix.empty())
1484 {
1485 switch (suffix[0])
1486 {
1487 case '/':
1488 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001489 {
1490 Options *command_options = cmd_obj->GetOptions();
1491 if (command_options && command_options->SupportsLongOption("gdb-format"))
1492 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001493 std::string gdb_format_option ("--gdb-format=");
1494 gdb_format_option += (suffix.c_str() + 1);
1495
1496 bool inserted = false;
1497 std::string &cmd = revised_command_line.GetString();
1498 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1499 if (arg_terminator_idx != std::string::npos)
1500 {
1501 // Insert the gdb format option before the "--" that terminates options
1502 gdb_format_option.append(1,' ');
1503 cmd.insert(arg_terminator_idx, gdb_format_option);
1504 inserted = true;
1505 }
1506
1507 if (!inserted)
1508 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1509
1510 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1511 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001512 }
1513 else
1514 {
1515 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1516 cmd_obj->GetCommandName());
1517 result.SetStatus (eReturnStatusFailed);
1518 return false;
1519 }
1520 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001521 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001522
1523 default:
1524 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1525 suffix.c_str());
1526 result.SetStatus (eReturnStatusFailed);
1527 return false;
1528
Greg Clayton7268b4c2011-10-28 21:38:01 +00001529 }
1530 }
1531 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001532 if (command_string.length() == 0)
1533 done = true;
1534
Chris Lattner24943d22010-06-08 16:52:24 +00001535 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001536
Greg Clayton7268b4c2011-10-28 21:38:01 +00001537 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001538 revised_command_line.Printf (" %s", command_string.c_str());
1539
1540 // End of Phase 1.
1541 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1542 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1543 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1544 // wants_raw_input specifies whether the Execute method expects raw input or not.
1545
1546
1547 if (log)
1548 {
1549 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1550 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1551 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1552 }
1553
1554 // Phase 2.
1555 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1556 // CommandObject, with the appropriate arguments.
1557
1558 if (cmd_obj != NULL)
1559 {
1560 if (add_to_history)
1561 {
1562 Args command_args (revised_command_line.GetData());
1563 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1564 if (repeat_command != NULL)
1565 m_repeat_command.assign(repeat_command);
1566 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001567 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001568
Jim Ingham6247dbe2011-07-12 03:12:18 +00001569 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001570 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001571 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001572 }
1573
1574 command_string = revised_command_line.GetData();
1575 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001576 std::string remainder;
1577 if (actual_cmd_name_len < command_string.length())
1578 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1579 // than cmd_obj->GetCommandName(), because name completion
1580 // allows users to enter short versions of the names,
1581 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001582
1583 // Remove any initial spaces
1584 std::string white_space (" \t\v");
1585 size_t pos = remainder.find_first_not_of (white_space);
1586 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001587 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001588
1589 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001590 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001591
Jim Inghamda26bd22012-06-08 21:56:10 +00001592 cmd_obj->Execute (remainder.c_str(), result);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001593 }
1594 else
1595 {
1596 // We didn't find the first command object, so complete the first argument.
1597 Args command_args (revised_command_line.GetData());
1598 StringList matches;
1599 int num_matches;
1600 int cursor_index = 0;
1601 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1602 bool word_complete;
1603 num_matches = HandleCompletionMatches (command_args,
1604 cursor_index,
1605 cursor_char_position,
1606 0,
1607 -1,
1608 word_complete,
1609 matches);
1610
1611 if (num_matches > 0)
1612 {
1613 std::string error_msg;
1614 error_msg.assign ("ambiguous command '");
1615 error_msg.append(command_args.GetArgumentAtIndex(0));
1616 error_msg.append ("'.");
1617
1618 error_msg.append (" Possible completions:");
1619 for (int i = 0; i < num_matches; i++)
1620 {
1621 error_msg.append ("\n\t");
1622 error_msg.append (matches.GetStringAtIndex (i));
1623 }
1624 error_msg.append ("\n");
1625 result.AppendRawError (error_msg.c_str(), error_msg.size());
1626 }
1627 else
1628 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1629
1630 result.SetStatus (eReturnStatusFailed);
1631 }
1632
Jason Molenda24c991c2011-08-25 00:20:04 +00001633 if (log)
1634 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1635
Chris Lattner24943d22010-06-08 16:52:24 +00001636 return result.Succeeded();
1637}
1638
1639int
1640CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1641 int &cursor_index,
1642 int &cursor_char_position,
1643 int match_start_point,
1644 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001645 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001646 StringList &matches)
1647{
1648 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001649 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001650
1651 // For any of the command completions a unique match will be a complete word.
1652 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001653
1654 if (cursor_index == -1)
1655 {
1656 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001657 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001658 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1659 }
1660 else if (cursor_index == 0)
1661 {
1662 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001663 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001664 num_command_matches = matches.GetSize();
1665
1666 if (num_command_matches == 1
1667 && cmd_obj && cmd_obj->IsMultiwordObject()
1668 && matches.GetStringAtIndex(0) != NULL
1669 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1670 {
1671 look_for_subcommand = true;
1672 num_command_matches = 0;
1673 matches.DeleteStringAtIndex(0);
1674 parsed_line.AppendArgument ("");
1675 cursor_index++;
1676 cursor_char_position = 0;
1677 }
1678 }
1679
1680 if (cursor_index > 0 || look_for_subcommand)
1681 {
1682 // We are completing further on into a commands arguments, so find the command and tell it
1683 // to complete the command.
1684 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001685 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001686 if (command_object == NULL)
1687 {
1688 return 0;
1689 }
1690 else
1691 {
1692 parsed_line.Shift();
1693 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001694 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001695 cursor_index,
1696 cursor_char_position,
1697 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001698 max_return_elements,
1699 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001700 matches);
1701 }
1702 }
1703
1704 return num_command_matches;
1705
1706}
1707
1708int
1709CommandInterpreter::HandleCompletion (const char *current_line,
1710 const char *cursor,
1711 const char *last_char,
1712 int match_start_point,
1713 int max_return_elements,
1714 StringList &matches)
1715{
1716 // We parse the argument up to the cursor, so the last argument in parsed_line is
1717 // the one containing the cursor, and the cursor is after the last character.
1718
1719 Args parsed_line(current_line, last_char - current_line);
1720 Args partial_parsed_line(current_line, cursor - current_line);
1721
Jim Ingham6247dbe2011-07-12 03:12:18 +00001722 // Don't complete comments, and if the line we are completing is just the history repeat character,
1723 // substitute the appropriate history line.
1724 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1725 if (first_arg)
1726 {
1727 if (first_arg[0] == m_comment_char)
1728 return 0;
1729 else if (first_arg[0] == m_repeat_char)
1730 {
1731 const char *history_string = FindHistoryString (first_arg);
1732 if (history_string != NULL)
1733 {
1734 matches.Clear();
1735 matches.InsertStringAtIndex(0, history_string);
1736 return -2;
1737 }
1738 else
1739 return 0;
1740
1741 }
1742 }
1743
1744
Chris Lattner24943d22010-06-08 16:52:24 +00001745 int num_args = partial_parsed_line.GetArgumentCount();
1746 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1747 int cursor_char_position;
1748
1749 if (cursor_index == -1)
1750 cursor_char_position = 0;
1751 else
1752 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001753
1754 if (cursor > current_line && cursor[-1] == ' ')
1755 {
1756 // We are just after a space. If we are in an argument, then we will continue
1757 // parsing, but if we are between arguments, then we have to complete whatever the next
1758 // element would be.
1759 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1760 // protected by a quote) then the space will also be in the parsed argument...
1761
1762 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1763 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1764 {
1765 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1766 cursor_index++;
1767 cursor_char_position = 0;
1768 }
1769 }
Chris Lattner24943d22010-06-08 16:52:24 +00001770
1771 int num_command_matches;
1772
1773 matches.Clear();
1774
1775 // Only max_return_elements == -1 is supported at present:
1776 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001777 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001778 num_command_matches = HandleCompletionMatches (parsed_line,
1779 cursor_index,
1780 cursor_char_position,
1781 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001782 max_return_elements,
1783 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001784 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001785
1786 if (num_command_matches <= 0)
1787 return num_command_matches;
1788
1789 if (num_args == 0)
1790 {
1791 // If we got an empty string, insert nothing.
1792 matches.InsertStringAtIndex(0, "");
1793 }
1794 else
1795 {
1796 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1797 // put an empty string in element 0.
1798 std::string command_partial_str;
1799 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001800 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1801 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001802
1803 std::string common_prefix;
1804 matches.LongestCommonPrefix (common_prefix);
1805 int partial_name_len = command_partial_str.size();
1806
1807 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001808 // Only do this if the completer told us this was a complete word, however...
1809 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001810 {
1811 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1812 if (quote_char != '\0')
1813 common_prefix.push_back(quote_char);
1814
1815 common_prefix.push_back(' ');
1816 }
1817 common_prefix.erase (0, partial_name_len);
1818 matches.InsertStringAtIndex(0, common_prefix.c_str());
1819 }
1820 return num_command_matches;
1821}
1822
Chris Lattner24943d22010-06-08 16:52:24 +00001823
1824CommandInterpreter::~CommandInterpreter ()
1825{
1826}
1827
1828const char *
1829CommandInterpreter::GetPrompt ()
1830{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001831 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001832}
1833
1834void
1835CommandInterpreter::SetPrompt (const char *new_prompt)
1836{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001837 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001838}
1839
Jim Ingham5e16ef52010-10-04 19:49:29 +00001840size_t
Greg Clayton58928562011-02-09 01:08:52 +00001841CommandInterpreter::GetConfirmationInputReaderCallback
1842(
1843 void *baton,
1844 InputReader &reader,
1845 lldb::InputReaderAction action,
1846 const char *bytes,
1847 size_t bytes_len
1848)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001849{
Greg Clayton58928562011-02-09 01:08:52 +00001850 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001851 bool *response_ptr = (bool *) baton;
1852
1853 switch (action)
1854 {
1855 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001856 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001857 {
1858 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001859 {
Greg Clayton58928562011-02-09 01:08:52 +00001860 out_file.Printf ("%s", reader.GetPrompt());
1861 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001862 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001863 }
1864 break;
1865
1866 case eInputReaderDeactivate:
1867 break;
1868
1869 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001870 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001871 {
Greg Clayton58928562011-02-09 01:08:52 +00001872 out_file.Printf ("%s", reader.GetPrompt());
1873 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001874 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001875 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001876
1877 case eInputReaderAsynchronousOutputWritten:
1878 break;
1879
Jim Ingham5e16ef52010-10-04 19:49:29 +00001880 case eInputReaderGotToken:
1881 if (bytes_len == 0)
1882 {
1883 reader.SetIsDone(true);
1884 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001885 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001886 {
1887 *response_ptr = true;
1888 reader.SetIsDone(true);
1889 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001890 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001891 {
1892 *response_ptr = false;
1893 reader.SetIsDone(true);
1894 }
1895 else
1896 {
Greg Clayton58928562011-02-09 01:08:52 +00001897 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001898 {
Jim Ingham26183802011-11-17 01:22:00 +00001899 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00001900 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001901 }
1902 }
1903 break;
1904
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001905 case eInputReaderInterrupt:
1906 case eInputReaderEndOfFile:
1907 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1908 reader.SetIsDone (true);
1909 break;
1910
Jim Ingham5e16ef52010-10-04 19:49:29 +00001911 case eInputReaderDone:
1912 break;
1913 }
1914
1915 return bytes_len;
1916
1917}
1918
1919bool
1920CommandInterpreter::Confirm (const char *message, bool default_answer)
1921{
Jim Ingham93057472010-10-04 22:44:14 +00001922 // Check AutoConfirm first:
1923 if (m_debugger.GetAutoConfirm())
1924 return default_answer;
1925
Jim Ingham5e16ef52010-10-04 19:49:29 +00001926 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1927 bool response = default_answer;
1928 if (reader_sp)
1929 {
1930 std::string prompt(message);
1931 prompt.append(": [");
1932 if (default_answer)
1933 prompt.append ("Y/n] ");
1934 else
1935 prompt.append ("y/N] ");
1936
1937 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1938 &response, // baton
1939 eInputReaderGranularityLine, // token size, to pass to callback function
1940 NULL, // end token
1941 prompt.c_str(), // prompt
1942 true)); // echo input
1943 if (err.Success())
1944 {
1945 GetDebugger().PushInputReader (reader_sp);
1946 }
1947 reader_sp->WaitOnReaderIsDone();
1948 }
1949 return response;
1950}
1951
1952
Chris Lattner24943d22010-06-08 16:52:24 +00001953void
1954CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1955{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001956 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001957
Sean Callananb386d822012-08-09 00:50:26 +00001958 if (cmd_obj_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001959 {
1960 CommandObject *cmd_obj = cmd_obj_sp.get();
1961 if (cmd_obj->IsCrossRefObject ())
1962 cmd_obj->AddObject (object_type);
1963 }
1964}
1965
Chris Lattner24943d22010-06-08 16:52:24 +00001966OptionArgVectorSP
1967CommandInterpreter::GetAliasOptions (const char *alias_name)
1968{
1969 OptionArgMap::iterator pos;
1970 OptionArgVectorSP ret_val;
1971
1972 std::string alias (alias_name);
1973
1974 if (HasAliasOptions())
1975 {
1976 pos = m_alias_options.find (alias);
1977 if (pos != m_alias_options.end())
1978 ret_val = pos->second;
1979 }
1980
1981 return ret_val;
1982}
1983
1984void
1985CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1986{
1987 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1988 if (pos != m_alias_options.end())
1989 {
1990 m_alias_options.erase (pos);
1991 }
1992}
1993
1994void
1995CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1996{
1997 m_alias_options[alias_name] = option_arg_vector_sp;
1998}
1999
2000bool
2001CommandInterpreter::HasCommands ()
2002{
2003 return (!m_command_dict.empty());
2004}
2005
2006bool
2007CommandInterpreter::HasAliases ()
2008{
2009 return (!m_alias_dict.empty());
2010}
2011
2012bool
2013CommandInterpreter::HasUserCommands ()
2014{
2015 return (!m_user_dict.empty());
2016}
2017
2018bool
2019CommandInterpreter::HasAliasOptions ()
2020{
2021 return (!m_alias_options.empty());
2022}
2023
Chris Lattner24943d22010-06-08 16:52:24 +00002024void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002025CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2026 const char *alias_name,
2027 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00002028 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002029 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00002030{
2031 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00002032
2033 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00002034
Caroline Tice44c841d2010-12-07 19:58:26 +00002035 // Make sure that the alias name is the 0th element in cmd_args
2036 std::string alias_name_str = alias_name;
2037 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2038 cmd_args.Unshift (alias_name);
2039
2040 Args new_args (alias_cmd_obj->GetCommandName());
2041 if (new_args.GetArgumentCount() == 2)
2042 new_args.Shift();
2043
Chris Lattner24943d22010-06-08 16:52:24 +00002044 if (option_arg_vector_sp.get())
2045 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002046 if (wants_raw_input)
2047 {
2048 // We have a command that both has command options and takes raw input. Make *sure* it has a
2049 // " -- " in the right place in the raw_input_string.
2050 size_t pos = raw_input_string.find(" -- ");
2051 if (pos == std::string::npos)
2052 {
2053 // None found; assume it goes at the beginning of the raw input string
2054 raw_input_string.insert (0, " -- ");
2055 }
2056 }
Chris Lattner24943d22010-06-08 16:52:24 +00002057
2058 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2059 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002060 std::vector<bool> used (old_size + 1, false);
2061
2062 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002063
2064 for (int i = 0; i < option_arg_vector->size(); ++i)
2065 {
2066 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00002067 OptionArgValue value_pair = option_pair.second;
2068 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00002069 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00002070 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00002071 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002072 {
2073 if (!wants_raw_input
2074 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2075 new_args.AppendArgument (value.c_str());
2076 }
Chris Lattner24943d22010-06-08 16:52:24 +00002077 else
2078 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002079 if (value_type != optional_argument)
2080 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002081 if (value.compare ("<no-argument>") != 0)
2082 {
2083 int index = GetOptionArgumentPosition (value.c_str());
2084 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002085 {
Chris Lattner24943d22010-06-08 16:52:24 +00002086 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002087 if (value_type != optional_argument)
2088 new_args.AppendArgument (value.c_str());
2089 else
2090 {
2091 char buffer[255];
2092 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2093 new_args.AppendArgument (buffer);
2094 }
2095
2096 }
Chris Lattner24943d22010-06-08 16:52:24 +00002097 else if (index >= cmd_args.GetArgumentCount())
2098 {
2099 result.AppendErrorWithFormat
2100 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2101 index);
2102 result.SetStatus (eReturnStatusFailed);
2103 return;
2104 }
2105 else
2106 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002107 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2108 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2109 if (strpos != std::string::npos)
2110 {
2111 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2112 }
2113
2114 if (value_type != optional_argument)
2115 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2116 else
2117 {
2118 char buffer[255];
2119 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2120 cmd_args.GetArgumentAtIndex (index));
2121 new_args.AppendArgument (buffer);
2122 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002123 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002124 }
2125 }
2126 }
2127 }
2128
2129 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2130 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002131 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002132 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2133 }
2134
2135 cmd_args.Clear();
2136 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2137 }
2138 else
2139 {
2140 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002141 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2142 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2143 // input string.
2144 if (wants_raw_input)
2145 {
2146 cmd_args.Clear();
2147 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2148 }
Chris Lattner24943d22010-06-08 16:52:24 +00002149 return;
2150 }
2151
2152 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2153 return;
2154}
2155
2156
2157int
2158CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2159{
2160 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2161 // of zero.
2162
2163 char *cptr = (char *) in_string;
2164
2165 // Does it start with '%'
2166 if (cptr[0] == '%')
2167 {
2168 ++cptr;
2169
2170 // Is the rest of it entirely digits?
2171 if (isdigit (cptr[0]))
2172 {
2173 const char *start = cptr;
2174 while (isdigit (cptr[0]))
2175 ++cptr;
2176
2177 // We've gotten to the end of the digits; are we at the end of the string?
2178 if (cptr[0] == '\0')
2179 position = atoi (start);
2180 }
2181 }
2182
2183 return position;
2184}
2185
2186void
2187CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2188{
Jim Ingham574c3d62011-08-12 23:34:31 +00002189 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002190 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002191 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002192 // In the current working directory we don't load any program specific
2193 // .lldbinit files, we only look for a "./.lldbinit" file.
2194 if (m_skip_lldbinit_files)
2195 return;
2196
2197 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002198 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002199 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002200 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002201 // If we aren't looking in the current working directory we are looking
2202 // in the home directory. We will first see if there is an application
2203 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2204 // "-" and the name of the program. If this file doesn't exist, we fall
2205 // back to just the "~/.lldbinit" file. We also obey any requests to not
2206 // load the init files.
2207 const char *init_file_path = "~/.lldbinit";
2208
2209 if (m_skip_app_init_files == false)
2210 {
2211 FileSpec program_file_spec (Host::GetProgramFileSpec());
2212 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002213
Greg Claytond6edcb52011-09-11 00:01:44 +00002214 if (program_name)
2215 {
2216 char program_init_file_name[PATH_MAX];
2217 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2218 init_file.SetFile (program_init_file_name, true);
2219 if (!init_file.Exists())
2220 init_file.Clear();
2221 }
2222 }
2223
2224 if (!init_file && !m_skip_lldbinit_files)
2225 init_file.SetFile (init_file_path, true);
2226 }
2227
Chris Lattner24943d22010-06-08 16:52:24 +00002228 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2229 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2230
2231 if (init_file.Exists())
2232 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002233 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2234 bool stop_on_continue = true;
2235 bool stop_on_error = false;
2236 bool echo_commands = false;
2237 bool print_results = false;
2238
Enrico Granata01bc2d42012-05-31 01:09:06 +00002239 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002240 }
2241 else
2242 {
2243 // nothing to be done if the file doesn't exist
2244 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2245 }
2246}
2247
Greg Claytonb72d0f02011-04-12 05:54:46 +00002248PlatformSP
2249CommandInterpreter::GetPlatform (bool prefer_target_platform)
2250{
2251 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002252 if (prefer_target_platform)
2253 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002254 ExecutionContext exe_ctx(GetExecutionContext());
2255 Target *target = exe_ctx.GetTargetPtr();
Greg Clayton567e7f32011-09-22 04:58:26 +00002256 if (target)
2257 platform_sp = target->GetPlatform();
2258 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002259
2260 if (!platform_sp)
2261 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2262 return platform_sp;
2263}
2264
Jim Ingham949d5ac2011-02-18 00:54:25 +00002265void
Jim Inghama4fede32011-03-11 01:51:49 +00002266CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002267 ExecutionContext *override_context,
2268 bool stop_on_continue,
2269 bool stop_on_error,
2270 bool echo_commands,
2271 bool print_results,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002272 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002273 CommandReturnObject &result)
2274{
2275 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002276
2277 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2278 // Make sure you reset this value anywhere you return from the function.
2279
2280 bool old_async_execution = m_debugger.GetAsyncExecution();
2281
2282 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2283 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2284
2285 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002286 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002287
2288 if (!stop_on_continue)
2289 {
2290 m_debugger.SetAsyncExecution (false);
2291 }
2292
2293 for (int idx = 0; idx < num_lines; idx++)
2294 {
2295 const char *cmd = commands.GetStringAtIndex(idx);
2296 if (cmd[0] == '\0')
2297 continue;
2298
Jim Ingham949d5ac2011-02-18 00:54:25 +00002299 if (echo_commands)
2300 {
2301 result.AppendMessageWithFormat ("%s %s\n",
2302 GetPrompt(),
2303 cmd);
2304 }
2305
Greg Claytonaa378b12011-02-20 02:15:07 +00002306 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002307 // If override_context is not NULL, pass no_context_switching = true for
2308 // HandleCommand() since we updated our context already.
Enrico Granata01bc2d42012-05-31 01:09:06 +00002309 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002310 NULL, /* override_context */
2311 true, /* repeat_on_empty_command */
2312 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002313
2314 if (print_results)
2315 {
2316 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002317 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002318 }
2319
2320 if (!success || !tmp_result.Succeeded())
2321 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002322 const char *error_msg = tmp_result.GetErrorData();
2323 if (error_msg == NULL || error_msg[0] == '\0')
2324 error_msg = "<unknown error>.\n";
Jim Ingham949d5ac2011-02-18 00:54:25 +00002325 if (stop_on_error)
2326 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002327 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2328 idx, cmd, error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002329 result.SetStatus (eReturnStatusFailed);
2330 m_debugger.SetAsyncExecution (old_async_execution);
2331 return;
2332 }
2333 else if (print_results)
2334 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002335 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Ingham949d5ac2011-02-18 00:54:25 +00002336 idx + 1,
2337 cmd,
Jim Ingham862fd5c2012-04-24 02:25:07 +00002338 error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002339 }
2340 }
2341
Caroline Tice4a348082011-05-02 20:41:46 +00002342 if (result.GetImmediateOutputStream())
2343 result.GetImmediateOutputStream()->Flush();
2344
2345 if (result.GetImmediateErrorStream())
2346 result.GetImmediateErrorStream()->Flush();
2347
Jim Ingham949d5ac2011-02-18 00:54:25 +00002348 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2349 // could be running (for instance in Breakpoint Commands.
2350 // So we check the return value to see if it is has running in it.
2351 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2352 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2353 {
2354 if (stop_on_continue)
2355 {
2356 // If we caused the target to proceed, and we're going to stop in that case, set the
2357 // status in our real result before returning. This is an error if the continue was not the
2358 // last command in the set of commands to be run.
2359 if (idx != num_lines - 1)
2360 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2361 idx + 1, cmd);
2362 else
2363 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2364
2365 result.SetStatus(tmp_result.GetStatus());
2366 m_debugger.SetAsyncExecution (old_async_execution);
2367
2368 return;
2369 }
2370 }
2371
2372 }
2373
2374 result.SetStatus (eReturnStatusSuccessFinishResult);
2375 m_debugger.SetAsyncExecution (old_async_execution);
2376
2377 return;
2378}
2379
2380void
2381CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2382 ExecutionContext *context,
2383 bool stop_on_continue,
2384 bool stop_on_error,
2385 bool echo_command,
2386 bool print_result,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002387 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002388 CommandReturnObject &result)
2389{
2390 if (cmd_file.Exists())
2391 {
2392 bool success;
2393 StringList commands;
2394 success = commands.ReadFileLines(cmd_file);
2395 if (!success)
2396 {
2397 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2398 result.SetStatus (eReturnStatusFailed);
2399 return;
2400 }
Enrico Granata01bc2d42012-05-31 01:09:06 +00002401 m_command_source_depth++;
2402 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2403 m_command_source_depth--;
Jim Ingham949d5ac2011-02-18 00:54:25 +00002404 }
2405 else
2406 {
2407 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2408 cmd_file.GetFilename().AsCString());
2409 result.SetStatus (eReturnStatusFailed);
2410 return;
2411 }
2412}
2413
Chris Lattner24943d22010-06-08 16:52:24 +00002414ScriptInterpreter *
2415CommandInterpreter::GetScriptInterpreter ()
2416{
Enrico Granatac5c10a42012-07-10 18:23:48 +00002417 // <rdar://problem/11751427>
2418 // we need to protect the initialization of the script interpreter
2419 // otherwise we could end up with two threads both trying to create
2420 // their instance of it, and for some languages (e.g. Python)
2421 // this is a bulletproof recipe for disaster!
2422 // this needs to be a function-level static because multiple Debugger instances living in the same process
2423 // still need to be isolated and not try to initialize Python concurrently
Enrico Granatab88c0a92012-07-10 19:04:14 +00002424 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2425 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granatac5c10a42012-07-10 18:23:48 +00002426
Caroline Tice0aa2e552011-01-14 00:29:16 +00002427 if (m_script_interpreter_ap.get() != NULL)
2428 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002429
Caroline Tice0aa2e552011-01-14 00:29:16 +00002430 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2431 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002432 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002433 case eScriptLanguagePython:
2434#ifndef LLDB_DISABLE_PYTHON
2435 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2436 break;
2437#else
2438 // Fall through to the None case when python is disabled
2439#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002440 case eScriptLanguageNone:
2441 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2442 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002443 default:
2444 break;
2445 };
2446
2447 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002448}
2449
2450
2451
2452bool
2453CommandInterpreter::GetSynchronous ()
2454{
2455 return m_synchronous_execution;
2456}
2457
2458void
2459CommandInterpreter::SetSynchronous (bool value)
2460{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002461 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002462}
2463
2464void
2465CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2466 const char *word_text,
2467 const char *separator,
2468 const char *help_text,
2469 uint32_t max_word_len)
2470{
Greg Clayton238c0a12010-09-18 01:14:36 +00002471 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2472
Chris Lattner24943d22010-06-08 16:52:24 +00002473 int indent_size = max_word_len + strlen (separator) + 2;
2474
2475 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002476
2477 StreamString text_strm;
2478 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2479
2480 size_t len = text_strm.GetSize();
2481 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002482 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002483 {
2484 text_strm.EOL();
2485 len = text_strm.GetSize();
2486 }
Chris Lattner24943d22010-06-08 16:52:24 +00002487
2488 if (len < max_columns)
2489 {
2490 // Output it as a single line.
2491 strm.Printf ("%s", text);
2492 }
2493 else
2494 {
2495 // We need to break it up into multiple lines.
2496 bool first_line = true;
2497 int text_width;
2498 int start = 0;
2499 int end = start;
2500 int final_end = strlen (text);
2501 int sub_len;
2502
2503 while (end < final_end)
2504 {
2505 if (first_line)
2506 text_width = max_columns - 1;
2507 else
2508 text_width = max_columns - indent_size - 1;
2509
2510 // Don't start the 'text' on a space, since we're already outputting the indentation.
2511 if (!first_line)
2512 {
2513 while ((start < final_end) && (text[start] == ' '))
2514 start++;
2515 }
2516
2517 end = start + text_width;
2518 if (end > final_end)
2519 end = final_end;
2520 else
2521 {
2522 // If we're not at the end of the text, make sure we break the line on white space.
2523 while (end > start
2524 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2525 end--;
Greg Clayton73844aa2012-08-22 17:17:09 +00002526 assert (end > 0);
Chris Lattner24943d22010-06-08 16:52:24 +00002527 }
2528
2529 sub_len = end - start;
2530 if (start != 0)
2531 strm.EOL();
2532 if (!first_line)
2533 strm.Indent();
2534 else
2535 first_line = false;
2536 assert (start <= final_end);
2537 assert (start + sub_len <= final_end);
2538 if (sub_len > 0)
2539 strm.Write (text + start, sub_len);
2540 start = end + 1;
2541 }
2542 }
2543 strm.EOL();
2544 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002545}
2546
2547void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002548CommandInterpreter::OutputHelpText (Stream &strm,
2549 const char *word_text,
2550 const char *separator,
2551 const char *help_text,
2552 uint32_t max_word_len)
2553{
2554 int indent_size = max_word_len + strlen (separator) + 2;
2555
2556 strm.IndentMore (indent_size);
2557
2558 StreamString text_strm;
2559 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2560
2561 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata1bba6e52011-07-07 00:38:40 +00002562
2563 size_t len = text_strm.GetSize();
2564 const char *text = text_strm.GetData();
2565
2566 uint32_t chars_left = max_columns;
2567
2568 for (uint32_t i = 0; i < len; i++)
2569 {
2570 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2571 {
Enrico Granata1bba6e52011-07-07 00:38:40 +00002572 chars_left = max_columns - indent_size;
2573 strm.EOL();
2574 strm.Indent();
2575 }
2576 else
2577 {
2578 strm.PutChar(text[i]);
2579 chars_left--;
2580 }
2581
2582 }
2583
2584 strm.EOL();
2585 strm.IndentLess(indent_size);
2586}
2587
2588void
Chris Lattner24943d22010-06-08 16:52:24 +00002589CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2590 StringList &commands_found, StringList &commands_help)
2591{
2592 CommandObject::CommandMap::const_iterator pos;
2593 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2594 CommandObject *sub_cmd_obj;
2595
2596 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2597 {
2598 const char * command_name = pos->first.c_str();
2599 sub_cmd_obj = pos->second.get();
2600 StreamString complete_command_name;
2601
2602 complete_command_name.Printf ("%s %s", prefix, command_name);
2603
Greg Clayton238c0a12010-09-18 01:14:36 +00002604 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002605 {
2606 commands_found.AppendString (complete_command_name.GetData());
2607 commands_help.AppendString (sub_cmd_obj->GetHelp());
2608 }
2609
2610 if (sub_cmd_obj->IsMultiwordObject())
2611 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2612 commands_help);
2613 }
2614
2615}
2616
2617void
2618CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2619 StringList &commands_help)
2620{
2621 CommandObject::CommandMap::const_iterator pos;
2622
2623 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2624 {
2625 const char *command_name = pos->first.c_str();
2626 CommandObject *cmd_obj = pos->second.get();
2627
Greg Clayton238c0a12010-09-18 01:14:36 +00002628 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002629 {
2630 commands_found.AppendString (command_name);
2631 commands_help.AppendString (cmd_obj->GetHelp());
2632 }
2633
2634 if (cmd_obj->IsMultiwordObject())
2635 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2636
2637 }
2638}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002639
2640
2641void
2642CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2643{
Greg Claytonb72d0f02011-04-12 05:54:46 +00002644 if (override_context != NULL)
2645 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002646 m_exe_ctx_ref = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002647 }
2648 else
2649 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002650 const bool adopt_selected = true;
2651 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002652 }
2653}
2654
Jim Ingham6247dbe2011-07-12 03:12:18 +00002655void
2656CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2657{
2658 DumpHistory (stream, 0, count - 1);
2659}
2660
2661void
2662CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2663{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002664 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2665 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002666 {
2667 if (!m_command_history[i].empty())
2668 {
2669 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002670 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002671 }
2672 }
2673}
2674
2675const char *
2676CommandInterpreter::FindHistoryString (const char *input_str) const
2677{
2678 if (input_str[0] != m_repeat_char)
2679 return NULL;
2680 if (input_str[1] == '-')
2681 {
2682 bool success;
2683 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2684 if (!success)
2685 return NULL;
2686 if (idx > m_command_history.size())
2687 return NULL;
2688 idx = m_command_history.size() - idx;
2689 return m_command_history[idx].c_str();
2690
2691 }
2692 else if (input_str[1] == m_repeat_char)
2693 {
2694 if (m_command_history.empty())
2695 return NULL;
2696 else
2697 return m_command_history.back().c_str();
2698 }
2699 else
2700 {
2701 bool success;
2702 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2703 if (!success)
2704 return NULL;
2705 if (idx >= m_command_history.size())
2706 return NULL;
2707 return m_command_history[idx].c_str();
2708 }
2709}