blob: 9cec1f39906b8621c062f426fca70aec97947bee [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
Johnny Chena47e44b2012-08-24 18:15:45 +0000135 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callananfc58af22012-05-04 23:15:02 +0000136 if (cmd_obj_sp)
137 {
138 AddAlias ("attach", cmd_obj_sp);
139 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000140
Johnny Chena47e44b2012-08-24 18:15:45 +0000141 cmd_obj_sp = GetCommandSPExact ("process detach",false);
142 if (cmd_obj_sp)
143 {
144 AddAlias ("detach", cmd_obj_sp);
145 }
146
Caroline Tice5ddbe212011-05-06 21:37:15 +0000147 cmd_obj_sp = GetCommandSPExact ("process continue", false);
148 if (cmd_obj_sp)
149 {
150 AddAlias ("c", cmd_obj_sp);
151 AddAlias ("continue", cmd_obj_sp);
152 }
153
154 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
155 if (cmd_obj_sp)
156 AddAlias ("b", cmd_obj_sp);
157
158 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
159 if (cmd_obj_sp)
160 AddAlias ("bt", cmd_obj_sp);
161
162 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
163 if (cmd_obj_sp)
Jason Molenda47eb00e2011-10-22 00:47:41 +0000164 {
165 AddAlias ("stepi", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000166 AddAlias ("si", cmd_obj_sp);
Jason Molenda47eb00e2011-10-22 00:47:41 +0000167 }
168
169 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
170 if (cmd_obj_sp)
171 {
172 AddAlias ("nexti", cmd_obj_sp);
173 AddAlias ("ni", cmd_obj_sp);
174 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000175
176 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
177 if (cmd_obj_sp)
178 {
179 AddAlias ("s", cmd_obj_sp);
180 AddAlias ("step", cmd_obj_sp);
181 }
182
183 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
184 if (cmd_obj_sp)
185 {
186 AddAlias ("n", cmd_obj_sp);
187 AddAlias ("next", cmd_obj_sp);
188 }
189
190 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
191 if (cmd_obj_sp)
192 {
Caroline Tice5ddbe212011-05-06 21:37:15 +0000193 AddAlias ("finish", cmd_obj_sp);
194 }
195
Jim Ingham59355252011-12-02 01:12:59 +0000196 cmd_obj_sp = GetCommandSPExact ("frame select", false);
197 if (cmd_obj_sp)
198 {
199 AddAlias ("f", cmd_obj_sp);
200 }
201
Caroline Tice5ddbe212011-05-06 21:37:15 +0000202 cmd_obj_sp = GetCommandSPExact ("source list", false);
203 if (cmd_obj_sp)
204 {
205 AddAlias ("l", cmd_obj_sp);
206 AddAlias ("list", cmd_obj_sp);
207 }
208
209 cmd_obj_sp = GetCommandSPExact ("memory read", false);
210 if (cmd_obj_sp)
211 AddAlias ("x", cmd_obj_sp);
212
213 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
214 if (cmd_obj_sp)
215 AddAlias ("up", cmd_obj_sp);
216
217 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
218 if (cmd_obj_sp)
219 AddAlias ("down", cmd_obj_sp);
220
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000221 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000222 if (cmd_obj_sp)
223 AddAlias ("display", cmd_obj_sp);
Jim Ingham9d1acc12011-10-24 18:37:00 +0000224
225 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
226 if (cmd_obj_sp)
227 AddAlias ("dis", cmd_obj_sp);
228
229 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
230 if (cmd_obj_sp)
231 AddAlias ("di", cmd_obj_sp);
232
233
Jason Molenda730cae02011-10-22 01:30:52 +0000234
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000235 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000236 if (cmd_obj_sp)
237 AddAlias ("undisplay", cmd_obj_sp);
238
Caroline Tice5ddbe212011-05-06 21:37:15 +0000239 cmd_obj_sp = GetCommandSPExact ("target create", false);
240 if (cmd_obj_sp)
241 AddAlias ("file", cmd_obj_sp);
242
243 cmd_obj_sp = GetCommandSPExact ("target modules", false);
244 if (cmd_obj_sp)
245 AddAlias ("image", cmd_obj_sp);
246
247
248 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000249
Caroline Tice5ddbe212011-05-06 21:37:15 +0000250 cmd_obj_sp = GetCommandSPExact ("expression", false);
251 if (cmd_obj_sp)
252 {
253 AddAlias ("expr", cmd_obj_sp);
254
255 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
256 AddAlias ("p", cmd_obj_sp);
257 AddAlias ("print", cmd_obj_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000258 AddAlias ("call", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000259 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
260 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan59959eb2012-08-08 01:30:34 +0000261 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000262
263 alias_arguments_vector_sp.reset (new OptionArgVector);
264 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
265 AddAlias ("po", cmd_obj_sp);
266 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
267 }
268
Sean Callananee301fa2012-06-01 23:29:32 +0000269 cmd_obj_sp = GetCommandSPExact ("process kill", false);
270 if (cmd_obj_sp)
271 AddAlias ("kill", cmd_obj_sp);
272
Caroline Tice5ddbe212011-05-06 21:37:15 +0000273 cmd_obj_sp = GetCommandSPExact ("process launch", false);
274 if (cmd_obj_sp)
275 {
276 alias_arguments_vector_sp.reset (new OptionArgVector);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000277#if defined (__arm__)
278 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
279#else
Greg Clayton86c50d72012-05-18 00:04:38 +0000280 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000281#endif
Caroline Tice5ddbe212011-05-06 21:37:15 +0000282 AddAlias ("r", cmd_obj_sp);
283 AddAlias ("run", cmd_obj_sp);
284 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
285 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
286 }
Greg Claytonc84623f2012-03-29 21:47:51 +0000287
288 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
289 if (cmd_obj_sp)
290 {
291 AddAlias ("add-dsym", cmd_obj_sp);
292 }
Sean Callanan7b71b172012-05-21 18:25:19 +0000293
294 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
295 if (cmd_obj_sp)
296 {
297 alias_arguments_vector_sp.reset (new OptionArgVector);
298 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
299 AddAlias ("rb", cmd_obj_sp);
300 AddOrReplaceAliasOptions("rb", alias_arguments_vector_sp);
301 }
Chris Lattner24943d22010-06-08 16:52:24 +0000302}
303
Chris Lattner24943d22010-06-08 16:52:24 +0000304const char *
305CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
306{
307 // This function has not yet been implemented.
308
309 // Look for any embedded script command
310 // If found,
311 // get interpreter object from the command dictionary,
312 // call execute_one_command on it,
313 // get the results as a string,
314 // substitute that string for current stuff.
315
316 return arg;
317}
318
319
320void
321CommandInterpreter::LoadCommandDictionary ()
322{
323 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
324
325 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
326 //
327 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
328 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
329 // the cross-referencing stuff) are created!!!
330 //
331 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
332
333
334 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
335 // are created. This is so that when another command is created that needs to go into a crossref object,
336 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
337 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
338
Chris Lattner24943d22010-06-08 16:52:24 +0000339 // Non-CommandObjectCrossref commands can now be created.
340
Caroline Tice5bc8c972010-09-20 20:44:43 +0000341 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000342
Greg Clayton238c0a12010-09-18 01:14:36 +0000343 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000344 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000345 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000346 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000347 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
348 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000349// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000350 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000351 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000352 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000353 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
354 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000355 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000356 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000357 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000358 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000359 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000360 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000361 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000362 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
363 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000364 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000365 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000366 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000367
368 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000369 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000370 "_regexp-break",
Johnny Chen58edac32012-08-23 00:32:22 +0000371 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
372 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000373 if (break_regex_cmd_ap.get())
374 {
375 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
Johnny Chen58edac32012-08-23 00:32:22 +0000376 break_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000377 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
378 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000379 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000380 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000381 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000382 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
383 {
384 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
385 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
386 }
387 }
Jim Inghame56493f2011-03-22 02:29:32 +0000388
389 std::auto_ptr<CommandObjectRegexCommand>
Johnny Chena47e44b2012-08-24 18:15:45 +0000390 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
391 "_regexp-attach",
392 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.",
393 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]", 2));
394 if (attach_regex_cmd_ap.get())
395 {
396 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "process attach --pid %1") &&
397 attach_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "process attach --name '%1'"))
398 {
399 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
400 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
401 }
402 }
403
404 std::auto_ptr<CommandObjectRegexCommand>
Jim Inghame56493f2011-03-22 02:29:32 +0000405 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000406 "_regexp-down",
407 "Go down \"n\" frames in the stack (1 frame by default).",
408 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000409 if (down_regex_cmd_ap.get())
410 {
411 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
412 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
413 {
414 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
415 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
416 }
417 }
418
419 std::auto_ptr<CommandObjectRegexCommand>
420 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000421 "_regexp-up",
422 "Go up \"n\" frames in the stack (1 frame by default).",
423 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000424 if (up_regex_cmd_ap.get())
425 {
426 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
427 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
428 {
429 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
430 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
431 }
432 }
Jason Molenda730cae02011-10-22 01:30:52 +0000433
434 std::auto_ptr<CommandObjectRegexCommand>
435 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000436 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000437 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000438 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000439 if (display_regex_cmd_ap.get())
440 {
441 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
442 {
443 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
444 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
445 }
446 }
447
448 std::auto_ptr<CommandObjectRegexCommand>
449 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000450 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000451 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000452 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000453 if (undisplay_regex_cmd_ap.get())
454 {
455 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
456 {
457 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
458 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
459 }
460 }
461
Greg Claytonc3750432012-09-26 22:26:47 +0000462 std::auto_ptr<CommandObjectRegexCommand>
463 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
464 "gdb-remote",
465 "Connect to a remote GDB server.",
466 "gdb-remote [<host>:<port>]\ngdb-remote [<port>]", 2));
467 if (connect_gdb_remote_cmd_ap.get())
468 {
469 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
470 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
471 {
472 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
473 m_command_dict[command_sp->GetCommandName ()] = command_sp;
474 }
475 }
476
477 std::auto_ptr<CommandObjectRegexCommand>
478 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
479 "kdp-remote",
480 "Connect to a remote KDP server.",
481 "kdp-remote [<host>]\nkdp-remote [<host>:<port>]", 2));
482 if (connect_kdp_remote_cmd_ap.get())
483 {
484 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
485 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.*)$", "process connect --plugin kdp-remote udp://%1:41139"))
486 {
487 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
488 m_command_dict[command_sp->GetCommandName ()] = command_sp;
489 }
490 }
491
Chris Lattner24943d22010-06-08 16:52:24 +0000492}
493
494int
495CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
496 StringList &matches)
497{
498 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
499
500 if (include_aliases)
501 {
502 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
503 }
504
505 return matches.GetSize();
506}
507
508CommandObjectSP
509CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
510{
511 CommandObject::CommandMap::iterator pos;
512 CommandObjectSP ret_val;
513
514 std::string cmd(cmd_cstr);
515
516 if (HasCommands())
517 {
518 pos = m_command_dict.find(cmd);
519 if (pos != m_command_dict.end())
520 ret_val = pos->second;
521 }
522
523 if (include_aliases && HasAliases())
524 {
525 pos = m_alias_dict.find(cmd);
526 if (pos != m_alias_dict.end())
527 ret_val = pos->second;
528 }
529
530 if (HasUserCommands())
531 {
532 pos = m_user_dict.find(cmd);
533 if (pos != m_user_dict.end())
534 ret_val = pos->second;
535 }
536
Sean Callananb386d822012-08-09 00:50:26 +0000537 if (!exact && !ret_val)
Chris Lattner24943d22010-06-08 16:52:24 +0000538 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000539 // We will only get into here if we didn't find any exact matches.
540
541 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
542
Chris Lattner24943d22010-06-08 16:52:24 +0000543 StringList local_matches;
544 if (matches == NULL)
545 matches = &local_matches;
546
Jim Inghamd40f8a62010-07-06 22:46:59 +0000547 unsigned int num_cmd_matches = 0;
548 unsigned int num_alias_matches = 0;
549 unsigned int num_user_matches = 0;
550
551 // Look through the command dictionaries one by one, and if we get only one match from any of
552 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
553
Chris Lattner24943d22010-06-08 16:52:24 +0000554 if (HasCommands())
555 {
556 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
557 }
558
559 if (num_cmd_matches == 1)
560 {
561 cmd.assign(matches->GetStringAtIndex(0));
562 pos = m_command_dict.find(cmd);
563 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000564 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000565 }
566
Jim Ingham9a574172010-06-24 20:28:42 +0000567 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000568 {
569 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
570
571 }
572
Jim Inghamd40f8a62010-07-06 22:46:59 +0000573 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000574 {
575 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
576 pos = m_alias_dict.find(cmd);
577 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000578 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000579 }
580
Jim Ingham9a574172010-06-24 20:28:42 +0000581 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000582 {
583 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
584 }
585
Jim Inghamd40f8a62010-07-06 22:46:59 +0000586 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000587 {
588 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
589
590 pos = m_user_dict.find (cmd);
591 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000592 user_match_sp = pos->second;
593 }
594
595 // If we got exactly one match, return that, otherwise return the match list.
596
597 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
598 {
599 if (num_cmd_matches)
600 return real_match_sp;
601 else if (num_alias_matches)
602 return alias_match_sp;
603 else
604 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000605 }
606 }
Sean Callananb386d822012-08-09 00:50:26 +0000607 else if (matches && ret_val)
Jim Inghamd40f8a62010-07-06 22:46:59 +0000608 {
609 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000610 }
611
612
613 return ret_val;
614}
615
Greg Claytond12aeab2011-04-20 16:37:46 +0000616bool
617CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
618{
619 if (name && name[0])
620 {
621 std::string name_sstr(name);
622 if (!can_replace)
623 {
624 if (m_command_dict.find (name_sstr) != m_command_dict.end())
625 return false;
626 }
627 m_command_dict[name_sstr] = cmd_sp;
628 return true;
629 }
630 return false;
631}
632
Enrico Granata6b1596d2011-08-16 23:24:13 +0000633bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000634CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000635 const lldb::CommandObjectSP &cmd_sp,
636 bool can_replace)
637{
Enrico Granata6010ace2011-11-07 22:57:04 +0000638 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000639 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000640
641 const char* name_cstr = name.c_str();
642
643 // do not allow replacement of internal commands
644 if (CommandExists(name_cstr))
645 return false;
646
647 if (can_replace == false && UserCommandExists(name_cstr))
648 return false;
649
650 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000651 return true;
652 }
653 return false;
654}
Greg Claytond12aeab2011-04-20 16:37:46 +0000655
Jim Inghamd40f8a62010-07-06 22:46:59 +0000656CommandObjectSP
657CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000658{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000659 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
660 CommandObjectSP ret_val; // Possibly empty return value.
661
662 if (cmd_cstr == NULL)
663 return ret_val;
664
665 if (cmd_words.GetArgumentCount() == 1)
666 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
667 else
668 {
669 // We have a multi-word command (seemingly), so we need to do more work.
670 // First, get the cmd_obj_sp for the first word in the command.
671 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
672 if (cmd_obj_sp.get() != NULL)
673 {
674 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
675 // command name), and find the appropriate sub-command SP for each command word....
676 size_t end = cmd_words.GetArgumentCount();
677 for (size_t j= 1; j < end; ++j)
678 {
679 if (cmd_obj_sp->IsMultiwordObject())
680 {
681 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
682 (cmd_words.GetArgumentAtIndex (j));
683 if (cmd_obj_sp.get() == NULL)
684 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
685 return ret_val;
686 }
687 else
688 // We have more words in the command name, but we don't have a multiword object. Fail and return
689 // empty 'ret_val'.
690 return ret_val;
691 }
692 // We successfully looped through all the command words and got valid command objects for them. Assign the
693 // last object retrieved to 'ret_val'.
694 ret_val = cmd_obj_sp;
695 }
696 }
697 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000698}
699
700CommandObject *
701CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
702{
703 return GetCommandSPExact (cmd_cstr, include_aliases).get();
704}
705
706CommandObject *
707CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
708{
709 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
710
711 // If we didn't find an exact match to the command string in the commands, look in
712 // the aliases.
713
714 if (command_obj == NULL)
715 {
716 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
717 }
718
719 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
720 // in both the commands and the aliases.
721
722 if (command_obj == NULL)
723 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
724
725 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000726}
727
728bool
729CommandInterpreter::CommandExists (const char *cmd)
730{
731 return m_command_dict.find(cmd) != m_command_dict.end();
732}
733
734bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000735CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
736 const char *options_args,
737 OptionArgVectorSP &option_arg_vector_sp)
738{
739 bool success = true;
740 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
741
742 if (!options_args || (strlen (options_args) < 1))
743 return true;
744
745 std::string options_string (options_args);
746 Args args (options_args);
747 CommandReturnObject result;
748 // Check to see if the command being aliased can take any command options.
749 Options *options = cmd_obj_sp->GetOptions ();
750 if (options)
751 {
752 // See if any options were specified as part of the alias; if so, handle them appropriately.
753 options->NotifyOptionParsingStarting ();
754 args.Unshift ("dummy_arg");
755 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
756 args.Shift ();
757 if (result.Succeeded())
758 options->VerifyPartialOptions (result);
759 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
760 {
761 result.AppendError ("Unable to create requested alias.\n");
762 return false;
763 }
764 }
765
Greg Clayton7268b4c2011-10-28 21:38:01 +0000766 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000767 {
768 if (cmd_obj_sp->WantsRawCommandString ())
769 option_arg_vector->push_back (OptionArgPair ("<argument>",
770 OptionArgValue (-1,
771 options_string)));
772 else
773 {
774 int argc = args.GetArgumentCount();
775 for (size_t i = 0; i < argc; ++i)
776 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
777 option_arg_vector->push_back
778 (OptionArgPair ("<argument>",
779 OptionArgValue (-1,
780 std::string (args.GetArgumentAtIndex (i)))));
781 }
782 }
783
784 return success;
785}
786
787bool
Chris Lattner24943d22010-06-08 16:52:24 +0000788CommandInterpreter::AliasExists (const char *cmd)
789{
790 return m_alias_dict.find(cmd) != m_alias_dict.end();
791}
792
793bool
794CommandInterpreter::UserCommandExists (const char *cmd)
795{
796 return m_user_dict.find(cmd) != m_user_dict.end();
797}
798
799void
800CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
801{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000802 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000803 m_alias_dict[alias_name] = command_obj_sp;
804}
805
806bool
807CommandInterpreter::RemoveAlias (const char *alias_name)
808{
809 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
810 if (pos != m_alias_dict.end())
811 {
812 m_alias_dict.erase(pos);
813 return true;
814 }
815 return false;
816}
817bool
818CommandInterpreter::RemoveUser (const char *alias_name)
819{
820 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
821 if (pos != m_user_dict.end())
822 {
823 m_user_dict.erase(pos);
824 return true;
825 }
826 return false;
827}
828
Chris Lattner24943d22010-06-08 16:52:24 +0000829void
830CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
831{
832 help_string.Printf ("'%s", command_name);
833 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
834
Sean Callananb386d822012-08-09 00:50:26 +0000835 if (option_arg_vector_sp)
Chris Lattner24943d22010-06-08 16:52:24 +0000836 {
837 OptionArgVector *options = option_arg_vector_sp.get();
838 for (int i = 0; i < options->size(); ++i)
839 {
840 OptionArgPair cur_option = (*options)[i];
841 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000842 OptionArgValue value_pair = cur_option.second;
843 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000844 if (opt.compare("<argument>") == 0)
845 {
846 help_string.Printf (" %s", value.c_str());
847 }
848 else
849 {
850 help_string.Printf (" %s", opt.c_str());
851 if ((value.compare ("<no-argument>") != 0)
852 && (value.compare ("<need-argument") != 0))
853 {
854 help_string.Printf (" %s", value.c_str());
855 }
856 }
857 }
858 }
859
860 help_string.Printf ("'");
861}
862
Greg Clayton65124ea2010-08-26 22:05:43 +0000863size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000864CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
865{
866 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000867 CommandObject::CommandMap::const_iterator end = dict.end();
868 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000869
Greg Clayton65124ea2010-08-26 22:05:43 +0000870 for (pos = dict.begin(); pos != end; ++pos)
871 {
872 size_t len = pos->first.size();
873 if (max_len < len)
874 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000875 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000876 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000877}
878
879void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000880CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000881 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000882{
883 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000884 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000885
886 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000887 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000888
889 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
890 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000891
Enrico Granata6b1596d2011-08-16 23:24:13 +0000892 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
893 {
894 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
895 max_len);
896 }
897 result.AppendMessage("");
898
899 }
900
Greg Clayton7268b4c2011-10-28 21:38:01 +0000901 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000902 {
Jim Inghame3663e82010-10-22 18:47:16 +0000903 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000904 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000905 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000906 max_len = FindLongestCommandWord (m_alias_dict);
907
Chris Lattner24943d22010-06-08 16:52:24 +0000908 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
909 {
910 StreamString sstr;
911 StreamString translation_and_help;
912 std::string entry_name = pos->first;
913 std::string second_entry = pos->second.get()->GetCommandName();
914 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
915
916 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
917 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
918 translation_and_help.GetData(), max_len);
919 }
920 result.AppendMessage("");
921 }
922
Greg Clayton7268b4c2011-10-28 21:38:01 +0000923 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000924 {
925 result.AppendMessage ("The following is a list of your current user-defined commands:");
926 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000927 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000928 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
929 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000930 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
931 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000932 }
933 result.AppendMessage("");
934 }
935
936 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
937}
938
Caroline Ticee0da7a52010-12-09 22:52:49 +0000939CommandObject *
940CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000941{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000942 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
943 // eventually be invoked by the given command line.
944
945 CommandObject *cmd_obj = NULL;
946 std::string white_space (" \t\v");
947 size_t start = command_string.find_first_not_of (white_space);
948 size_t end = 0;
949 bool done = false;
950 while (!done)
951 {
952 if (start != std::string::npos)
953 {
954 // Get the next word from command_string.
955 end = command_string.find_first_of (white_space, start);
956 if (end == std::string::npos)
957 end = command_string.size();
958 std::string cmd_word = command_string.substr (start, end - start);
959
960 if (cmd_obj == NULL)
961 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
962 // command or alias.
963 cmd_obj = GetCommandObject (cmd_word.c_str());
964 else if (cmd_obj->IsMultiwordObject ())
965 {
966 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
967 CommandObject *sub_cmd_obj =
968 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
969 if (sub_cmd_obj)
970 cmd_obj = sub_cmd_obj;
971 else // cmd_word was not a valid sub-command word, so we are donee
972 done = true;
973 }
974 else
975 // We have a cmd_obj and it is not a multi-word object, so we are done.
976 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000977
Caroline Ticee0da7a52010-12-09 22:52:49 +0000978 // If we didn't find a valid command object, or our command object is not a multi-word object, or
979 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
980 // next word.
981
982 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
983 done = true;
984 else
985 start = command_string.find_first_not_of (white_space, end);
986 }
987 else
988 // Unable to find any more words.
989 done = true;
990 }
991
992 if (end == command_string.size())
993 command_string.clear();
994 else
995 command_string = command_string.substr(end);
996
997 return cmd_obj;
998}
999
Greg Clayton9d855c62011-10-25 00:36:27 +00001000static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +00001001static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +00001002static void
1003StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001004{
Greg Clayton9d855c62011-10-25 00:36:27 +00001005 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001006 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001007 size_t pos = s.find_first_not_of (k_white_space);
1008 if (pos == std::string::npos)
1009 s.clear();
1010 else if (pos == 0)
1011 return;
1012 s.erase (0, pos);
1013 }
1014}
1015
Greg Clayton3840cd72011-11-09 23:25:03 +00001016static size_t
1017FindArgumentTerminator (const std::string &s)
1018{
Greg Clayton3840cd72011-11-09 23:25:03 +00001019 const size_t s_len = s.size();
1020 size_t offset = 0;
1021 while (offset < s_len)
1022 {
1023 size_t pos = s.find ("--", offset);
1024 if (pos == std::string::npos)
1025 break;
1026 if (pos > 0)
1027 {
1028 if (isspace(s[pos-1]))
1029 {
1030 // Check if the string ends "\s--" (where \s is a space character)
1031 // or if we have "\s--\s".
1032 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1033 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001034 return pos;
1035 }
1036 }
1037 }
1038 offset = pos + 2;
1039 }
Greg Clayton3840cd72011-11-09 23:25:03 +00001040 return std::string::npos;
1041}
1042
Greg Clayton9d855c62011-10-25 00:36:27 +00001043static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +00001044ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +00001045{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001046 command.clear();
1047 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +00001048 StripLeadingSpaces (command_string);
1049
1050 bool result = false;
1051 quote_char = '\0';
1052
1053 if (!command_string.empty())
1054 {
1055 const char first_char = command_string[0];
1056 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +00001057 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001058 quote_char = first_char;
1059 const size_t end_quote_pos = command_string.find (quote_char, 1);
1060 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001061 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001062 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001063 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001064 }
1065 else
1066 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001067 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +00001068 if (end_quote_pos + 1 < command_string.size())
1069 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1070 else
1071 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001072 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001073 }
1074 else
1075 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001076 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1077 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001078 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001079 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001080 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +00001081 }
1082 else
1083 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001084 command.assign (command_string, 0, first_space_pos);
1085 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +00001086 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001087 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001088 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001089 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001090
1091
1092 if (!command.empty())
1093 {
1094 // actual commands can't start with '-' or '_'
1095 if (command[0] != '-' && command[0] != '_')
1096 {
1097 size_t pos = command.find_first_not_of(k_valid_command_chars);
1098 if (pos > 0 && pos != std::string::npos)
1099 {
1100 suffix.assign (command.begin() + pos, command.end());
1101 command.erase (pos);
1102 }
1103 }
1104 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001105
1106 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001107}
1108
Greg Clayton7268b4c2011-10-28 21:38:01 +00001109CommandObject *
1110CommandInterpreter::BuildAliasResult (const char *alias_name,
1111 std::string &raw_input_string,
1112 std::string &alias_result,
1113 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001114{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001115 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001116 Args cmd_args (raw_input_string.c_str());
1117 alias_cmd_obj = GetCommandObject (alias_name);
1118 StreamString result_str;
1119
1120 if (alias_cmd_obj)
1121 {
1122 std::string alias_name_str = alias_name;
1123 if ((cmd_args.GetArgumentCount() == 0)
1124 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1125 cmd_args.Unshift (alias_name);
1126
1127 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1128 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1129
1130 if (option_arg_vector_sp.get())
1131 {
1132 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1133
1134 for (int i = 0; i < option_arg_vector->size(); ++i)
1135 {
1136 OptionArgPair option_pair = (*option_arg_vector)[i];
1137 OptionArgValue value_pair = option_pair.second;
1138 int value_type = value_pair.first;
1139 std::string option = option_pair.first;
1140 std::string value = value_pair.second;
1141 if (option.compare ("<argument>") == 0)
1142 result_str.Printf (" %s", value.c_str());
1143 else
1144 {
1145 result_str.Printf (" %s", option.c_str());
1146 if (value_type != optional_argument)
1147 result_str.Printf (" ");
1148 if (value.compare ("<no_argument>") != 0)
1149 {
1150 int index = GetOptionArgumentPosition (value.c_str());
1151 if (index == 0)
1152 result_str.Printf ("%s", value.c_str());
1153 else if (index >= cmd_args.GetArgumentCount())
1154 {
1155
1156 result.AppendErrorWithFormat
1157 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1158 index);
1159 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001160 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001161 }
1162 else
1163 {
1164 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1165 if (strpos != std::string::npos)
1166 raw_input_string = raw_input_string.erase (strpos,
1167 strlen (cmd_args.GetArgumentAtIndex (index)));
1168 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1169 }
1170 }
1171 }
1172 }
1173 }
1174
1175 alias_result = result_str.GetData();
1176 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001177 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001178}
1179
Greg Claytonf5c0c722011-10-14 07:41:33 +00001180Error
1181CommandInterpreter::PreprocessCommand (std::string &command)
1182{
1183 // The command preprocessor needs to do things to the command
1184 // line before any parsing of arguments or anything else is done.
1185 // The only current stuff that gets proprocessed is anyting enclosed
1186 // in backtick ('`') characters is evaluated as an expression and
1187 // the result of the expression must be a scalar that can be substituted
1188 // into the command. An example would be:
1189 // (lldb) memory read `$rsp + 20`
1190 Error error; // Error for any expressions that might not evaluate
1191 size_t start_backtick;
1192 size_t pos = 0;
1193 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1194 {
1195 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1196 {
1197 // The backtick was preceeded by a '\' character, remove the slash
1198 // and don't treat the backtick as the start of an expression
1199 command.erase(start_backtick-1, 1);
1200 // No need to add one to start_backtick since we just deleted a char
1201 pos = start_backtick;
1202 }
1203 else
1204 {
1205 const size_t expr_content_start = start_backtick + 1;
1206 const size_t end_backtick = command.find ('`', expr_content_start);
1207 if (end_backtick == std::string::npos)
1208 return error;
1209 else if (end_backtick == expr_content_start)
1210 {
1211 // Empty expression (two backticks in a row)
1212 command.erase (start_backtick, 2);
1213 }
1214 else
1215 {
1216 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1217
Greg Claytonbcaf99a2012-07-12 20:32:19 +00001218 ExecutionContext exe_ctx(GetExecutionContext());
1219 Target *target = exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001220 // Get a dummy target to allow for calculator mode while processing backticks.
1221 // This also helps break the infinite loop caused when target is null.
1222 if (!target)
1223 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001224 if (target)
1225 {
Greg Claytonf5c0c722011-10-14 07:41:33 +00001226 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad27026e2012-09-05 20:41:26 +00001227
1228 Target::EvaluateExpressionOptions options;
1229 options.SetCoerceToId(false)
1230 .SetUnwindOnError(true)
1231 .SetKeepInMemory(false)
1232 .SetSingleThreadTimeoutUsec(0);
1233
Greg Claytonf5c0c722011-10-14 07:41:33 +00001234 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad27026e2012-09-05 20:41:26 +00001235 exe_ctx.GetFramePtr(),
Enrico Granata6cca9692012-07-16 23:10:35 +00001236 expr_result_valobj_sp,
Enrico Granatad27026e2012-09-05 20:41:26 +00001237 options);
1238
Greg Claytonf5c0c722011-10-14 07:41:33 +00001239 if (expr_result == eExecutionCompleted)
1240 {
1241 Scalar scalar;
1242 if (expr_result_valobj_sp->ResolveValue (scalar))
1243 {
1244 command.erase (start_backtick, end_backtick - start_backtick + 1);
1245 StreamString value_strm;
1246 const bool show_type = false;
1247 scalar.GetValue (&value_strm, show_type);
1248 size_t value_string_size = value_strm.GetSize();
1249 if (value_string_size)
1250 {
1251 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1252 pos = start_backtick + value_string_size;
1253 continue;
1254 }
1255 else
1256 {
1257 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1258 }
1259 }
1260 else
1261 {
1262 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1263 }
1264 }
1265 else
1266 {
1267 if (expr_result_valobj_sp)
1268 error = expr_result_valobj_sp->GetError();
1269 if (error.Success())
1270 {
1271
1272 switch (expr_result)
1273 {
1274 case eExecutionSetupError:
1275 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1276 break;
1277 case eExecutionCompleted:
1278 break;
1279 case eExecutionDiscarded:
1280 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1281 break;
1282 case eExecutionInterrupted:
1283 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1284 break;
1285 case eExecutionTimedOut:
1286 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1287 break;
1288 }
1289 }
1290 }
1291 }
1292 }
1293 if (error.Fail())
1294 break;
1295 }
1296 }
1297 return error;
1298}
1299
1300
Caroline Ticee0da7a52010-12-09 22:52:49 +00001301bool
1302CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata01bc2d42012-05-31 01:09:06 +00001303 LazyBool lazy_add_to_history,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001304 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001305 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001306 bool repeat_on_empty_command,
1307 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001308
Caroline Ticee0da7a52010-12-09 22:52:49 +00001309{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001310
Caroline Ticee0da7a52010-12-09 22:52:49 +00001311 bool done = false;
1312 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001313 bool wants_raw_input = false;
1314 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001315 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001316
1317 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001318 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1319
1320 // Make a scoped cleanup object that will clear the crash description string
1321 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001322 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001323
Caroline Ticee0da7a52010-12-09 22:52:49 +00001324 if (log)
1325 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001326
Jim Inghamabab14b2010-11-04 23:08:45 +00001327 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1328
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001329 if (!no_context_switching)
1330 UpdateExecutionContext (override_context);
Enrico Granata01bc2d42012-05-31 01:09:06 +00001331
1332 // <rdar://problem/11328896>
1333 bool add_to_history;
1334 if (lazy_add_to_history == eLazyBoolCalculate)
1335 add_to_history = (m_command_source_depth == 0);
1336 else
1337 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1338
Jim Ingham949d5ac2011-02-18 00:54:25 +00001339 bool empty_command = false;
1340 bool comment_command = false;
1341 if (command_string.empty())
1342 empty_command = true;
1343 else
Chris Lattner24943d22010-06-08 16:52:24 +00001344 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001345 const char *k_space_characters = "\t\n\v\f\r ";
1346
1347 size_t non_space = command_string.find_first_not_of (k_space_characters);
1348 // Check for empty line or comment line (lines whose first
1349 // non-space character is the comment character for this interpreter)
1350 if (non_space == std::string::npos)
1351 empty_command = true;
1352 else if (command_string[non_space] == m_comment_char)
1353 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001354 else if (command_string[non_space] == m_repeat_char)
1355 {
1356 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1357 if (history_string == NULL)
1358 {
1359 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1360 result.SetStatus(eReturnStatusFailed);
1361 return false;
1362 }
1363 add_to_history = false;
1364 command_string = history_string;
1365 original_command_string = history_string;
1366 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001367 }
1368
1369 if (empty_command)
1370 {
1371 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001372 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001373 if (m_command_history.empty())
1374 {
1375 result.AppendError ("empty command");
1376 result.SetStatus(eReturnStatusFailed);
1377 return false;
1378 }
1379 else
1380 {
1381 command_line = m_repeat_command.c_str();
1382 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001383 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001384 if (m_repeat_command.empty())
1385 {
1386 result.AppendErrorWithFormat("No auto repeat.\n");
1387 result.SetStatus (eReturnStatusFailed);
1388 return false;
1389 }
1390 }
1391 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001392 }
1393 else
1394 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001395 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1396 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001397 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001398 }
1399 else if (comment_command)
1400 {
1401 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1402 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001403 }
Caroline Tice649116c2011-05-11 16:07:06 +00001404
Greg Claytonf5c0c722011-10-14 07:41:33 +00001405
1406 Error error (PreprocessCommand (command_string));
1407
1408 if (error.Fail())
1409 {
1410 result.AppendError (error.AsCString());
1411 result.SetStatus(eReturnStatusFailed);
1412 return false;
1413 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001414 // Phase 1.
1415
1416 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1417 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1418 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1419 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1420 // 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 +00001421 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001422 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001423
Caroline Ticee0da7a52010-12-09 22:52:49 +00001424 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001425 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001426 std::string next_word;
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001427 StringList matches;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001428 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001429 {
Caroline Tice649116c2011-05-11 16:07:06 +00001430 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001431 std::string suffix;
1432 ExtractCommand (command_string, next_word, suffix, quote_char);
1433 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001434 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001435 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001436 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001437 std::string alias_result;
1438 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1439 revised_command_line.Printf ("%s", alias_result.c_str());
1440 if (cmd_obj)
1441 {
1442 wants_raw_input = cmd_obj->WantsRawCommandString ();
1443 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1444 }
Chris Lattner24943d22010-06-08 16:52:24 +00001445 }
1446 else
1447 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001448 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001449 if (cmd_obj)
1450 {
1451 actual_cmd_name_len += next_word.length();
1452 revised_command_line.Printf ("%s", next_word.c_str());
1453 wants_raw_input = cmd_obj->WantsRawCommandString ();
1454 }
Caroline Tice649116c2011-05-11 16:07:06 +00001455 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001456 {
1457 revised_command_line.Printf ("%s", next_word.c_str());
1458 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001459 }
1460 }
1461 else
1462 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001463 if (cmd_obj->IsMultiwordObject ())
1464 {
1465 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1466 if (sub_cmd_obj)
1467 {
1468 actual_cmd_name_len += next_word.length() + 1;
1469 revised_command_line.Printf (" %s", next_word.c_str());
1470 cmd_obj = sub_cmd_obj;
1471 wants_raw_input = cmd_obj->WantsRawCommandString ();
1472 }
1473 else
1474 {
1475 if (quote_char)
1476 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1477 else
1478 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1479 done = true;
1480 }
1481 }
Caroline Tice649116c2011-05-11 16:07:06 +00001482 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001483 {
1484 if (quote_char)
1485 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1486 else
1487 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1488 done = true;
1489 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001490 }
1491
1492 if (cmd_obj == NULL)
1493 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001494 uint32_t num_matches = matches.GetSize();
1495 if (matches.GetSize() > 1) {
1496 std::string error_msg;
1497 error_msg.assign ("Ambiguous command '");
1498 error_msg.append(next_word.c_str());
1499 error_msg.append ("'.");
1500
1501 error_msg.append (" Possible matches:");
1502
1503 for (uint32_t i = 0; i < num_matches; ++i) {
1504 error_msg.append ("\n\t");
1505 error_msg.append (matches.GetStringAtIndex(i));
1506 }
1507 error_msg.append ("\n");
1508 result.AppendRawError (error_msg.c_str(), error_msg.size());
1509 } else {
1510 // We didn't have only one match, otherwise we wouldn't get here.
1511 assert(num_matches == 0);
1512 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1513 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001514 result.SetStatus (eReturnStatusFailed);
1515 return false;
1516 }
1517
Greg Clayton7268b4c2011-10-28 21:38:01 +00001518 if (cmd_obj->IsMultiwordObject ())
1519 {
1520 if (!suffix.empty())
1521 {
1522
1523 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1524 next_word.c_str(),
1525 suffix.c_str());
1526 result.SetStatus (eReturnStatusFailed);
1527 return false;
1528 }
1529 }
1530 else
1531 {
1532 // If we found a normal command, we are done
1533 done = true;
1534 if (!suffix.empty())
1535 {
1536 switch (suffix[0])
1537 {
1538 case '/':
1539 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001540 {
1541 Options *command_options = cmd_obj->GetOptions();
1542 if (command_options && command_options->SupportsLongOption("gdb-format"))
1543 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001544 std::string gdb_format_option ("--gdb-format=");
1545 gdb_format_option += (suffix.c_str() + 1);
1546
1547 bool inserted = false;
1548 std::string &cmd = revised_command_line.GetString();
1549 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1550 if (arg_terminator_idx != std::string::npos)
1551 {
1552 // Insert the gdb format option before the "--" that terminates options
1553 gdb_format_option.append(1,' ');
1554 cmd.insert(arg_terminator_idx, gdb_format_option);
1555 inserted = true;
1556 }
1557
1558 if (!inserted)
1559 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1560
1561 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1562 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001563 }
1564 else
1565 {
1566 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1567 cmd_obj->GetCommandName());
1568 result.SetStatus (eReturnStatusFailed);
1569 return false;
1570 }
1571 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001572 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001573
1574 default:
1575 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1576 suffix.c_str());
1577 result.SetStatus (eReturnStatusFailed);
1578 return false;
1579
Greg Clayton7268b4c2011-10-28 21:38:01 +00001580 }
1581 }
1582 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001583 if (command_string.length() == 0)
1584 done = true;
1585
Chris Lattner24943d22010-06-08 16:52:24 +00001586 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001587
Greg Clayton7268b4c2011-10-28 21:38:01 +00001588 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001589 revised_command_line.Printf (" %s", command_string.c_str());
1590
1591 // End of Phase 1.
1592 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1593 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1594 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1595 // wants_raw_input specifies whether the Execute method expects raw input or not.
1596
1597
1598 if (log)
1599 {
1600 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1601 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1602 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1603 }
1604
1605 // Phase 2.
1606 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1607 // CommandObject, with the appropriate arguments.
1608
1609 if (cmd_obj != NULL)
1610 {
1611 if (add_to_history)
1612 {
1613 Args command_args (revised_command_line.GetData());
1614 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1615 if (repeat_command != NULL)
1616 m_repeat_command.assign(repeat_command);
1617 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001618 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001619
Jim Ingham6247dbe2011-07-12 03:12:18 +00001620 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001621 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001622 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001623 }
1624
1625 command_string = revised_command_line.GetData();
1626 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001627 std::string remainder;
1628 if (actual_cmd_name_len < command_string.length())
1629 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1630 // than cmd_obj->GetCommandName(), because name completion
1631 // allows users to enter short versions of the names,
1632 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001633
1634 // Remove any initial spaces
1635 std::string white_space (" \t\v");
1636 size_t pos = remainder.find_first_not_of (white_space);
1637 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001638 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001639
1640 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001641 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001642
Jim Inghamda26bd22012-06-08 21:56:10 +00001643 cmd_obj->Execute (remainder.c_str(), result);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001644 }
1645 else
1646 {
1647 // We didn't find the first command object, so complete the first argument.
1648 Args command_args (revised_command_line.GetData());
1649 StringList matches;
1650 int num_matches;
1651 int cursor_index = 0;
1652 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1653 bool word_complete;
1654 num_matches = HandleCompletionMatches (command_args,
1655 cursor_index,
1656 cursor_char_position,
1657 0,
1658 -1,
1659 word_complete,
1660 matches);
1661
1662 if (num_matches > 0)
1663 {
1664 std::string error_msg;
1665 error_msg.assign ("ambiguous command '");
1666 error_msg.append(command_args.GetArgumentAtIndex(0));
1667 error_msg.append ("'.");
1668
1669 error_msg.append (" Possible completions:");
1670 for (int i = 0; i < num_matches; i++)
1671 {
1672 error_msg.append ("\n\t");
1673 error_msg.append (matches.GetStringAtIndex (i));
1674 }
1675 error_msg.append ("\n");
1676 result.AppendRawError (error_msg.c_str(), error_msg.size());
1677 }
1678 else
1679 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1680
1681 result.SetStatus (eReturnStatusFailed);
1682 }
1683
Jason Molenda24c991c2011-08-25 00:20:04 +00001684 if (log)
1685 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1686
Chris Lattner24943d22010-06-08 16:52:24 +00001687 return result.Succeeded();
1688}
1689
1690int
1691CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1692 int &cursor_index,
1693 int &cursor_char_position,
1694 int match_start_point,
1695 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001696 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001697 StringList &matches)
1698{
1699 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001700 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001701
1702 // For any of the command completions a unique match will be a complete word.
1703 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001704
1705 if (cursor_index == -1)
1706 {
1707 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001708 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001709 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1710 }
1711 else if (cursor_index == 0)
1712 {
1713 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001714 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001715 num_command_matches = matches.GetSize();
1716
1717 if (num_command_matches == 1
1718 && cmd_obj && cmd_obj->IsMultiwordObject()
1719 && matches.GetStringAtIndex(0) != NULL
1720 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1721 {
1722 look_for_subcommand = true;
1723 num_command_matches = 0;
1724 matches.DeleteStringAtIndex(0);
1725 parsed_line.AppendArgument ("");
1726 cursor_index++;
1727 cursor_char_position = 0;
1728 }
1729 }
1730
1731 if (cursor_index > 0 || look_for_subcommand)
1732 {
1733 // We are completing further on into a commands arguments, so find the command and tell it
1734 // to complete the command.
1735 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001736 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001737 if (command_object == NULL)
1738 {
1739 return 0;
1740 }
1741 else
1742 {
1743 parsed_line.Shift();
1744 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001745 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001746 cursor_index,
1747 cursor_char_position,
1748 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001749 max_return_elements,
1750 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001751 matches);
1752 }
1753 }
1754
1755 return num_command_matches;
1756
1757}
1758
1759int
1760CommandInterpreter::HandleCompletion (const char *current_line,
1761 const char *cursor,
1762 const char *last_char,
1763 int match_start_point,
1764 int max_return_elements,
1765 StringList &matches)
1766{
1767 // We parse the argument up to the cursor, so the last argument in parsed_line is
1768 // the one containing the cursor, and the cursor is after the last character.
1769
1770 Args parsed_line(current_line, last_char - current_line);
1771 Args partial_parsed_line(current_line, cursor - current_line);
1772
Jim Ingham6247dbe2011-07-12 03:12:18 +00001773 // Don't complete comments, and if the line we are completing is just the history repeat character,
1774 // substitute the appropriate history line.
1775 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1776 if (first_arg)
1777 {
1778 if (first_arg[0] == m_comment_char)
1779 return 0;
1780 else if (first_arg[0] == m_repeat_char)
1781 {
1782 const char *history_string = FindHistoryString (first_arg);
1783 if (history_string != NULL)
1784 {
1785 matches.Clear();
1786 matches.InsertStringAtIndex(0, history_string);
1787 return -2;
1788 }
1789 else
1790 return 0;
1791
1792 }
1793 }
1794
1795
Chris Lattner24943d22010-06-08 16:52:24 +00001796 int num_args = partial_parsed_line.GetArgumentCount();
1797 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1798 int cursor_char_position;
1799
1800 if (cursor_index == -1)
1801 cursor_char_position = 0;
1802 else
1803 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001804
1805 if (cursor > current_line && cursor[-1] == ' ')
1806 {
1807 // We are just after a space. If we are in an argument, then we will continue
1808 // parsing, but if we are between arguments, then we have to complete whatever the next
1809 // element would be.
1810 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1811 // protected by a quote) then the space will also be in the parsed argument...
1812
1813 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1814 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1815 {
1816 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1817 cursor_index++;
1818 cursor_char_position = 0;
1819 }
1820 }
Chris Lattner24943d22010-06-08 16:52:24 +00001821
1822 int num_command_matches;
1823
1824 matches.Clear();
1825
1826 // Only max_return_elements == -1 is supported at present:
1827 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001828 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001829 num_command_matches = HandleCompletionMatches (parsed_line,
1830 cursor_index,
1831 cursor_char_position,
1832 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001833 max_return_elements,
1834 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001835 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001836
1837 if (num_command_matches <= 0)
1838 return num_command_matches;
1839
1840 if (num_args == 0)
1841 {
1842 // If we got an empty string, insert nothing.
1843 matches.InsertStringAtIndex(0, "");
1844 }
1845 else
1846 {
1847 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1848 // put an empty string in element 0.
1849 std::string command_partial_str;
1850 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001851 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1852 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001853
1854 std::string common_prefix;
1855 matches.LongestCommonPrefix (common_prefix);
1856 int partial_name_len = command_partial_str.size();
1857
1858 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001859 // Only do this if the completer told us this was a complete word, however...
1860 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001861 {
1862 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1863 if (quote_char != '\0')
1864 common_prefix.push_back(quote_char);
1865
1866 common_prefix.push_back(' ');
1867 }
1868 common_prefix.erase (0, partial_name_len);
1869 matches.InsertStringAtIndex(0, common_prefix.c_str());
1870 }
1871 return num_command_matches;
1872}
1873
Chris Lattner24943d22010-06-08 16:52:24 +00001874
1875CommandInterpreter::~CommandInterpreter ()
1876{
1877}
1878
1879const char *
1880CommandInterpreter::GetPrompt ()
1881{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001882 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001883}
1884
1885void
1886CommandInterpreter::SetPrompt (const char *new_prompt)
1887{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001888 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001889}
1890
Jim Ingham5e16ef52010-10-04 19:49:29 +00001891size_t
Greg Clayton58928562011-02-09 01:08:52 +00001892CommandInterpreter::GetConfirmationInputReaderCallback
1893(
1894 void *baton,
1895 InputReader &reader,
1896 lldb::InputReaderAction action,
1897 const char *bytes,
1898 size_t bytes_len
1899)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001900{
Greg Clayton58928562011-02-09 01:08:52 +00001901 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001902 bool *response_ptr = (bool *) baton;
1903
1904 switch (action)
1905 {
1906 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001907 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001908 {
1909 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001910 {
Greg Clayton58928562011-02-09 01:08:52 +00001911 out_file.Printf ("%s", reader.GetPrompt());
1912 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001913 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001914 }
1915 break;
1916
1917 case eInputReaderDeactivate:
1918 break;
1919
1920 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001921 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001922 {
Greg Clayton58928562011-02-09 01:08:52 +00001923 out_file.Printf ("%s", reader.GetPrompt());
1924 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001925 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001926 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001927
1928 case eInputReaderAsynchronousOutputWritten:
1929 break;
1930
Jim Ingham5e16ef52010-10-04 19:49:29 +00001931 case eInputReaderGotToken:
1932 if (bytes_len == 0)
1933 {
1934 reader.SetIsDone(true);
1935 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001936 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001937 {
1938 *response_ptr = true;
1939 reader.SetIsDone(true);
1940 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001941 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001942 {
1943 *response_ptr = false;
1944 reader.SetIsDone(true);
1945 }
1946 else
1947 {
Greg Clayton58928562011-02-09 01:08:52 +00001948 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001949 {
Jim Ingham26183802011-11-17 01:22:00 +00001950 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00001951 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001952 }
1953 }
1954 break;
1955
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001956 case eInputReaderInterrupt:
1957 case eInputReaderEndOfFile:
1958 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1959 reader.SetIsDone (true);
1960 break;
1961
Jim Ingham5e16ef52010-10-04 19:49:29 +00001962 case eInputReaderDone:
1963 break;
1964 }
1965
1966 return bytes_len;
1967
1968}
1969
1970bool
1971CommandInterpreter::Confirm (const char *message, bool default_answer)
1972{
Jim Ingham93057472010-10-04 22:44:14 +00001973 // Check AutoConfirm first:
1974 if (m_debugger.GetAutoConfirm())
1975 return default_answer;
1976
Jim Ingham5e16ef52010-10-04 19:49:29 +00001977 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1978 bool response = default_answer;
1979 if (reader_sp)
1980 {
1981 std::string prompt(message);
1982 prompt.append(": [");
1983 if (default_answer)
1984 prompt.append ("Y/n] ");
1985 else
1986 prompt.append ("y/N] ");
1987
1988 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1989 &response, // baton
1990 eInputReaderGranularityLine, // token size, to pass to callback function
1991 NULL, // end token
1992 prompt.c_str(), // prompt
1993 true)); // echo input
1994 if (err.Success())
1995 {
1996 GetDebugger().PushInputReader (reader_sp);
1997 }
1998 reader_sp->WaitOnReaderIsDone();
1999 }
2000 return response;
2001}
2002
2003
Chris Lattner24943d22010-06-08 16:52:24 +00002004void
2005CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
2006{
Jim Inghamd40f8a62010-07-06 22:46:59 +00002007 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00002008
Sean Callananb386d822012-08-09 00:50:26 +00002009 if (cmd_obj_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002010 {
2011 CommandObject *cmd_obj = cmd_obj_sp.get();
2012 if (cmd_obj->IsCrossRefObject ())
2013 cmd_obj->AddObject (object_type);
2014 }
2015}
2016
Chris Lattner24943d22010-06-08 16:52:24 +00002017OptionArgVectorSP
2018CommandInterpreter::GetAliasOptions (const char *alias_name)
2019{
2020 OptionArgMap::iterator pos;
2021 OptionArgVectorSP ret_val;
2022
2023 std::string alias (alias_name);
2024
2025 if (HasAliasOptions())
2026 {
2027 pos = m_alias_options.find (alias);
2028 if (pos != m_alias_options.end())
2029 ret_val = pos->second;
2030 }
2031
2032 return ret_val;
2033}
2034
2035void
2036CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2037{
2038 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2039 if (pos != m_alias_options.end())
2040 {
2041 m_alias_options.erase (pos);
2042 }
2043}
2044
2045void
2046CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2047{
2048 m_alias_options[alias_name] = option_arg_vector_sp;
2049}
2050
2051bool
2052CommandInterpreter::HasCommands ()
2053{
2054 return (!m_command_dict.empty());
2055}
2056
2057bool
2058CommandInterpreter::HasAliases ()
2059{
2060 return (!m_alias_dict.empty());
2061}
2062
2063bool
2064CommandInterpreter::HasUserCommands ()
2065{
2066 return (!m_user_dict.empty());
2067}
2068
2069bool
2070CommandInterpreter::HasAliasOptions ()
2071{
2072 return (!m_alias_options.empty());
2073}
2074
Chris Lattner24943d22010-06-08 16:52:24 +00002075void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002076CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2077 const char *alias_name,
2078 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00002079 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002080 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00002081{
2082 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00002083
2084 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00002085
Caroline Tice44c841d2010-12-07 19:58:26 +00002086 // Make sure that the alias name is the 0th element in cmd_args
2087 std::string alias_name_str = alias_name;
2088 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2089 cmd_args.Unshift (alias_name);
2090
2091 Args new_args (alias_cmd_obj->GetCommandName());
2092 if (new_args.GetArgumentCount() == 2)
2093 new_args.Shift();
2094
Chris Lattner24943d22010-06-08 16:52:24 +00002095 if (option_arg_vector_sp.get())
2096 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002097 if (wants_raw_input)
2098 {
2099 // We have a command that both has command options and takes raw input. Make *sure* it has a
2100 // " -- " in the right place in the raw_input_string.
2101 size_t pos = raw_input_string.find(" -- ");
2102 if (pos == std::string::npos)
2103 {
2104 // None found; assume it goes at the beginning of the raw input string
2105 raw_input_string.insert (0, " -- ");
2106 }
2107 }
Chris Lattner24943d22010-06-08 16:52:24 +00002108
2109 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2110 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002111 std::vector<bool> used (old_size + 1, false);
2112
2113 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002114
2115 for (int i = 0; i < option_arg_vector->size(); ++i)
2116 {
2117 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00002118 OptionArgValue value_pair = option_pair.second;
2119 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00002120 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00002121 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00002122 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002123 {
2124 if (!wants_raw_input
2125 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2126 new_args.AppendArgument (value.c_str());
2127 }
Chris Lattner24943d22010-06-08 16:52:24 +00002128 else
2129 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002130 if (value_type != optional_argument)
2131 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002132 if (value.compare ("<no-argument>") != 0)
2133 {
2134 int index = GetOptionArgumentPosition (value.c_str());
2135 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002136 {
Chris Lattner24943d22010-06-08 16:52:24 +00002137 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002138 if (value_type != optional_argument)
2139 new_args.AppendArgument (value.c_str());
2140 else
2141 {
2142 char buffer[255];
2143 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2144 new_args.AppendArgument (buffer);
2145 }
2146
2147 }
Chris Lattner24943d22010-06-08 16:52:24 +00002148 else if (index >= cmd_args.GetArgumentCount())
2149 {
2150 result.AppendErrorWithFormat
2151 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2152 index);
2153 result.SetStatus (eReturnStatusFailed);
2154 return;
2155 }
2156 else
2157 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002158 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2159 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2160 if (strpos != std::string::npos)
2161 {
2162 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2163 }
2164
2165 if (value_type != optional_argument)
2166 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2167 else
2168 {
2169 char buffer[255];
2170 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2171 cmd_args.GetArgumentAtIndex (index));
2172 new_args.AppendArgument (buffer);
2173 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002174 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002175 }
2176 }
2177 }
2178 }
2179
2180 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2181 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002182 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002183 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2184 }
2185
2186 cmd_args.Clear();
2187 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2188 }
2189 else
2190 {
2191 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002192 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2193 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2194 // input string.
2195 if (wants_raw_input)
2196 {
2197 cmd_args.Clear();
2198 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2199 }
Chris Lattner24943d22010-06-08 16:52:24 +00002200 return;
2201 }
2202
2203 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2204 return;
2205}
2206
2207
2208int
2209CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2210{
2211 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2212 // of zero.
2213
2214 char *cptr = (char *) in_string;
2215
2216 // Does it start with '%'
2217 if (cptr[0] == '%')
2218 {
2219 ++cptr;
2220
2221 // Is the rest of it entirely digits?
2222 if (isdigit (cptr[0]))
2223 {
2224 const char *start = cptr;
2225 while (isdigit (cptr[0]))
2226 ++cptr;
2227
2228 // We've gotten to the end of the digits; are we at the end of the string?
2229 if (cptr[0] == '\0')
2230 position = atoi (start);
2231 }
2232 }
2233
2234 return position;
2235}
2236
2237void
2238CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2239{
Jim Ingham574c3d62011-08-12 23:34:31 +00002240 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002241 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002242 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002243 // In the current working directory we don't load any program specific
2244 // .lldbinit files, we only look for a "./.lldbinit" file.
2245 if (m_skip_lldbinit_files)
2246 return;
2247
2248 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002249 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002250 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002251 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002252 // If we aren't looking in the current working directory we are looking
2253 // in the home directory. We will first see if there is an application
2254 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2255 // "-" and the name of the program. If this file doesn't exist, we fall
2256 // back to just the "~/.lldbinit" file. We also obey any requests to not
2257 // load the init files.
2258 const char *init_file_path = "~/.lldbinit";
2259
2260 if (m_skip_app_init_files == false)
2261 {
2262 FileSpec program_file_spec (Host::GetProgramFileSpec());
2263 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002264
Greg Claytond6edcb52011-09-11 00:01:44 +00002265 if (program_name)
2266 {
2267 char program_init_file_name[PATH_MAX];
2268 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2269 init_file.SetFile (program_init_file_name, true);
2270 if (!init_file.Exists())
2271 init_file.Clear();
2272 }
2273 }
2274
2275 if (!init_file && !m_skip_lldbinit_files)
2276 init_file.SetFile (init_file_path, true);
2277 }
2278
Chris Lattner24943d22010-06-08 16:52:24 +00002279 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2280 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2281
2282 if (init_file.Exists())
2283 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002284 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2285 bool stop_on_continue = true;
2286 bool stop_on_error = false;
2287 bool echo_commands = false;
2288 bool print_results = false;
2289
Enrico Granata01bc2d42012-05-31 01:09:06 +00002290 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002291 }
2292 else
2293 {
2294 // nothing to be done if the file doesn't exist
2295 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2296 }
2297}
2298
Greg Claytonb72d0f02011-04-12 05:54:46 +00002299PlatformSP
2300CommandInterpreter::GetPlatform (bool prefer_target_platform)
2301{
2302 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002303 if (prefer_target_platform)
2304 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002305 ExecutionContext exe_ctx(GetExecutionContext());
2306 Target *target = exe_ctx.GetTargetPtr();
Greg Clayton567e7f32011-09-22 04:58:26 +00002307 if (target)
2308 platform_sp = target->GetPlatform();
2309 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002310
2311 if (!platform_sp)
2312 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2313 return platform_sp;
2314}
2315
Jim Ingham949d5ac2011-02-18 00:54:25 +00002316void
Jim Inghama4fede32011-03-11 01:51:49 +00002317CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002318 ExecutionContext *override_context,
2319 bool stop_on_continue,
2320 bool stop_on_error,
2321 bool echo_commands,
2322 bool print_results,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002323 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002324 CommandReturnObject &result)
2325{
2326 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002327
2328 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2329 // Make sure you reset this value anywhere you return from the function.
2330
2331 bool old_async_execution = m_debugger.GetAsyncExecution();
2332
2333 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2334 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2335
2336 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002337 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002338
2339 if (!stop_on_continue)
2340 {
2341 m_debugger.SetAsyncExecution (false);
2342 }
2343
2344 for (int idx = 0; idx < num_lines; idx++)
2345 {
2346 const char *cmd = commands.GetStringAtIndex(idx);
2347 if (cmd[0] == '\0')
2348 continue;
2349
Jim Ingham949d5ac2011-02-18 00:54:25 +00002350 if (echo_commands)
2351 {
2352 result.AppendMessageWithFormat ("%s %s\n",
2353 GetPrompt(),
2354 cmd);
2355 }
2356
Greg Claytonaa378b12011-02-20 02:15:07 +00002357 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002358 // If override_context is not NULL, pass no_context_switching = true for
2359 // HandleCommand() since we updated our context already.
Enrico Granata01bc2d42012-05-31 01:09:06 +00002360 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002361 NULL, /* override_context */
2362 true, /* repeat_on_empty_command */
2363 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002364
2365 if (print_results)
2366 {
2367 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002368 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002369 }
2370
2371 if (!success || !tmp_result.Succeeded())
2372 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002373 const char *error_msg = tmp_result.GetErrorData();
2374 if (error_msg == NULL || error_msg[0] == '\0')
2375 error_msg = "<unknown error>.\n";
Jim Ingham949d5ac2011-02-18 00:54:25 +00002376 if (stop_on_error)
2377 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002378 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2379 idx, cmd, error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002380 result.SetStatus (eReturnStatusFailed);
2381 m_debugger.SetAsyncExecution (old_async_execution);
2382 return;
2383 }
2384 else if (print_results)
2385 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002386 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Ingham949d5ac2011-02-18 00:54:25 +00002387 idx + 1,
2388 cmd,
Jim Ingham862fd5c2012-04-24 02:25:07 +00002389 error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002390 }
2391 }
2392
Caroline Tice4a348082011-05-02 20:41:46 +00002393 if (result.GetImmediateOutputStream())
2394 result.GetImmediateOutputStream()->Flush();
2395
2396 if (result.GetImmediateErrorStream())
2397 result.GetImmediateErrorStream()->Flush();
2398
Jim Ingham949d5ac2011-02-18 00:54:25 +00002399 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2400 // could be running (for instance in Breakpoint Commands.
2401 // So we check the return value to see if it is has running in it.
2402 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2403 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2404 {
2405 if (stop_on_continue)
2406 {
2407 // If we caused the target to proceed, and we're going to stop in that case, set the
2408 // status in our real result before returning. This is an error if the continue was not the
2409 // last command in the set of commands to be run.
2410 if (idx != num_lines - 1)
2411 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2412 idx + 1, cmd);
2413 else
2414 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2415
2416 result.SetStatus(tmp_result.GetStatus());
2417 m_debugger.SetAsyncExecution (old_async_execution);
2418
2419 return;
2420 }
2421 }
2422
2423 }
2424
2425 result.SetStatus (eReturnStatusSuccessFinishResult);
2426 m_debugger.SetAsyncExecution (old_async_execution);
2427
2428 return;
2429}
2430
2431void
2432CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2433 ExecutionContext *context,
2434 bool stop_on_continue,
2435 bool stop_on_error,
2436 bool echo_command,
2437 bool print_result,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002438 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002439 CommandReturnObject &result)
2440{
2441 if (cmd_file.Exists())
2442 {
2443 bool success;
2444 StringList commands;
2445 success = commands.ReadFileLines(cmd_file);
2446 if (!success)
2447 {
2448 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2449 result.SetStatus (eReturnStatusFailed);
2450 return;
2451 }
Enrico Granata01bc2d42012-05-31 01:09:06 +00002452 m_command_source_depth++;
2453 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2454 m_command_source_depth--;
Jim Ingham949d5ac2011-02-18 00:54:25 +00002455 }
2456 else
2457 {
2458 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2459 cmd_file.GetFilename().AsCString());
2460 result.SetStatus (eReturnStatusFailed);
2461 return;
2462 }
2463}
2464
Chris Lattner24943d22010-06-08 16:52:24 +00002465ScriptInterpreter *
2466CommandInterpreter::GetScriptInterpreter ()
2467{
Enrico Granatac5c10a42012-07-10 18:23:48 +00002468 // <rdar://problem/11751427>
2469 // we need to protect the initialization of the script interpreter
2470 // otherwise we could end up with two threads both trying to create
2471 // their instance of it, and for some languages (e.g. Python)
2472 // this is a bulletproof recipe for disaster!
2473 // this needs to be a function-level static because multiple Debugger instances living in the same process
2474 // still need to be isolated and not try to initialize Python concurrently
Enrico Granatab88c0a92012-07-10 19:04:14 +00002475 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2476 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granatac5c10a42012-07-10 18:23:48 +00002477
Caroline Tice0aa2e552011-01-14 00:29:16 +00002478 if (m_script_interpreter_ap.get() != NULL)
2479 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002480
Caroline Tice0aa2e552011-01-14 00:29:16 +00002481 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2482 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002483 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002484 case eScriptLanguagePython:
2485#ifndef LLDB_DISABLE_PYTHON
2486 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2487 break;
2488#else
2489 // Fall through to the None case when python is disabled
2490#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002491 case eScriptLanguageNone:
2492 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2493 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002494 default:
2495 break;
2496 };
2497
2498 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002499}
2500
2501
2502
2503bool
2504CommandInterpreter::GetSynchronous ()
2505{
2506 return m_synchronous_execution;
2507}
2508
2509void
2510CommandInterpreter::SetSynchronous (bool value)
2511{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002512 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002513}
2514
2515void
2516CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2517 const char *word_text,
2518 const char *separator,
2519 const char *help_text,
2520 uint32_t max_word_len)
2521{
Greg Clayton238c0a12010-09-18 01:14:36 +00002522 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2523
Chris Lattner24943d22010-06-08 16:52:24 +00002524 int indent_size = max_word_len + strlen (separator) + 2;
2525
2526 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002527
2528 StreamString text_strm;
2529 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2530
2531 size_t len = text_strm.GetSize();
2532 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002533 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002534 {
2535 text_strm.EOL();
2536 len = text_strm.GetSize();
2537 }
Chris Lattner24943d22010-06-08 16:52:24 +00002538
2539 if (len < max_columns)
2540 {
2541 // Output it as a single line.
2542 strm.Printf ("%s", text);
2543 }
2544 else
2545 {
2546 // We need to break it up into multiple lines.
2547 bool first_line = true;
2548 int text_width;
2549 int start = 0;
2550 int end = start;
2551 int final_end = strlen (text);
2552 int sub_len;
2553
2554 while (end < final_end)
2555 {
2556 if (first_line)
2557 text_width = max_columns - 1;
2558 else
2559 text_width = max_columns - indent_size - 1;
2560
2561 // Don't start the 'text' on a space, since we're already outputting the indentation.
2562 if (!first_line)
2563 {
2564 while ((start < final_end) && (text[start] == ' '))
2565 start++;
2566 }
2567
2568 end = start + text_width;
2569 if (end > final_end)
2570 end = final_end;
2571 else
2572 {
2573 // If we're not at the end of the text, make sure we break the line on white space.
2574 while (end > start
2575 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2576 end--;
Greg Clayton73844aa2012-08-22 17:17:09 +00002577 assert (end > 0);
Chris Lattner24943d22010-06-08 16:52:24 +00002578 }
2579
2580 sub_len = end - start;
2581 if (start != 0)
2582 strm.EOL();
2583 if (!first_line)
2584 strm.Indent();
2585 else
2586 first_line = false;
2587 assert (start <= final_end);
2588 assert (start + sub_len <= final_end);
2589 if (sub_len > 0)
2590 strm.Write (text + start, sub_len);
2591 start = end + 1;
2592 }
2593 }
2594 strm.EOL();
2595 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002596}
2597
2598void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002599CommandInterpreter::OutputHelpText (Stream &strm,
2600 const char *word_text,
2601 const char *separator,
2602 const char *help_text,
2603 uint32_t max_word_len)
2604{
2605 int indent_size = max_word_len + strlen (separator) + 2;
2606
2607 strm.IndentMore (indent_size);
2608
2609 StreamString text_strm;
2610 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2611
2612 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata1bba6e52011-07-07 00:38:40 +00002613
2614 size_t len = text_strm.GetSize();
2615 const char *text = text_strm.GetData();
2616
2617 uint32_t chars_left = max_columns;
2618
2619 for (uint32_t i = 0; i < len; i++)
2620 {
2621 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2622 {
Enrico Granata1bba6e52011-07-07 00:38:40 +00002623 chars_left = max_columns - indent_size;
2624 strm.EOL();
2625 strm.Indent();
2626 }
2627 else
2628 {
2629 strm.PutChar(text[i]);
2630 chars_left--;
2631 }
2632
2633 }
2634
2635 strm.EOL();
2636 strm.IndentLess(indent_size);
2637}
2638
2639void
Chris Lattner24943d22010-06-08 16:52:24 +00002640CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2641 StringList &commands_found, StringList &commands_help)
2642{
2643 CommandObject::CommandMap::const_iterator pos;
2644 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2645 CommandObject *sub_cmd_obj;
2646
2647 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2648 {
2649 const char * command_name = pos->first.c_str();
2650 sub_cmd_obj = pos->second.get();
2651 StreamString complete_command_name;
2652
2653 complete_command_name.Printf ("%s %s", prefix, command_name);
2654
Greg Clayton238c0a12010-09-18 01:14:36 +00002655 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002656 {
2657 commands_found.AppendString (complete_command_name.GetData());
2658 commands_help.AppendString (sub_cmd_obj->GetHelp());
2659 }
2660
2661 if (sub_cmd_obj->IsMultiwordObject())
2662 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2663 commands_help);
2664 }
2665
2666}
2667
2668void
2669CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2670 StringList &commands_help)
2671{
2672 CommandObject::CommandMap::const_iterator pos;
2673
2674 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2675 {
2676 const char *command_name = pos->first.c_str();
2677 CommandObject *cmd_obj = pos->second.get();
2678
Greg Clayton238c0a12010-09-18 01:14:36 +00002679 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002680 {
2681 commands_found.AppendString (command_name);
2682 commands_help.AppendString (cmd_obj->GetHelp());
2683 }
2684
2685 if (cmd_obj->IsMultiwordObject())
2686 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2687
2688 }
2689}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002690
2691
2692void
2693CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2694{
Greg Claytonb72d0f02011-04-12 05:54:46 +00002695 if (override_context != NULL)
2696 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002697 m_exe_ctx_ref = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002698 }
2699 else
2700 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002701 const bool adopt_selected = true;
2702 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002703 }
2704}
2705
Jim Ingham6247dbe2011-07-12 03:12:18 +00002706void
2707CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2708{
2709 DumpHistory (stream, 0, count - 1);
2710}
2711
2712void
2713CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2714{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002715 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2716 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002717 {
2718 if (!m_command_history[i].empty())
2719 {
2720 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002721 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002722 }
2723 }
2724}
2725
2726const char *
2727CommandInterpreter::FindHistoryString (const char *input_str) const
2728{
2729 if (input_str[0] != m_repeat_char)
2730 return NULL;
2731 if (input_str[1] == '-')
2732 {
2733 bool success;
2734 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2735 if (!success)
2736 return NULL;
2737 if (idx > m_command_history.size())
2738 return NULL;
2739 idx = m_command_history.size() - idx;
2740 return m_command_history[idx].c_str();
2741
2742 }
2743 else if (input_str[1] == m_repeat_char)
2744 {
2745 if (m_command_history.empty())
2746 return NULL;
2747 else
2748 return m_command_history.back().c_str();
2749 }
2750 else
2751 {
2752 bool success;
2753 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2754 if (!success)
2755 return NULL;
2756 if (idx >= m_command_history.size())
2757 return NULL;
2758 return m_command_history[idx].c_str();
2759 }
2760}