blob: 62c11974d9cb1c3064b052fab6a16c00b64fbe70 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012#include <string>
Caroline Tice4ab31c92010-10-12 21:57:09 +000013#include <vector>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000014
15#include <getopt.h>
16#include <stdlib.h>
17
Greg Clayton4a33d312011-06-23 17:59:56 +000018#include "CommandObjectScript.h"
Peter Collingbourne08405b62011-06-23 20:37:26 +000019#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000020
Eli Friedman3afb70c2010-06-13 02:17:17 +000021#include "../Commands/CommandObjectApropos.h"
22#include "../Commands/CommandObjectArgs.h"
23#include "../Commands/CommandObjectBreakpoint.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000024#include "../Commands/CommandObjectDisassemble.h"
25#include "../Commands/CommandObjectExpression.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectFrame.h"
27#include "../Commands/CommandObjectHelp.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000028#include "../Commands/CommandObjectLog.h"
29#include "../Commands/CommandObjectMemory.h"
Greg Claytonded470d2011-03-19 01:12:21 +000030#include "../Commands/CommandObjectPlatform.h"
Enrico Granata21dfcd92012-09-28 23:57:51 +000031#include "../Commands/CommandObjectPlugin.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000032#include "../Commands/CommandObjectProcess.h"
33#include "../Commands/CommandObjectQuit.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectRegister.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSettings.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000036#include "../Commands/CommandObjectSource.h"
Jim Inghamebc09c32010-07-07 03:36:20 +000037#include "../Commands/CommandObjectCommands.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000038#include "../Commands/CommandObjectSyntax.h"
39#include "../Commands/CommandObjectTarget.h"
40#include "../Commands/CommandObjectThread.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000041#include "../Commands/CommandObjectType.h"
Johnny Chen31c39da2010-12-23 20:21:44 +000042#include "../Commands/CommandObjectVersion.h"
Johnny Chenf04ee932011-09-22 18:04:58 +000043#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044
Chris Lattner30fdc8d2010-06-08 16:52:24 +000045#include "lldb/Core/Debugger.h"
Jim Ingham97a6dc72010-10-04 19:49:29 +000046#include "lldb/Core/InputReader.h"
Enrico Granatab5887262012-10-29 21:18:03 +000047#include "lldb/Core/Log.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048#include "lldb/Core/Stream.h"
49#include "lldb/Core/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000050
Greg Clayton7fb56d02011-02-01 01:31:41 +000051#include "lldb/Host/Host.h"
Enrico Granatab5887262012-10-29 21:18:03 +000052
53#include "lldb/Interpreter/Args.h"
54#include "lldb/Interpreter/CommandReturnObject.h"
55#include "lldb/Interpreter/CommandInterpreter.h"
56#include "lldb/Interpreter/Options.h"
57#include "lldb/Interpreter/ScriptInterpreterNone.h"
58#include "lldb/Interpreter/ScriptInterpreterPython.h"
59
60
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061#include "lldb/Target/Process.h"
62#include "lldb/Target/Thread.h"
63#include "lldb/Target/TargetList.h"
64
Enrico Granatab5887262012-10-29 21:18:03 +000065#include "lldb/Utility/CleanUp.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066
67using namespace lldb;
68using namespace lldb_private;
69
Greg Clayton754a9362012-08-23 00:22:02 +000070
71static PropertyDefinition
72g_properties[] =
73{
74 { "expand-regex-aliases", OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, regular expression alias commands will show the expanded command that will be executed. This can be used to debug new regular expression alias commands." },
Enrico Granatabcba2b22013-01-17 21:36:19 +000075 { "prompt-on-quit", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, LLDB will prompt you before quitting if there are any live processes being debugged. If false, LLDB will quit without asking in any case." },
Greg Clayton754a9362012-08-23 00:22:02 +000076 { NULL , OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL }
77};
78
79enum
80{
Enrico Granatabcba2b22013-01-17 21:36:19 +000081 ePropertyExpandRegexAliases = 0,
82 ePropertyPromptOnQuit = 1
Greg Clayton754a9362012-08-23 00:22:02 +000083};
84
Jim Ingham4bddaeb2012-02-16 06:50:00 +000085ConstString &
86CommandInterpreter::GetStaticBroadcasterClass ()
87{
88 static ConstString class_name ("lldb.commandInterpreter");
89 return class_name;
90}
91
Chris Lattner30fdc8d2010-06-08 16:52:24 +000092CommandInterpreter::CommandInterpreter
93(
Greg Clayton66111032010-06-23 01:19:29 +000094 Debugger &debugger,
Chris Lattner30fdc8d2010-06-08 16:52:24 +000095 ScriptLanguage script_language,
Greg Clayton66111032010-06-23 01:19:29 +000096 bool synchronous_execution
Chris Lattner30fdc8d2010-06-08 16:52:24 +000097) :
Jim Ingham4bddaeb2012-02-16 06:50:00 +000098 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton754a9362012-08-23 00:22:02 +000099 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton66111032010-06-23 01:19:29 +0000100 m_debugger (debugger),
Greg Clayton6eee5aa2010-10-11 01:05:37 +0000101 m_synchronous_execution (synchronous_execution),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000102 m_skip_lldbinit_files (false),
Jim Ingham16e0c682011-08-12 23:34:31 +0000103 m_skip_app_init_files (false),
Jim Inghame16c50a2011-02-18 00:54:25 +0000104 m_script_interpreter_ap (),
Caroline Ticed61c10b2011-06-16 16:27:19 +0000105 m_comment_char ('#'),
Jim Inghama5a97eb2011-07-12 03:12:18 +0000106 m_repeat_char ('!'),
Johnny Chen4ac1d9e2012-08-09 22:06:10 +0000107 m_batch_command_mode (false),
Enrico Granata5f5ab602012-05-31 01:09:06 +0000108 m_truncation_warning(eNoTruncation),
109 m_command_source_depth (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000110{
Greg Clayton67cc0632012-08-22 17:17:09 +0000111 debugger.SetScriptLanguage (script_language);
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000112 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
113 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton67cc0632012-08-22 17:17:09 +0000114 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000115 CheckInWithManager ();
Greg Clayton754a9362012-08-23 00:22:02 +0000116 m_collection_sp->Initialize (g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000117}
118
Greg Clayton754a9362012-08-23 00:22:02 +0000119bool
120CommandInterpreter::GetExpandRegexAliases () const
121{
122 const uint32_t idx = ePropertyExpandRegexAliases;
123 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
124}
125
Enrico Granatabcba2b22013-01-17 21:36:19 +0000126bool
127CommandInterpreter::GetPromptOnQuit () const
128{
129 const uint32_t idx = ePropertyPromptOnQuit;
130 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
131}
Greg Clayton754a9362012-08-23 00:22:02 +0000132
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000133void
134CommandInterpreter::Initialize ()
135{
136 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
137
138 CommandReturnObject result;
139
140 LoadCommandDictionary ();
141
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000142 // Set up some initial aliases.
Caroline Ticeca90c472011-05-06 21:37:15 +0000143 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
144 if (cmd_obj_sp)
145 {
146 AddAlias ("q", cmd_obj_sp);
147 AddAlias ("exit", cmd_obj_sp);
148 }
Sean Callanan247e62a2012-05-04 23:15:02 +0000149
Johnny Chen6d675242012-08-24 18:15:45 +0000150 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callanan247e62a2012-05-04 23:15:02 +0000151 if (cmd_obj_sp)
152 {
153 AddAlias ("attach", cmd_obj_sp);
154 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000155
Johnny Chen6d675242012-08-24 18:15:45 +0000156 cmd_obj_sp = GetCommandSPExact ("process detach",false);
157 if (cmd_obj_sp)
158 {
159 AddAlias ("detach", cmd_obj_sp);
160 }
161
Caroline Ticeca90c472011-05-06 21:37:15 +0000162 cmd_obj_sp = GetCommandSPExact ("process continue", false);
163 if (cmd_obj_sp)
164 {
165 AddAlias ("c", cmd_obj_sp);
166 AddAlias ("continue", cmd_obj_sp);
167 }
168
169 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
170 if (cmd_obj_sp)
171 AddAlias ("b", cmd_obj_sp);
172
Jim Inghamca36cd12012-10-05 19:16:31 +0000173 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
174 if (cmd_obj_sp)
175 AddAlias ("tbreak", cmd_obj_sp);
176
Caroline Ticeca90c472011-05-06 21:37:15 +0000177 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
178 if (cmd_obj_sp)
Jason Molendaf385f122011-10-22 00:47:41 +0000179 {
180 AddAlias ("stepi", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000181 AddAlias ("si", cmd_obj_sp);
Jason Molendaf385f122011-10-22 00:47:41 +0000182 }
183
184 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
185 if (cmd_obj_sp)
186 {
187 AddAlias ("nexti", cmd_obj_sp);
188 AddAlias ("ni", cmd_obj_sp);
189 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000190
191 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
192 if (cmd_obj_sp)
193 {
194 AddAlias ("s", cmd_obj_sp);
195 AddAlias ("step", cmd_obj_sp);
196 }
197
198 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
199 if (cmd_obj_sp)
200 {
201 AddAlias ("n", cmd_obj_sp);
202 AddAlias ("next", cmd_obj_sp);
203 }
204
205 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
206 if (cmd_obj_sp)
207 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000208 AddAlias ("finish", cmd_obj_sp);
209 }
210
Jim Ingham6d6d1072011-12-02 01:12:59 +0000211 cmd_obj_sp = GetCommandSPExact ("frame select", false);
212 if (cmd_obj_sp)
213 {
214 AddAlias ("f", cmd_obj_sp);
215 }
216
Jim Inghamca36cd12012-10-05 19:16:31 +0000217 cmd_obj_sp = GetCommandSPExact ("thread select", false);
218 if (cmd_obj_sp)
219 {
220 AddAlias ("t", cmd_obj_sp);
221 }
222
Caroline Ticeca90c472011-05-06 21:37:15 +0000223 cmd_obj_sp = GetCommandSPExact ("source list", false);
224 if (cmd_obj_sp)
225 {
226 AddAlias ("l", cmd_obj_sp);
227 AddAlias ("list", cmd_obj_sp);
228 }
229
230 cmd_obj_sp = GetCommandSPExact ("memory read", false);
231 if (cmd_obj_sp)
232 AddAlias ("x", cmd_obj_sp);
233
234 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
235 if (cmd_obj_sp)
236 AddAlias ("up", cmd_obj_sp);
237
238 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
239 if (cmd_obj_sp)
240 AddAlias ("down", cmd_obj_sp);
241
Jason Molenda0c8e0062011-10-25 02:11:20 +0000242 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000243 if (cmd_obj_sp)
244 AddAlias ("display", cmd_obj_sp);
Jim Ingham7e18e422011-10-24 18:37:00 +0000245
246 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
247 if (cmd_obj_sp)
248 AddAlias ("dis", cmd_obj_sp);
249
250 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
251 if (cmd_obj_sp)
252 AddAlias ("di", cmd_obj_sp);
253
254
Jason Molendabc7748b2011-10-22 01:30:52 +0000255
Jason Molenda0c8e0062011-10-25 02:11:20 +0000256 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000257 if (cmd_obj_sp)
258 AddAlias ("undisplay", cmd_obj_sp);
259
Jim Ingham71bf2992012-10-10 16:51:31 +0000260 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
261 if (cmd_obj_sp)
262 AddAlias ("bt", cmd_obj_sp);
263
Caroline Ticeca90c472011-05-06 21:37:15 +0000264 cmd_obj_sp = GetCommandSPExact ("target create", false);
265 if (cmd_obj_sp)
266 AddAlias ("file", cmd_obj_sp);
267
268 cmd_obj_sp = GetCommandSPExact ("target modules", false);
269 if (cmd_obj_sp)
270 AddAlias ("image", cmd_obj_sp);
271
272
273 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghamffba2292011-03-22 02:29:32 +0000274
Caroline Ticeca90c472011-05-06 21:37:15 +0000275 cmd_obj_sp = GetCommandSPExact ("expression", false);
276 if (cmd_obj_sp)
277 {
278 AddAlias ("expr", cmd_obj_sp);
279
280 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
281 AddAlias ("p", cmd_obj_sp);
282 AddAlias ("print", cmd_obj_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000283 AddAlias ("call", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000284 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
285 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000286 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000287
288 alias_arguments_vector_sp.reset (new OptionArgVector);
Enrico Granata7b8c5132012-12-12 03:23:37 +0000289 ProcessAliasOptionsArgs (cmd_obj_sp, "-O --", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000290 AddAlias ("po", cmd_obj_sp);
291 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
292 }
293
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000294 cmd_obj_sp = GetCommandSPExact ("process kill", false);
295 if (cmd_obj_sp)
Greg Claytone86fd742012-09-27 00:02:27 +0000296 {
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000297 AddAlias ("kill", cmd_obj_sp);
Greg Claytone86fd742012-09-27 00:02:27 +0000298 }
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000299
Caroline Ticeca90c472011-05-06 21:37:15 +0000300 cmd_obj_sp = GetCommandSPExact ("process launch", false);
301 if (cmd_obj_sp)
302 {
303 alias_arguments_vector_sp.reset (new OptionArgVector);
Jason Molenda85da3122012-07-06 02:46:23 +0000304#if defined (__arm__)
305 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
306#else
Greg Clayton0ca92a12012-05-18 00:04:38 +0000307 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
Jason Molenda85da3122012-07-06 02:46:23 +0000308#endif
Caroline Ticeca90c472011-05-06 21:37:15 +0000309 AddAlias ("r", cmd_obj_sp);
310 AddAlias ("run", cmd_obj_sp);
311 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
312 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
313 }
Greg Clayton843d62d2012-03-29 21:47:51 +0000314
315 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
316 if (cmd_obj_sp)
317 {
318 AddAlias ("add-dsym", cmd_obj_sp);
319 }
Sean Callananfc732752012-05-21 18:25:19 +0000320
321 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
322 if (cmd_obj_sp)
323 {
324 alias_arguments_vector_sp.reset (new OptionArgVector);
325 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
Jim Ingham06d282d2012-10-18 23:24:12 +0000326 AddAlias ("rbreak", cmd_obj_sp);
327 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
Sean Callananfc732752012-05-21 18:25:19 +0000328 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000329}
330
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000331const char *
332CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
333{
334 // This function has not yet been implemented.
335
336 // Look for any embedded script command
337 // If found,
338 // get interpreter object from the command dictionary,
339 // call execute_one_command on it,
340 // get the results as a string,
341 // substitute that string for current stuff.
342
343 return arg;
344}
345
346
347void
348CommandInterpreter::LoadCommandDictionary ()
349{
350 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
351
352 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
353 //
354 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
355 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
356 // the cross-referencing stuff) are created!!!
357 //
358 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
359
360
361 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
362 // are created. This is so that when another command is created that needs to go into a crossref object,
363 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
364 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
365
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000366 // Non-CommandObjectCrossref commands can now be created.
367
Caroline Ticedaccaa92010-09-20 20:44:43 +0000368 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000369
Greg Claytona7015092010-09-18 01:14:36 +0000370 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000371 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000372 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chenb89982d2011-04-21 00:39:18 +0000373 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000374 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
375 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Clayton7260f622011-04-18 08:33:37 +0000376// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000377 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000378 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytoneffe5c92011-05-03 22:09:39 +0000379 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000380 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
381 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonded470d2011-03-19 01:12:21 +0000382 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata21dfcd92012-09-28 23:57:51 +0000383 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000384 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000385 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000386 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000387 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000388 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Inghamebc09c32010-07-07 03:36:20 +0000389 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000390 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
391 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata223383e2011-08-16 23:24:13 +0000392 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen31c39da2010-12-23 20:21:44 +0000393 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chenf04ee932011-09-22 18:04:58 +0000394 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000395
Jim Inghamca36cd12012-10-05 19:16:31 +0000396 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
397 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
398 {"^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
Greg Clayton1b3815c2013-01-30 00:18:29 +0000399 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000400 {"^(-.*)$", "breakpoint set %1"},
401 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
402 {"^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"}};
403
404 size_t num_regexes = sizeof break_regexes/sizeof(char *[2]);
405
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000406 std::auto_ptr<CommandObjectRegexCommand>
Greg Claytona7015092010-09-18 01:14:36 +0000407 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000408 "_regexp-break",
Johnny Chenb417dcd2012-08-23 00:32:22 +0000409 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
410 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Jim Inghamca36cd12012-10-05 19:16:31 +0000411
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000412 if (break_regex_cmd_ap.get())
413 {
Jim Inghamca36cd12012-10-05 19:16:31 +0000414 bool success = true;
415 for (size_t i = 0; i < num_regexes; i++)
416 {
417 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
418 if (!success)
419 break;
420 }
421 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
422
423 if (success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000424 {
425 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
426 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
427 }
428 }
Jim Inghamffba2292011-03-22 02:29:32 +0000429
430 std::auto_ptr<CommandObjectRegexCommand>
Jim Inghamca36cd12012-10-05 19:16:31 +0000431 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
432 "_regexp-tbreak",
433 "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
434 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
435
436 if (tbreak_regex_cmd_ap.get())
437 {
438 bool success = true;
439 for (size_t i = 0; i < num_regexes; i++)
440 {
441 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
442 char buffer[1024];
443 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
444 assert (num_printed < 1024);
445 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
446 if (!success)
447 break;
448 }
449 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
450
451 if (success)
452 {
453 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
454 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
455 }
456 }
457
458 std::auto_ptr<CommandObjectRegexCommand>
Johnny Chen6d675242012-08-24 18:15:45 +0000459 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
460 "_regexp-attach",
461 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.",
462 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]", 2));
463 if (attach_regex_cmd_ap.get())
464 {
Greg Clayton3cb4c7d2012-12-15 01:19:07 +0000465 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
466 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
467 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
468 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
Johnny Chen6d675242012-08-24 18:15:45 +0000469 {
470 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
471 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
472 }
473 }
474
475 std::auto_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000476 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000477 "_regexp-down",
478 "Go down \"n\" frames in the stack (1 frame by default).",
479 "_regexp-down [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000480 if (down_regex_cmd_ap.get())
481 {
482 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
483 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
484 {
485 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
486 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
487 }
488 }
489
490 std::auto_ptr<CommandObjectRegexCommand>
491 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000492 "_regexp-up",
493 "Go up \"n\" frames in the stack (1 frame by default).",
494 "_regexp-up [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000495 if (up_regex_cmd_ap.get())
496 {
497 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
498 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
499 {
500 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
501 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
502 }
503 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000504
505 std::auto_ptr<CommandObjectRegexCommand>
506 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda0c8e0062011-10-25 02:11:20 +0000507 "_regexp-display",
Jason Molendabc7748b2011-10-22 01:30:52 +0000508 "Add an expression evaluation stop-hook.",
Jason Molenda0c8e0062011-10-25 02:11:20 +0000509 "_regexp-display expression", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000510 if (display_regex_cmd_ap.get())
511 {
512 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
513 {
514 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
515 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
516 }
517 }
518
519 std::auto_ptr<CommandObjectRegexCommand>
520 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda0c8e0062011-10-25 02:11:20 +0000521 "_regexp-undisplay",
Jason Molendabc7748b2011-10-22 01:30:52 +0000522 "Remove an expression evaluation stop-hook.",
Jason Molenda0c8e0062011-10-25 02:11:20 +0000523 "_regexp-undisplay stop-hook-number", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000524 if (undisplay_regex_cmd_ap.get())
525 {
526 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
527 {
528 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
529 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
530 }
531 }
532
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000533 std::auto_ptr<CommandObjectRegexCommand>
534 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
535 "gdb-remote",
Jason Molendaa7dcb332012-10-23 03:05:16 +0000536 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
537 "gdb-remote [<hostname>:]<portnum>", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000538 if (connect_gdb_remote_cmd_ap.get())
539 {
540 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
541 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
542 {
543 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
544 m_command_dict[command_sp->GetCommandName ()] = command_sp;
545 }
546 }
547
548 std::auto_ptr<CommandObjectRegexCommand>
549 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
550 "kdp-remote",
Jason Molendaa7dcb332012-10-23 03:05:16 +0000551 "Connect to a remote KDP server. udp port 41139 is the default port number.",
552 "kdp-remote <hostname>[:<portnum>]", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000553 if (connect_kdp_remote_cmd_ap.get())
554 {
555 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molendac36b1842012-09-27 02:47:55 +0000556 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000557 {
558 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
559 m_command_dict[command_sp->GetCommandName ()] = command_sp;
560 }
561 }
562
Jason Molenda4cddfed2012-10-05 05:29:32 +0000563 std::auto_ptr<CommandObjectRegexCommand>
564 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jim Ingham71bf2992012-10-10 16:51:31 +0000565 "_regexp-bt",
Jason Molenda4cddfed2012-10-05 05:29:32 +0000566 "Show a backtrace. An optional argument is accepted; if that argument is a number, it specifies the number of frames to display. If that argument is 'all', full backtraces of all threads are displayed.",
567 "bt [<digit>|all]", 2));
568 if (bt_regex_cmd_ap.get())
569 {
570 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
571 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
572 // so now "bt 3" is the preferred form, in line with gdb.
573 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
574 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
575 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
576 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
577 {
578 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
579 m_command_dict[command_sp->GetCommandName ()] = command_sp;
580 }
581 }
582
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000583}
584
585int
586CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
587 StringList &matches)
588{
589 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
590
591 if (include_aliases)
592 {
593 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
594 }
595
596 return matches.GetSize();
597}
598
599CommandObjectSP
600CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
601{
602 CommandObject::CommandMap::iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +0000603 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000604
605 std::string cmd(cmd_cstr);
606
607 if (HasCommands())
608 {
609 pos = m_command_dict.find(cmd);
610 if (pos != m_command_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000611 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000612 }
613
614 if (include_aliases && HasAliases())
615 {
616 pos = m_alias_dict.find(cmd);
617 if (pos != m_alias_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000618 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000619 }
620
621 if (HasUserCommands())
622 {
623 pos = m_user_dict.find(cmd);
624 if (pos != m_user_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000625 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000626 }
627
Greg Claytonc7bece562013-01-25 18:06:21 +0000628 if (!exact && !command_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000629 {
Jim Ingham279a6c22010-07-06 22:46:59 +0000630 // We will only get into here if we didn't find any exact matches.
631
632 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
633
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000634 StringList local_matches;
635 if (matches == NULL)
636 matches = &local_matches;
637
Jim Ingham279a6c22010-07-06 22:46:59 +0000638 unsigned int num_cmd_matches = 0;
639 unsigned int num_alias_matches = 0;
640 unsigned int num_user_matches = 0;
641
642 // Look through the command dictionaries one by one, and if we get only one match from any of
643 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
644
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000645 if (HasCommands())
646 {
647 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
648 }
649
650 if (num_cmd_matches == 1)
651 {
652 cmd.assign(matches->GetStringAtIndex(0));
653 pos = m_command_dict.find(cmd);
654 if (pos != m_command_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000655 real_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000656 }
657
Jim Ingham490ac552010-06-24 20:28:42 +0000658 if (include_aliases && HasAliases())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000659 {
660 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
661
662 }
663
Jim Ingham279a6c22010-07-06 22:46:59 +0000664 if (num_alias_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000665 {
666 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
667 pos = m_alias_dict.find(cmd);
668 if (pos != m_alias_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000669 alias_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000670 }
671
Jim Ingham490ac552010-06-24 20:28:42 +0000672 if (HasUserCommands())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000673 {
674 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
675 }
676
Jim Ingham279a6c22010-07-06 22:46:59 +0000677 if (num_user_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000678 {
679 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
680
681 pos = m_user_dict.find (cmd);
682 if (pos != m_user_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000683 user_match_sp = pos->second;
684 }
685
686 // If we got exactly one match, return that, otherwise return the match list.
687
688 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
689 {
690 if (num_cmd_matches)
691 return real_match_sp;
692 else if (num_alias_matches)
693 return alias_match_sp;
694 else
695 return user_match_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000696 }
697 }
Greg Claytonc7bece562013-01-25 18:06:21 +0000698 else if (matches && command_sp)
Jim Ingham279a6c22010-07-06 22:46:59 +0000699 {
700 matches->AppendString (cmd_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000701 }
702
703
Greg Claytonc7bece562013-01-25 18:06:21 +0000704 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000705}
706
Greg Claytonde164aa2011-04-20 16:37:46 +0000707bool
708CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
709{
710 if (name && name[0])
711 {
712 std::string name_sstr(name);
Enrico Granatae00af802012-10-01 17:19:37 +0000713 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
714 if (found && !can_replace)
715 return false;
716 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata21dfcd92012-09-28 23:57:51 +0000717 return false;
Greg Claytonde164aa2011-04-20 16:37:46 +0000718 m_command_dict[name_sstr] = cmd_sp;
719 return true;
720 }
721 return false;
722}
723
Enrico Granata223383e2011-08-16 23:24:13 +0000724bool
Enrico Granata0a305db2011-11-07 22:57:04 +0000725CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata223383e2011-08-16 23:24:13 +0000726 const lldb::CommandObjectSP &cmd_sp,
727 bool can_replace)
728{
Enrico Granata0a305db2011-11-07 22:57:04 +0000729 if (!name.empty())
Enrico Granata223383e2011-08-16 23:24:13 +0000730 {
Enrico Granata0a305db2011-11-07 22:57:04 +0000731
732 const char* name_cstr = name.c_str();
733
734 // do not allow replacement of internal commands
735 if (CommandExists(name_cstr))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000736 {
737 if (can_replace == false)
738 return false;
739 if (m_command_dict[name]->IsRemovable() == false)
740 return false;
741 }
Enrico Granata0a305db2011-11-07 22:57:04 +0000742
Enrico Granata21dfcd92012-09-28 23:57:51 +0000743 if (UserCommandExists(name_cstr))
744 {
745 if (can_replace == false)
746 return false;
747 if (m_user_dict[name]->IsRemovable() == false)
748 return false;
749 }
750
Enrico Granata0a305db2011-11-07 22:57:04 +0000751 m_user_dict[name] = cmd_sp;
Enrico Granata223383e2011-08-16 23:24:13 +0000752 return true;
753 }
754 return false;
755}
Greg Claytonde164aa2011-04-20 16:37:46 +0000756
Jim Ingham279a6c22010-07-06 22:46:59 +0000757CommandObjectSP
758CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000759{
Caroline Tice472362e2010-12-14 18:51:39 +0000760 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
761 CommandObjectSP ret_val; // Possibly empty return value.
762
763 if (cmd_cstr == NULL)
764 return ret_val;
765
766 if (cmd_words.GetArgumentCount() == 1)
767 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
768 else
769 {
770 // We have a multi-word command (seemingly), so we need to do more work.
771 // First, get the cmd_obj_sp for the first word in the command.
772 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
773 if (cmd_obj_sp.get() != NULL)
774 {
775 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
776 // command name), and find the appropriate sub-command SP for each command word....
777 size_t end = cmd_words.GetArgumentCount();
778 for (size_t j= 1; j < end; ++j)
779 {
780 if (cmd_obj_sp->IsMultiwordObject())
781 {
Greg Clayton998255b2012-10-13 02:07:45 +0000782 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Caroline Tice472362e2010-12-14 18:51:39 +0000783 if (cmd_obj_sp.get() == NULL)
784 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
785 return ret_val;
786 }
787 else
788 // We have more words in the command name, but we don't have a multiword object. Fail and return
789 // empty 'ret_val'.
790 return ret_val;
791 }
792 // We successfully looped through all the command words and got valid command objects for them. Assign the
793 // last object retrieved to 'ret_val'.
794 ret_val = cmd_obj_sp;
795 }
796 }
797 return ret_val;
Jim Ingham279a6c22010-07-06 22:46:59 +0000798}
799
800CommandObject *
801CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
802{
803 return GetCommandSPExact (cmd_cstr, include_aliases).get();
804}
805
806CommandObject *
807CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
808{
809 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
810
811 // If we didn't find an exact match to the command string in the commands, look in
812 // the aliases.
813
814 if (command_obj == NULL)
815 {
816 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
817 }
818
819 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
820 // in both the commands and the aliases.
821
822 if (command_obj == NULL)
823 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
824
825 return command_obj;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000826}
827
828bool
829CommandInterpreter::CommandExists (const char *cmd)
830{
831 return m_command_dict.find(cmd) != m_command_dict.end();
832}
833
834bool
Caroline Ticeca90c472011-05-06 21:37:15 +0000835CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
836 const char *options_args,
837 OptionArgVectorSP &option_arg_vector_sp)
838{
839 bool success = true;
840 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
841
842 if (!options_args || (strlen (options_args) < 1))
843 return true;
844
845 std::string options_string (options_args);
846 Args args (options_args);
847 CommandReturnObject result;
848 // Check to see if the command being aliased can take any command options.
849 Options *options = cmd_obj_sp->GetOptions ();
850 if (options)
851 {
852 // See if any options were specified as part of the alias; if so, handle them appropriately.
853 options->NotifyOptionParsingStarting ();
854 args.Unshift ("dummy_arg");
855 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
856 args.Shift ();
857 if (result.Succeeded())
858 options->VerifyPartialOptions (result);
859 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
860 {
861 result.AppendError ("Unable to create requested alias.\n");
862 return false;
863 }
864 }
865
Greg Clayton5521f992011-10-28 21:38:01 +0000866 if (!options_string.empty())
Caroline Ticeca90c472011-05-06 21:37:15 +0000867 {
868 if (cmd_obj_sp->WantsRawCommandString ())
869 option_arg_vector->push_back (OptionArgPair ("<argument>",
870 OptionArgValue (-1,
871 options_string)));
872 else
873 {
Greg Claytonc7bece562013-01-25 18:06:21 +0000874 const size_t argc = args.GetArgumentCount();
Caroline Ticeca90c472011-05-06 21:37:15 +0000875 for (size_t i = 0; i < argc; ++i)
876 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
877 option_arg_vector->push_back
878 (OptionArgPair ("<argument>",
879 OptionArgValue (-1,
880 std::string (args.GetArgumentAtIndex (i)))));
881 }
882 }
883
884 return success;
885}
886
887bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000888CommandInterpreter::AliasExists (const char *cmd)
889{
890 return m_alias_dict.find(cmd) != m_alias_dict.end();
891}
892
893bool
894CommandInterpreter::UserCommandExists (const char *cmd)
895{
896 return m_user_dict.find(cmd) != m_user_dict.end();
897}
898
899void
900CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
901{
Jim Ingham279a6c22010-07-06 22:46:59 +0000902 command_obj_sp->SetIsAlias (true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000903 m_alias_dict[alias_name] = command_obj_sp;
904}
905
906bool
907CommandInterpreter::RemoveAlias (const char *alias_name)
908{
909 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
910 if (pos != m_alias_dict.end())
911 {
912 m_alias_dict.erase(pos);
913 return true;
914 }
915 return false;
916}
917bool
918CommandInterpreter::RemoveUser (const char *alias_name)
919{
920 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
921 if (pos != m_user_dict.end())
922 {
923 m_user_dict.erase(pos);
924 return true;
925 }
926 return false;
927}
928
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000929void
930CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
931{
932 help_string.Printf ("'%s", command_name);
933 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
934
Sean Callanan9a028512012-08-09 00:50:26 +0000935 if (option_arg_vector_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000936 {
937 OptionArgVector *options = option_arg_vector_sp.get();
938 for (int i = 0; i < options->size(); ++i)
939 {
940 OptionArgPair cur_option = (*options)[i];
941 std::string opt = cur_option.first;
Caroline Ticed9d63362010-12-07 19:58:26 +0000942 OptionArgValue value_pair = cur_option.second;
943 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000944 if (opt.compare("<argument>") == 0)
945 {
946 help_string.Printf (" %s", value.c_str());
947 }
948 else
949 {
950 help_string.Printf (" %s", opt.c_str());
951 if ((value.compare ("<no-argument>") != 0)
952 && (value.compare ("<need-argument") != 0))
953 {
954 help_string.Printf (" %s", value.c_str());
955 }
956 }
957 }
958 }
959
960 help_string.Printf ("'");
961}
962
Greg Clayton12fc3e02010-08-26 22:05:43 +0000963size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000964CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
965{
966 CommandObject::CommandMap::const_iterator pos;
Greg Clayton12fc3e02010-08-26 22:05:43 +0000967 CommandObject::CommandMap::const_iterator end = dict.end();
968 size_t max_len = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000969
Greg Clayton12fc3e02010-08-26 22:05:43 +0000970 for (pos = dict.begin(); pos != end; ++pos)
971 {
972 size_t len = pos->first.size();
973 if (max_len < len)
974 max_len = len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000975 }
Greg Clayton12fc3e02010-08-26 22:05:43 +0000976 return max_len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000977}
978
979void
Enrico Granata223383e2011-08-16 23:24:13 +0000980CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata08633ee2011-09-09 17:49:36 +0000981 uint32_t cmd_types)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000982{
983 CommandObject::CommandMap::const_iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +0000984 size_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata223383e2011-08-16 23:24:13 +0000985
986 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000987 {
Enrico Granata223383e2011-08-16 23:24:13 +0000988
989 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
990 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000991
Enrico Granata223383e2011-08-16 23:24:13 +0000992 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
993 {
994 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
995 max_len);
996 }
997 result.AppendMessage("");
998
999 }
1000
Greg Clayton5521f992011-10-28 21:38:01 +00001001 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001002 {
Jim Ingham49e80a12010-10-22 18:47:16 +00001003 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chenb89982d2011-04-21 00:39:18 +00001004 "(see 'help command alias' for more info):");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001005 result.AppendMessage("");
Greg Clayton12fc3e02010-08-26 22:05:43 +00001006 max_len = FindLongestCommandWord (m_alias_dict);
1007
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001008 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1009 {
1010 StreamString sstr;
1011 StreamString translation_and_help;
1012 std::string entry_name = pos->first;
1013 std::string second_entry = pos->second.get()->GetCommandName();
1014 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1015
1016 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1017 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1018 translation_and_help.GetData(), max_len);
1019 }
1020 result.AppendMessage("");
1021 }
1022
Greg Clayton5521f992011-10-28 21:38:01 +00001023 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001024 {
1025 result.AppendMessage ("The following is a list of your current user-defined commands:");
1026 result.AppendMessage("");
Enrico Granata223383e2011-08-16 23:24:13 +00001027 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001028 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1029 {
Enrico Granata223383e2011-08-16 23:24:13 +00001030 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1031 max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001032 }
1033 result.AppendMessage("");
1034 }
1035
1036 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1037}
1038
Caroline Tice844d2302010-12-09 22:52:49 +00001039CommandObject *
1040CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001041{
Caroline Tice844d2302010-12-09 22:52:49 +00001042 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1043 // eventually be invoked by the given command line.
1044
1045 CommandObject *cmd_obj = NULL;
1046 std::string white_space (" \t\v");
1047 size_t start = command_string.find_first_not_of (white_space);
1048 size_t end = 0;
1049 bool done = false;
1050 while (!done)
1051 {
1052 if (start != std::string::npos)
1053 {
1054 // Get the next word from command_string.
1055 end = command_string.find_first_of (white_space, start);
1056 if (end == std::string::npos)
1057 end = command_string.size();
1058 std::string cmd_word = command_string.substr (start, end - start);
1059
1060 if (cmd_obj == NULL)
1061 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1062 // command or alias.
1063 cmd_obj = GetCommandObject (cmd_word.c_str());
1064 else if (cmd_obj->IsMultiwordObject ())
1065 {
1066 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
Greg Clayton998255b2012-10-13 02:07:45 +00001067 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001068 if (sub_cmd_obj)
1069 cmd_obj = sub_cmd_obj;
1070 else // cmd_word was not a valid sub-command word, so we are donee
1071 done = true;
1072 }
1073 else
1074 // We have a cmd_obj and it is not a multi-word object, so we are done.
1075 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001076
Caroline Tice844d2302010-12-09 22:52:49 +00001077 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1078 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1079 // next word.
1080
1081 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1082 done = true;
1083 else
1084 start = command_string.find_first_not_of (white_space, end);
1085 }
1086 else
1087 // Unable to find any more words.
1088 done = true;
1089 }
1090
1091 if (end == command_string.size())
1092 command_string.clear();
1093 else
1094 command_string = command_string.substr(end);
1095
1096 return cmd_obj;
1097}
1098
Greg Clayton51964162011-10-25 00:36:27 +00001099static const char *k_white_space = " \t\v";
Greg Clayton5521f992011-10-28 21:38:01 +00001100static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton51964162011-10-25 00:36:27 +00001101static void
1102StripLeadingSpaces (std::string &s)
Caroline Tice844d2302010-12-09 22:52:49 +00001103{
Greg Clayton51964162011-10-25 00:36:27 +00001104 if (!s.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001105 {
Greg Clayton51964162011-10-25 00:36:27 +00001106 size_t pos = s.find_first_not_of (k_white_space);
1107 if (pos == std::string::npos)
1108 s.clear();
1109 else if (pos == 0)
1110 return;
1111 s.erase (0, pos);
1112 }
1113}
1114
Greg Clayton93c62e62011-11-09 23:25:03 +00001115static size_t
1116FindArgumentTerminator (const std::string &s)
1117{
Greg Clayton93c62e62011-11-09 23:25:03 +00001118 const size_t s_len = s.size();
1119 size_t offset = 0;
1120 while (offset < s_len)
1121 {
1122 size_t pos = s.find ("--", offset);
1123 if (pos == std::string::npos)
1124 break;
1125 if (pos > 0)
1126 {
1127 if (isspace(s[pos-1]))
1128 {
1129 // Check if the string ends "\s--" (where \s is a space character)
1130 // or if we have "\s--\s".
1131 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1132 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001133 return pos;
1134 }
1135 }
1136 }
1137 offset = pos + 2;
1138 }
Greg Clayton93c62e62011-11-09 23:25:03 +00001139 return std::string::npos;
1140}
1141
Greg Clayton51964162011-10-25 00:36:27 +00001142static bool
Greg Clayton5521f992011-10-28 21:38:01 +00001143ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton51964162011-10-25 00:36:27 +00001144{
Greg Clayton5521f992011-10-28 21:38:01 +00001145 command.clear();
1146 suffix.clear();
Greg Clayton51964162011-10-25 00:36:27 +00001147 StripLeadingSpaces (command_string);
1148
1149 bool result = false;
1150 quote_char = '\0';
1151
1152 if (!command_string.empty())
1153 {
1154 const char first_char = command_string[0];
1155 if (first_char == '\'' || first_char == '"')
Caroline Tice844d2302010-12-09 22:52:49 +00001156 {
Greg Clayton51964162011-10-25 00:36:27 +00001157 quote_char = first_char;
1158 const size_t end_quote_pos = command_string.find (quote_char, 1);
1159 if (end_quote_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001160 {
Greg Clayton5521f992011-10-28 21:38:01 +00001161 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001162 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001163 }
1164 else
1165 {
Greg Clayton5521f992011-10-28 21:38:01 +00001166 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton51964162011-10-25 00:36:27 +00001167 if (end_quote_pos + 1 < command_string.size())
1168 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1169 else
1170 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001171 }
Caroline Tice844d2302010-12-09 22:52:49 +00001172 }
1173 else
1174 {
Greg Clayton51964162011-10-25 00:36:27 +00001175 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1176 if (first_space_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001177 {
Greg Clayton5521f992011-10-28 21:38:01 +00001178 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001179 command_string.erase();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001180 }
1181 else
1182 {
Greg Clayton5521f992011-10-28 21:38:01 +00001183 command.assign (command_string, 0, first_space_pos);
1184 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice2b5e8502011-05-11 16:07:06 +00001185 }
Caroline Tice844d2302010-12-09 22:52:49 +00001186 }
Greg Clayton51964162011-10-25 00:36:27 +00001187 result = true;
Caroline Tice844d2302010-12-09 22:52:49 +00001188 }
Greg Clayton5521f992011-10-28 21:38:01 +00001189
1190
1191 if (!command.empty())
1192 {
1193 // actual commands can't start with '-' or '_'
1194 if (command[0] != '-' && command[0] != '_')
1195 {
1196 size_t pos = command.find_first_not_of(k_valid_command_chars);
1197 if (pos > 0 && pos != std::string::npos)
1198 {
1199 suffix.assign (command.begin() + pos, command.end());
1200 command.erase (pos);
1201 }
1202 }
1203 }
Greg Clayton51964162011-10-25 00:36:27 +00001204
1205 return result;
Caroline Tice844d2302010-12-09 22:52:49 +00001206}
1207
Greg Clayton5521f992011-10-28 21:38:01 +00001208CommandObject *
1209CommandInterpreter::BuildAliasResult (const char *alias_name,
1210 std::string &raw_input_string,
1211 std::string &alias_result,
1212 CommandReturnObject &result)
Caroline Tice844d2302010-12-09 22:52:49 +00001213{
Greg Clayton5521f992011-10-28 21:38:01 +00001214 CommandObject *alias_cmd_obj = NULL;
Caroline Tice844d2302010-12-09 22:52:49 +00001215 Args cmd_args (raw_input_string.c_str());
1216 alias_cmd_obj = GetCommandObject (alias_name);
1217 StreamString result_str;
1218
1219 if (alias_cmd_obj)
1220 {
1221 std::string alias_name_str = alias_name;
1222 if ((cmd_args.GetArgumentCount() == 0)
1223 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1224 cmd_args.Unshift (alias_name);
1225
1226 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1227 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1228
1229 if (option_arg_vector_sp.get())
1230 {
1231 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1232
1233 for (int i = 0; i < option_arg_vector->size(); ++i)
1234 {
1235 OptionArgPair option_pair = (*option_arg_vector)[i];
1236 OptionArgValue value_pair = option_pair.second;
1237 int value_type = value_pair.first;
1238 std::string option = option_pair.first;
1239 std::string value = value_pair.second;
1240 if (option.compare ("<argument>") == 0)
1241 result_str.Printf (" %s", value.c_str());
1242 else
1243 {
1244 result_str.Printf (" %s", option.c_str());
1245 if (value_type != optional_argument)
1246 result_str.Printf (" ");
1247 if (value.compare ("<no_argument>") != 0)
1248 {
1249 int index = GetOptionArgumentPosition (value.c_str());
1250 if (index == 0)
1251 result_str.Printf ("%s", value.c_str());
1252 else if (index >= cmd_args.GetArgumentCount())
1253 {
1254
1255 result.AppendErrorWithFormat
1256 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1257 index);
1258 result.SetStatus (eReturnStatusFailed);
Greg Clayton5521f992011-10-28 21:38:01 +00001259 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001260 }
1261 else
1262 {
1263 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1264 if (strpos != std::string::npos)
1265 raw_input_string = raw_input_string.erase (strpos,
1266 strlen (cmd_args.GetArgumentAtIndex (index)));
1267 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1268 }
1269 }
1270 }
1271 }
1272 }
1273
1274 alias_result = result_str.GetData();
1275 }
Greg Clayton5521f992011-10-28 21:38:01 +00001276 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001277}
1278
Greg Clayton5a314712011-10-14 07:41:33 +00001279Error
1280CommandInterpreter::PreprocessCommand (std::string &command)
1281{
1282 // The command preprocessor needs to do things to the command
1283 // line before any parsing of arguments or anything else is done.
1284 // The only current stuff that gets proprocessed is anyting enclosed
1285 // in backtick ('`') characters is evaluated as an expression and
1286 // the result of the expression must be a scalar that can be substituted
1287 // into the command. An example would be:
1288 // (lldb) memory read `$rsp + 20`
1289 Error error; // Error for any expressions that might not evaluate
1290 size_t start_backtick;
1291 size_t pos = 0;
1292 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1293 {
1294 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1295 {
1296 // The backtick was preceeded by a '\' character, remove the slash
1297 // and don't treat the backtick as the start of an expression
1298 command.erase(start_backtick-1, 1);
1299 // No need to add one to start_backtick since we just deleted a char
1300 pos = start_backtick;
1301 }
1302 else
1303 {
1304 const size_t expr_content_start = start_backtick + 1;
1305 const size_t end_backtick = command.find ('`', expr_content_start);
1306 if (end_backtick == std::string::npos)
1307 return error;
1308 else if (end_backtick == expr_content_start)
1309 {
1310 // Empty expression (two backticks in a row)
1311 command.erase (start_backtick, 2);
1312 }
1313 else
1314 {
1315 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1316
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00001317 ExecutionContext exe_ctx(GetExecutionContext());
1318 Target *target = exe_ctx.GetTargetPtr();
Johnny Chen51ea0ad2011-10-29 00:21:50 +00001319 // Get a dummy target to allow for calculator mode while processing backticks.
1320 // This also helps break the infinite loop caused when target is null.
1321 if (!target)
1322 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Clayton5a314712011-10-14 07:41:33 +00001323 if (target)
1324 {
Greg Clayton5a314712011-10-14 07:41:33 +00001325 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001326
Jim Ingham35e1bda2012-10-16 21:41:58 +00001327 EvaluateExpressionOptions options;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001328 options.SetCoerceToId(false)
1329 .SetUnwindOnError(true)
Jim Ingham184e9812013-01-15 02:47:48 +00001330 .SetIgnoreBreakpoints(true)
Enrico Granatad4439aa2012-09-05 20:41:26 +00001331 .SetKeepInMemory(false)
Jim Ingham35e1bda2012-10-16 21:41:58 +00001332 .SetRunOthers(true)
1333 .SetTimeoutUsec(0);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001334
Greg Clayton5a314712011-10-14 07:41:33 +00001335 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad4439aa2012-09-05 20:41:26 +00001336 exe_ctx.GetFramePtr(),
Enrico Granata3372f582012-07-16 23:10:35 +00001337 expr_result_valobj_sp,
Enrico Granatad4439aa2012-09-05 20:41:26 +00001338 options);
1339
Greg Clayton5a314712011-10-14 07:41:33 +00001340 if (expr_result == eExecutionCompleted)
1341 {
1342 Scalar scalar;
1343 if (expr_result_valobj_sp->ResolveValue (scalar))
1344 {
1345 command.erase (start_backtick, end_backtick - start_backtick + 1);
1346 StreamString value_strm;
1347 const bool show_type = false;
1348 scalar.GetValue (&value_strm, show_type);
1349 size_t value_string_size = value_strm.GetSize();
1350 if (value_string_size)
1351 {
1352 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1353 pos = start_backtick + value_string_size;
1354 continue;
1355 }
1356 else
1357 {
1358 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1359 }
1360 }
1361 else
1362 {
1363 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1364 }
1365 }
1366 else
1367 {
1368 if (expr_result_valobj_sp)
1369 error = expr_result_valobj_sp->GetError();
1370 if (error.Success())
1371 {
1372
1373 switch (expr_result)
1374 {
1375 case eExecutionSetupError:
1376 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1377 break;
1378 case eExecutionCompleted:
1379 break;
1380 case eExecutionDiscarded:
1381 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1382 break;
1383 case eExecutionInterrupted:
1384 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1385 break;
Jim Ingham184e9812013-01-15 02:47:48 +00001386 case eExecutionHitBreakpoint:
1387 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1388 break;
Greg Clayton5a314712011-10-14 07:41:33 +00001389 case eExecutionTimedOut:
1390 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1391 break;
1392 }
1393 }
1394 }
1395 }
1396 }
1397 if (error.Fail())
1398 break;
1399 }
1400 }
1401 return error;
1402}
1403
1404
Caroline Tice844d2302010-12-09 22:52:49 +00001405bool
1406CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata5f5ab602012-05-31 01:09:06 +00001407 LazyBool lazy_add_to_history,
Caroline Tice844d2302010-12-09 22:52:49 +00001408 CommandReturnObject &result,
Jim Inghame16c50a2011-02-18 00:54:25 +00001409 ExecutionContext *override_context,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001410 bool repeat_on_empty_command,
1411 bool no_context_switching)
Jim Inghame16c50a2011-02-18 00:54:25 +00001412
Caroline Tice844d2302010-12-09 22:52:49 +00001413{
Jim Inghame16c50a2011-02-18 00:54:25 +00001414
Caroline Tice844d2302010-12-09 22:52:49 +00001415 bool done = false;
1416 CommandObject *cmd_obj = NULL;
Caroline Tice844d2302010-12-09 22:52:49 +00001417 bool wants_raw_input = false;
1418 std::string command_string (command_line);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001419 std::string original_command_string (command_line);
Caroline Tice844d2302010-12-09 22:52:49 +00001420
1421 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001422 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1423
1424 // Make a scoped cleanup object that will clear the crash description string
1425 // on exit of this function.
Enrico Granataf9fa6ee2011-07-12 00:18:11 +00001426 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001427
Caroline Tice844d2302010-12-09 22:52:49 +00001428 if (log)
1429 log->Printf ("Processing command: %s", command_line);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001430
Jim Ingham30244832010-11-04 23:08:45 +00001431 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1432
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001433 if (!no_context_switching)
1434 UpdateExecutionContext (override_context);
Enrico Granata5f5ab602012-05-31 01:09:06 +00001435
1436 // <rdar://problem/11328896>
1437 bool add_to_history;
1438 if (lazy_add_to_history == eLazyBoolCalculate)
1439 add_to_history = (m_command_source_depth == 0);
1440 else
1441 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1442
Jim Inghame16c50a2011-02-18 00:54:25 +00001443 bool empty_command = false;
1444 bool comment_command = false;
1445 if (command_string.empty())
1446 empty_command = true;
1447 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001448 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001449 const char *k_space_characters = "\t\n\v\f\r ";
1450
1451 size_t non_space = command_string.find_first_not_of (k_space_characters);
1452 // Check for empty line or comment line (lines whose first
1453 // non-space character is the comment character for this interpreter)
1454 if (non_space == std::string::npos)
1455 empty_command = true;
1456 else if (command_string[non_space] == m_comment_char)
1457 comment_command = true;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001458 else if (command_string[non_space] == m_repeat_char)
1459 {
1460 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1461 if (history_string == NULL)
1462 {
1463 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1464 result.SetStatus(eReturnStatusFailed);
1465 return false;
1466 }
1467 add_to_history = false;
1468 command_string = history_string;
1469 original_command_string = history_string;
1470 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001471 }
1472
1473 if (empty_command)
1474 {
1475 if (repeat_on_empty_command)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001476 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001477 if (m_command_history.empty())
1478 {
1479 result.AppendError ("empty command");
1480 result.SetStatus(eReturnStatusFailed);
1481 return false;
1482 }
1483 else
1484 {
1485 command_line = m_repeat_command.c_str();
1486 command_string = command_line;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001487 original_command_string = command_line;
Jim Inghame16c50a2011-02-18 00:54:25 +00001488 if (m_repeat_command.empty())
1489 {
1490 result.AppendErrorWithFormat("No auto repeat.\n");
1491 result.SetStatus (eReturnStatusFailed);
1492 return false;
1493 }
1494 }
1495 add_to_history = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001496 }
1497 else
1498 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001499 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1500 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001501 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001502 }
1503 else if (comment_command)
1504 {
1505 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1506 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001507 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001508
Greg Clayton5a314712011-10-14 07:41:33 +00001509
1510 Error error (PreprocessCommand (command_string));
1511
1512 if (error.Fail())
1513 {
1514 result.AppendError (error.AsCString());
1515 result.SetStatus(eReturnStatusFailed);
1516 return false;
1517 }
Caroline Tice844d2302010-12-09 22:52:49 +00001518 // Phase 1.
1519
1520 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1521 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1522 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1523 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1524 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command
Greg Clayton710dd5a2011-01-08 20:28:42 +00001525 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Tice844d2302010-12-09 22:52:49 +00001526 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Ticed9d63362010-12-07 19:58:26 +00001527
Caroline Tice844d2302010-12-09 22:52:49 +00001528 StreamString revised_command_line;
Caroline Tice01274c02010-12-11 08:16:56 +00001529 size_t actual_cmd_name_len = 0;
Greg Clayton5521f992011-10-28 21:38:01 +00001530 std::string next_word;
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001531 StringList matches;
Caroline Tice844d2302010-12-09 22:52:49 +00001532 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001533 {
Caroline Tice2b5e8502011-05-11 16:07:06 +00001534 char quote_char = '\0';
Greg Clayton5521f992011-10-28 21:38:01 +00001535 std::string suffix;
1536 ExtractCommand (command_string, next_word, suffix, quote_char);
1537 if (cmd_obj == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001538 {
Greg Clayton5521f992011-10-28 21:38:01 +00001539 if (AliasExists (next_word.c_str()))
Caroline Tice472362e2010-12-14 18:51:39 +00001540 {
Greg Clayton5521f992011-10-28 21:38:01 +00001541 std::string alias_result;
1542 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1543 revised_command_line.Printf ("%s", alias_result.c_str());
1544 if (cmd_obj)
1545 {
1546 wants_raw_input = cmd_obj->WantsRawCommandString ();
1547 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1548 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001549 }
1550 else
1551 {
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001552 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton5521f992011-10-28 21:38:01 +00001553 if (cmd_obj)
1554 {
1555 actual_cmd_name_len += next_word.length();
1556 revised_command_line.Printf ("%s", next_word.c_str());
1557 wants_raw_input = cmd_obj->WantsRawCommandString ();
1558 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001559 else
Greg Clayton5521f992011-10-28 21:38:01 +00001560 {
1561 revised_command_line.Printf ("%s", next_word.c_str());
1562 }
Caroline Tice844d2302010-12-09 22:52:49 +00001563 }
1564 }
1565 else
1566 {
Greg Clayton5521f992011-10-28 21:38:01 +00001567 if (cmd_obj->IsMultiwordObject ())
1568 {
Greg Clayton998255b2012-10-13 02:07:45 +00001569 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
Greg Clayton5521f992011-10-28 21:38:01 +00001570 if (sub_cmd_obj)
1571 {
1572 actual_cmd_name_len += next_word.length() + 1;
1573 revised_command_line.Printf (" %s", next_word.c_str());
1574 cmd_obj = sub_cmd_obj;
1575 wants_raw_input = cmd_obj->WantsRawCommandString ();
1576 }
1577 else
1578 {
1579 if (quote_char)
1580 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1581 else
1582 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1583 done = true;
1584 }
1585 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001586 else
Greg Clayton5521f992011-10-28 21:38:01 +00001587 {
1588 if (quote_char)
1589 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1590 else
1591 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1592 done = true;
1593 }
Caroline Tice844d2302010-12-09 22:52:49 +00001594 }
1595
1596 if (cmd_obj == NULL)
1597 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001598 const size_t num_matches = matches.GetSize();
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001599 if (matches.GetSize() > 1) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001600 StreamString error_msg;
1601 error_msg.Printf ("Ambiguous command '%s'. Possible matches:\n", next_word.c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001602
1603 for (uint32_t i = 0; i < num_matches; ++i) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001604 error_msg.Printf ("\t%s\n", matches.GetStringAtIndex(i));
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001605 }
Greg Claytonc7bece562013-01-25 18:06:21 +00001606 result.AppendRawError (error_msg.GetString().c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001607 } else {
1608 // We didn't have only one match, otherwise we wouldn't get here.
1609 assert(num_matches == 0);
1610 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1611 }
Caroline Tice844d2302010-12-09 22:52:49 +00001612 result.SetStatus (eReturnStatusFailed);
1613 return false;
1614 }
1615
Greg Clayton5521f992011-10-28 21:38:01 +00001616 if (cmd_obj->IsMultiwordObject ())
1617 {
1618 if (!suffix.empty())
1619 {
1620
1621 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1622 next_word.c_str(),
1623 suffix.c_str());
1624 result.SetStatus (eReturnStatusFailed);
1625 return false;
1626 }
1627 }
1628 else
1629 {
1630 // If we found a normal command, we are done
1631 done = true;
1632 if (!suffix.empty())
1633 {
1634 switch (suffix[0])
1635 {
1636 case '/':
1637 // GDB format suffixes
Greg Clayton52ec56c2011-10-29 00:57:28 +00001638 {
1639 Options *command_options = cmd_obj->GetOptions();
1640 if (command_options && command_options->SupportsLongOption("gdb-format"))
1641 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001642 std::string gdb_format_option ("--gdb-format=");
1643 gdb_format_option += (suffix.c_str() + 1);
1644
1645 bool inserted = false;
1646 std::string &cmd = revised_command_line.GetString();
1647 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1648 if (arg_terminator_idx != std::string::npos)
1649 {
1650 // Insert the gdb format option before the "--" that terminates options
1651 gdb_format_option.append(1,' ');
1652 cmd.insert(arg_terminator_idx, gdb_format_option);
1653 inserted = true;
1654 }
1655
1656 if (!inserted)
1657 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1658
1659 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1660 revised_command_line.PutCString (" --");
Greg Clayton52ec56c2011-10-29 00:57:28 +00001661 }
1662 else
1663 {
1664 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1665 cmd_obj->GetCommandName());
1666 result.SetStatus (eReturnStatusFailed);
1667 return false;
1668 }
1669 }
Greg Clayton5521f992011-10-28 21:38:01 +00001670 break;
Johnny Chen8e9383d2011-10-31 22:22:06 +00001671
1672 default:
1673 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1674 suffix.c_str());
1675 result.SetStatus (eReturnStatusFailed);
1676 return false;
1677
Greg Clayton5521f992011-10-28 21:38:01 +00001678 }
1679 }
1680 }
Caroline Tice844d2302010-12-09 22:52:49 +00001681 if (command_string.length() == 0)
1682 done = true;
1683
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001684 }
Caroline Tice844d2302010-12-09 22:52:49 +00001685
Greg Clayton5521f992011-10-28 21:38:01 +00001686 if (!command_string.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001687 revised_command_line.Printf (" %s", command_string.c_str());
1688
1689 // End of Phase 1.
1690 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1691 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1692 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1693 // wants_raw_input specifies whether the Execute method expects raw input or not.
1694
1695
1696 if (log)
1697 {
1698 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1699 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1700 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1701 }
1702
1703 // Phase 2.
1704 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1705 // CommandObject, with the appropriate arguments.
1706
1707 if (cmd_obj != NULL)
1708 {
1709 if (add_to_history)
1710 {
1711 Args command_args (revised_command_line.GetData());
1712 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1713 if (repeat_command != NULL)
1714 m_repeat_command.assign(repeat_command);
1715 else
Jim Inghama5a97eb2011-07-12 03:12:18 +00001716 m_repeat_command.assign(original_command_string.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001717
Jim Inghama5a97eb2011-07-12 03:12:18 +00001718 // Don't keep pushing the same command onto the history...
Greg Clayton5521f992011-10-28 21:38:01 +00001719 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001720 m_command_history.push_back (original_command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001721 }
1722
1723 command_string = revised_command_line.GetData();
1724 std::string command_name (cmd_obj->GetCommandName());
Caroline Tice01274c02010-12-11 08:16:56 +00001725 std::string remainder;
1726 if (actual_cmd_name_len < command_string.length())
1727 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1728 // than cmd_obj->GetCommandName(), because name completion
1729 // allows users to enter short versions of the names,
1730 // e.g. 'br s' for 'breakpoint set'.
Caroline Tice844d2302010-12-09 22:52:49 +00001731
1732 // Remove any initial spaces
1733 std::string white_space (" \t\v");
1734 size_t pos = remainder.find_first_not_of (white_space);
1735 if (pos != 0 && pos != std::string::npos)
Greg Claytona3482592011-04-22 20:58:45 +00001736 remainder.erase(0, pos);
Caroline Tice844d2302010-12-09 22:52:49 +00001737
1738 if (log)
Jason Molendabfb36ff2011-08-25 00:20:04 +00001739 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001740
Jim Ingham5a988412012-06-08 21:56:10 +00001741 cmd_obj->Execute (remainder.c_str(), result);
Caroline Tice844d2302010-12-09 22:52:49 +00001742 }
1743 else
1744 {
1745 // We didn't find the first command object, so complete the first argument.
1746 Args command_args (revised_command_line.GetData());
1747 StringList matches;
1748 int num_matches;
1749 int cursor_index = 0;
1750 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1751 bool word_complete;
1752 num_matches = HandleCompletionMatches (command_args,
1753 cursor_index,
1754 cursor_char_position,
1755 0,
1756 -1,
1757 word_complete,
1758 matches);
1759
1760 if (num_matches > 0)
1761 {
1762 std::string error_msg;
1763 error_msg.assign ("ambiguous command '");
1764 error_msg.append(command_args.GetArgumentAtIndex(0));
1765 error_msg.append ("'.");
1766
1767 error_msg.append (" Possible completions:");
1768 for (int i = 0; i < num_matches; i++)
1769 {
1770 error_msg.append ("\n\t");
1771 error_msg.append (matches.GetStringAtIndex (i));
1772 }
1773 error_msg.append ("\n");
Greg Claytonc7bece562013-01-25 18:06:21 +00001774 result.AppendRawError (error_msg.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001775 }
1776 else
1777 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1778
1779 result.SetStatus (eReturnStatusFailed);
1780 }
1781
Jason Molendabfb36ff2011-08-25 00:20:04 +00001782 if (log)
1783 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1784
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001785 return result.Succeeded();
1786}
1787
1788int
1789CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1790 int &cursor_index,
1791 int &cursor_char_position,
1792 int match_start_point,
1793 int max_return_elements,
Jim Ingham558ce122010-06-30 05:02:46 +00001794 bool &word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001795 StringList &matches)
1796{
1797 int num_command_matches = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001798 bool look_for_subcommand = false;
Jim Ingham558ce122010-06-30 05:02:46 +00001799
1800 // For any of the command completions a unique match will be a complete word.
1801 word_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001802
1803 if (cursor_index == -1)
1804 {
1805 // We got nothing on the command line, so return the list of commands
Jim Ingham279a6c22010-07-06 22:46:59 +00001806 bool include_aliases = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001807 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1808 }
1809 else if (cursor_index == 0)
1810 {
1811 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Ingham279a6c22010-07-06 22:46:59 +00001812 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001813 num_command_matches = matches.GetSize();
1814
1815 if (num_command_matches == 1
1816 && cmd_obj && cmd_obj->IsMultiwordObject()
1817 && matches.GetStringAtIndex(0) != NULL
1818 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1819 {
1820 look_for_subcommand = true;
1821 num_command_matches = 0;
1822 matches.DeleteStringAtIndex(0);
1823 parsed_line.AppendArgument ("");
1824 cursor_index++;
1825 cursor_char_position = 0;
1826 }
1827 }
1828
1829 if (cursor_index > 0 || look_for_subcommand)
1830 {
1831 // We are completing further on into a commands arguments, so find the command and tell it
1832 // to complete the command.
1833 // First see if there is a matching initial command:
Jim Ingham279a6c22010-07-06 22:46:59 +00001834 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001835 if (command_object == NULL)
1836 {
1837 return 0;
1838 }
1839 else
1840 {
1841 parsed_line.Shift();
1842 cursor_index--;
Greg Claytona7015092010-09-18 01:14:36 +00001843 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton66111032010-06-23 01:19:29 +00001844 cursor_index,
1845 cursor_char_position,
1846 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001847 max_return_elements,
1848 word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001849 matches);
1850 }
1851 }
1852
1853 return num_command_matches;
1854
1855}
1856
1857int
1858CommandInterpreter::HandleCompletion (const char *current_line,
1859 const char *cursor,
1860 const char *last_char,
1861 int match_start_point,
1862 int max_return_elements,
1863 StringList &matches)
1864{
1865 // We parse the argument up to the cursor, so the last argument in parsed_line is
1866 // the one containing the cursor, and the cursor is after the last character.
1867
1868 Args parsed_line(current_line, last_char - current_line);
1869 Args partial_parsed_line(current_line, cursor - current_line);
1870
Jim Inghama5a97eb2011-07-12 03:12:18 +00001871 // Don't complete comments, and if the line we are completing is just the history repeat character,
1872 // substitute the appropriate history line.
1873 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1874 if (first_arg)
1875 {
1876 if (first_arg[0] == m_comment_char)
1877 return 0;
1878 else if (first_arg[0] == m_repeat_char)
1879 {
1880 const char *history_string = FindHistoryString (first_arg);
1881 if (history_string != NULL)
1882 {
1883 matches.Clear();
1884 matches.InsertStringAtIndex(0, history_string);
1885 return -2;
1886 }
1887 else
1888 return 0;
1889
1890 }
1891 }
1892
1893
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001894 int num_args = partial_parsed_line.GetArgumentCount();
1895 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1896 int cursor_char_position;
1897
1898 if (cursor_index == -1)
1899 cursor_char_position = 0;
1900 else
1901 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamfe0c4252010-12-14 19:56:01 +00001902
1903 if (cursor > current_line && cursor[-1] == ' ')
1904 {
1905 // We are just after a space. If we are in an argument, then we will continue
1906 // parsing, but if we are between arguments, then we have to complete whatever the next
1907 // element would be.
1908 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1909 // protected by a quote) then the space will also be in the parsed argument...
1910
1911 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1912 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1913 {
1914 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1915 cursor_index++;
1916 cursor_char_position = 0;
1917 }
1918 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001919
1920 int num_command_matches;
1921
1922 matches.Clear();
1923
1924 // Only max_return_elements == -1 is supported at present:
1925 assert (max_return_elements == -1);
Jim Ingham558ce122010-06-30 05:02:46 +00001926 bool word_complete;
Greg Clayton66111032010-06-23 01:19:29 +00001927 num_command_matches = HandleCompletionMatches (parsed_line,
1928 cursor_index,
1929 cursor_char_position,
1930 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001931 max_return_elements,
1932 word_complete,
Greg Clayton66111032010-06-23 01:19:29 +00001933 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001934
1935 if (num_command_matches <= 0)
1936 return num_command_matches;
1937
1938 if (num_args == 0)
1939 {
1940 // If we got an empty string, insert nothing.
1941 matches.InsertStringAtIndex(0, "");
1942 }
1943 else
1944 {
1945 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1946 // put an empty string in element 0.
1947 std::string command_partial_str;
1948 if (cursor_index >= 0)
Jim Ingham49e80a12010-10-22 18:47:16 +00001949 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1950 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001951
1952 std::string common_prefix;
1953 matches.LongestCommonPrefix (common_prefix);
Greg Claytonc7bece562013-01-25 18:06:21 +00001954 const size_t partial_name_len = command_partial_str.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001955
1956 // If we matched a unique single command, add a space...
Jim Ingham558ce122010-06-30 05:02:46 +00001957 // Only do this if the completer told us this was a complete word, however...
1958 if (num_command_matches == 1 && word_complete)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001959 {
1960 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1961 if (quote_char != '\0')
1962 common_prefix.push_back(quote_char);
1963
1964 common_prefix.push_back(' ');
1965 }
1966 common_prefix.erase (0, partial_name_len);
1967 matches.InsertStringAtIndex(0, common_prefix.c_str());
1968 }
1969 return num_command_matches;
1970}
1971
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001972
1973CommandInterpreter::~CommandInterpreter ()
1974{
1975}
1976
1977const char *
1978CommandInterpreter::GetPrompt ()
1979{
Caroline Ticedaccaa92010-09-20 20:44:43 +00001980 return m_debugger.GetPrompt();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001981}
1982
1983void
1984CommandInterpreter::SetPrompt (const char *new_prompt)
1985{
Caroline Ticedaccaa92010-09-20 20:44:43 +00001986 m_debugger.SetPrompt (new_prompt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001987}
1988
Jim Ingham97a6dc72010-10-04 19:49:29 +00001989size_t
Greg Clayton51b1e2d2011-02-09 01:08:52 +00001990CommandInterpreter::GetConfirmationInputReaderCallback
1991(
1992 void *baton,
1993 InputReader &reader,
1994 lldb::InputReaderAction action,
1995 const char *bytes,
1996 size_t bytes_len
1997)
Jim Ingham97a6dc72010-10-04 19:49:29 +00001998{
Greg Clayton51b1e2d2011-02-09 01:08:52 +00001999 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002000 bool *response_ptr = (bool *) baton;
2001
2002 switch (action)
2003 {
2004 case eInputReaderActivate:
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002005 if (out_file.IsValid())
Jim Ingham97a6dc72010-10-04 19:49:29 +00002006 {
2007 if (reader.GetPrompt())
Caroline Tice31f7d462011-02-02 01:17:56 +00002008 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002009 out_file.Printf ("%s", reader.GetPrompt());
2010 out_file.Flush ();
Caroline Tice31f7d462011-02-02 01:17:56 +00002011 }
Jim Ingham97a6dc72010-10-04 19:49:29 +00002012 }
2013 break;
2014
2015 case eInputReaderDeactivate:
2016 break;
2017
2018 case eInputReaderReactivate:
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002019 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice31f7d462011-02-02 01:17:56 +00002020 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002021 out_file.Printf ("%s", reader.GetPrompt());
2022 out_file.Flush ();
Caroline Tice31f7d462011-02-02 01:17:56 +00002023 }
Jim Ingham97a6dc72010-10-04 19:49:29 +00002024 break;
Caroline Tice969ed3d2011-05-02 20:41:46 +00002025
2026 case eInputReaderAsynchronousOutputWritten:
2027 break;
2028
Jim Ingham97a6dc72010-10-04 19:49:29 +00002029 case eInputReaderGotToken:
2030 if (bytes_len == 0)
2031 {
2032 reader.SetIsDone(true);
2033 }
Jim Inghamc8b47582011-11-14 20:02:01 +00002034 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham97a6dc72010-10-04 19:49:29 +00002035 {
2036 *response_ptr = true;
2037 reader.SetIsDone(true);
2038 }
Jim Inghamc8b47582011-11-14 20:02:01 +00002039 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham97a6dc72010-10-04 19:49:29 +00002040 {
2041 *response_ptr = false;
2042 reader.SetIsDone(true);
2043 }
2044 else
2045 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002046 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham97a6dc72010-10-04 19:49:29 +00002047 {
Jim Ingham78d61482011-11-17 01:22:00 +00002048 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002049 out_file.Flush ();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002050 }
2051 }
2052 break;
2053
Caroline Ticeefed6132010-11-19 20:47:54 +00002054 case eInputReaderInterrupt:
2055 case eInputReaderEndOfFile:
2056 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
2057 reader.SetIsDone (true);
2058 break;
2059
Jim Ingham97a6dc72010-10-04 19:49:29 +00002060 case eInputReaderDone:
2061 break;
2062 }
2063
2064 return bytes_len;
2065
2066}
2067
2068bool
2069CommandInterpreter::Confirm (const char *message, bool default_answer)
2070{
Jim Ingham3bcdb292010-10-04 22:44:14 +00002071 // Check AutoConfirm first:
2072 if (m_debugger.GetAutoConfirm())
2073 return default_answer;
2074
Jim Ingham97a6dc72010-10-04 19:49:29 +00002075 InputReaderSP reader_sp (new InputReader(GetDebugger()));
2076 bool response = default_answer;
2077 if (reader_sp)
2078 {
2079 std::string prompt(message);
2080 prompt.append(": [");
2081 if (default_answer)
2082 prompt.append ("Y/n] ");
2083 else
2084 prompt.append ("y/N] ");
2085
2086 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
2087 &response, // baton
2088 eInputReaderGranularityLine, // token size, to pass to callback function
2089 NULL, // end token
2090 prompt.c_str(), // prompt
2091 true)); // echo input
2092 if (err.Success())
2093 {
2094 GetDebugger().PushInputReader (reader_sp);
2095 }
2096 reader_sp->WaitOnReaderIsDone();
2097 }
2098 return response;
2099}
2100
2101
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002102void
2103CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
2104{
Jim Ingham279a6c22010-07-06 22:46:59 +00002105 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002106
Sean Callanan9a028512012-08-09 00:50:26 +00002107 if (cmd_obj_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002108 {
2109 CommandObject *cmd_obj = cmd_obj_sp.get();
2110 if (cmd_obj->IsCrossRefObject ())
2111 cmd_obj->AddObject (object_type);
2112 }
2113}
2114
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002115OptionArgVectorSP
2116CommandInterpreter::GetAliasOptions (const char *alias_name)
2117{
2118 OptionArgMap::iterator pos;
2119 OptionArgVectorSP ret_val;
2120
2121 std::string alias (alias_name);
2122
2123 if (HasAliasOptions())
2124 {
2125 pos = m_alias_options.find (alias);
2126 if (pos != m_alias_options.end())
2127 ret_val = pos->second;
2128 }
2129
2130 return ret_val;
2131}
2132
2133void
2134CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2135{
2136 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2137 if (pos != m_alias_options.end())
2138 {
2139 m_alias_options.erase (pos);
2140 }
2141}
2142
2143void
2144CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2145{
2146 m_alias_options[alias_name] = option_arg_vector_sp;
2147}
2148
2149bool
2150CommandInterpreter::HasCommands ()
2151{
2152 return (!m_command_dict.empty());
2153}
2154
2155bool
2156CommandInterpreter::HasAliases ()
2157{
2158 return (!m_alias_dict.empty());
2159}
2160
2161bool
2162CommandInterpreter::HasUserCommands ()
2163{
2164 return (!m_user_dict.empty());
2165}
2166
2167bool
2168CommandInterpreter::HasAliasOptions ()
2169{
2170 return (!m_alias_options.empty());
2171}
2172
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002173void
Caroline Tice4ab31c92010-10-12 21:57:09 +00002174CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2175 const char *alias_name,
2176 Args &cmd_args,
Caroline Ticed9d63362010-12-07 19:58:26 +00002177 std::string &raw_input_string,
Caroline Tice4ab31c92010-10-12 21:57:09 +00002178 CommandReturnObject &result)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002179{
2180 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Ticed9d63362010-12-07 19:58:26 +00002181
2182 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002183
Caroline Ticed9d63362010-12-07 19:58:26 +00002184 // Make sure that the alias name is the 0th element in cmd_args
2185 std::string alias_name_str = alias_name;
2186 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2187 cmd_args.Unshift (alias_name);
2188
2189 Args new_args (alias_cmd_obj->GetCommandName());
2190 if (new_args.GetArgumentCount() == 2)
2191 new_args.Shift();
2192
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002193 if (option_arg_vector_sp.get())
2194 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002195 if (wants_raw_input)
2196 {
2197 // We have a command that both has command options and takes raw input. Make *sure* it has a
2198 // " -- " in the right place in the raw_input_string.
2199 size_t pos = raw_input_string.find(" -- ");
2200 if (pos == std::string::npos)
2201 {
2202 // None found; assume it goes at the beginning of the raw input string
2203 raw_input_string.insert (0, " -- ");
2204 }
2205 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002206
2207 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Greg Claytonc7bece562013-01-25 18:06:21 +00002208 const size_t old_size = cmd_args.GetArgumentCount();
Caroline Tice4ab31c92010-10-12 21:57:09 +00002209 std::vector<bool> used (old_size + 1, false);
2210
2211 used[0] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002212
2213 for (int i = 0; i < option_arg_vector->size(); ++i)
2214 {
2215 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Ticed9d63362010-12-07 19:58:26 +00002216 OptionArgValue value_pair = option_pair.second;
2217 int value_type = value_pair.first;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002218 std::string option = option_pair.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00002219 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002220 if (option.compare ("<argument>") == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002221 {
2222 if (!wants_raw_input
2223 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2224 new_args.AppendArgument (value.c_str());
2225 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002226 else
2227 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002228 if (value_type != optional_argument)
2229 new_args.AppendArgument (option.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002230 if (value.compare ("<no-argument>") != 0)
2231 {
2232 int index = GetOptionArgumentPosition (value.c_str());
2233 if (index == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002234 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002235 // value was NOT a positional argument; must be a real value
Caroline Ticed9d63362010-12-07 19:58:26 +00002236 if (value_type != optional_argument)
2237 new_args.AppendArgument (value.c_str());
2238 else
2239 {
2240 char buffer[255];
2241 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2242 new_args.AppendArgument (buffer);
2243 }
2244
2245 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002246 else if (index >= cmd_args.GetArgumentCount())
2247 {
2248 result.AppendErrorWithFormat
2249 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2250 index);
2251 result.SetStatus (eReturnStatusFailed);
2252 return;
2253 }
2254 else
2255 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002256 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2257 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2258 if (strpos != std::string::npos)
2259 {
2260 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2261 }
2262
2263 if (value_type != optional_argument)
2264 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2265 else
2266 {
2267 char buffer[255];
2268 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2269 cmd_args.GetArgumentAtIndex (index));
2270 new_args.AppendArgument (buffer);
2271 }
Caroline Tice4ab31c92010-10-12 21:57:09 +00002272 used[index] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002273 }
2274 }
2275 }
2276 }
2277
2278 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2279 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002280 if (!used[j] && !wants_raw_input)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002281 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2282 }
2283
2284 cmd_args.Clear();
2285 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2286 }
2287 else
2288 {
2289 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Ticed9d63362010-12-07 19:58:26 +00002290 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2291 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2292 // input string.
2293 if (wants_raw_input)
2294 {
2295 cmd_args.Clear();
2296 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2297 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002298 return;
2299 }
2300
2301 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2302 return;
2303}
2304
2305
2306int
2307CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2308{
2309 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2310 // of zero.
2311
2312 char *cptr = (char *) in_string;
2313
2314 // Does it start with '%'
2315 if (cptr[0] == '%')
2316 {
2317 ++cptr;
2318
2319 // Is the rest of it entirely digits?
2320 if (isdigit (cptr[0]))
2321 {
2322 const char *start = cptr;
2323 while (isdigit (cptr[0]))
2324 ++cptr;
2325
2326 // We've gotten to the end of the digits; are we at the end of the string?
2327 if (cptr[0] == '\0')
2328 position = atoi (start);
2329 }
2330 }
2331
2332 return position;
2333}
2334
2335void
2336CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2337{
Jim Ingham16e0c682011-08-12 23:34:31 +00002338 FileSpec init_file;
Greg Clayton14a35512011-09-11 00:01:44 +00002339 if (in_cwd)
Jim Ingham16e0c682011-08-12 23:34:31 +00002340 {
Greg Clayton14a35512011-09-11 00:01:44 +00002341 // In the current working directory we don't load any program specific
2342 // .lldbinit files, we only look for a "./.lldbinit" file.
2343 if (m_skip_lldbinit_files)
2344 return;
2345
2346 init_file.SetFile ("./.lldbinit", true);
Jim Ingham16e0c682011-08-12 23:34:31 +00002347 }
Greg Clayton14a35512011-09-11 00:01:44 +00002348 else
Jim Ingham16e0c682011-08-12 23:34:31 +00002349 {
Greg Clayton14a35512011-09-11 00:01:44 +00002350 // If we aren't looking in the current working directory we are looking
2351 // in the home directory. We will first see if there is an application
2352 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2353 // "-" and the name of the program. If this file doesn't exist, we fall
2354 // back to just the "~/.lldbinit" file. We also obey any requests to not
2355 // load the init files.
2356 const char *init_file_path = "~/.lldbinit";
2357
2358 if (m_skip_app_init_files == false)
2359 {
2360 FileSpec program_file_spec (Host::GetProgramFileSpec());
2361 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham16e0c682011-08-12 23:34:31 +00002362
Greg Clayton14a35512011-09-11 00:01:44 +00002363 if (program_name)
2364 {
2365 char program_init_file_name[PATH_MAX];
2366 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2367 init_file.SetFile (program_init_file_name, true);
2368 if (!init_file.Exists())
2369 init_file.Clear();
2370 }
2371 }
2372
2373 if (!init_file && !m_skip_lldbinit_files)
2374 init_file.SetFile (init_file_path, true);
2375 }
2376
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002377 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2378 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2379
2380 if (init_file.Exists())
2381 {
Jim Inghame16c50a2011-02-18 00:54:25 +00002382 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2383 bool stop_on_continue = true;
2384 bool stop_on_error = false;
2385 bool echo_commands = false;
2386 bool print_results = false;
2387
Enrico Granata5f5ab602012-05-31 01:09:06 +00002388 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002389 }
2390 else
2391 {
2392 // nothing to be done if the file doesn't exist
2393 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2394 }
2395}
2396
Greg Clayton8b82f082011-04-12 05:54:46 +00002397PlatformSP
2398CommandInterpreter::GetPlatform (bool prefer_target_platform)
2399{
2400 PlatformSP platform_sp;
Greg Claytonc14ee322011-09-22 04:58:26 +00002401 if (prefer_target_platform)
2402 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002403 ExecutionContext exe_ctx(GetExecutionContext());
2404 Target *target = exe_ctx.GetTargetPtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002405 if (target)
2406 platform_sp = target->GetPlatform();
2407 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002408
2409 if (!platform_sp)
2410 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2411 return platform_sp;
2412}
2413
Jim Inghame16c50a2011-02-18 00:54:25 +00002414void
Jim Inghambad87fe2011-03-11 01:51:49 +00002415CommandInterpreter::HandleCommands (const StringList &commands,
Jim Inghame16c50a2011-02-18 00:54:25 +00002416 ExecutionContext *override_context,
2417 bool stop_on_continue,
2418 bool stop_on_error,
2419 bool echo_commands,
2420 bool print_results,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002421 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002422 CommandReturnObject &result)
2423{
2424 size_t num_lines = commands.GetSize();
Jim Inghame16c50a2011-02-18 00:54:25 +00002425
2426 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2427 // Make sure you reset this value anywhere you return from the function.
2428
2429 bool old_async_execution = m_debugger.GetAsyncExecution();
2430
2431 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2432 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2433
2434 if (override_context != NULL)
Greg Clayton8b82f082011-04-12 05:54:46 +00002435 UpdateExecutionContext (override_context);
Jim Inghame16c50a2011-02-18 00:54:25 +00002436
2437 if (!stop_on_continue)
2438 {
2439 m_debugger.SetAsyncExecution (false);
2440 }
2441
2442 for (int idx = 0; idx < num_lines; idx++)
2443 {
2444 const char *cmd = commands.GetStringAtIndex(idx);
2445 if (cmd[0] == '\0')
2446 continue;
2447
Jim Inghame16c50a2011-02-18 00:54:25 +00002448 if (echo_commands)
2449 {
2450 result.AppendMessageWithFormat ("%s %s\n",
2451 GetPrompt(),
2452 cmd);
2453 }
2454
Greg Clayton9d0402b2011-02-20 02:15:07 +00002455 CommandReturnObject tmp_result;
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002456 // If override_context is not NULL, pass no_context_switching = true for
2457 // HandleCommand() since we updated our context already.
Enrico Granata5f5ab602012-05-31 01:09:06 +00002458 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002459 NULL, /* override_context */
2460 true, /* repeat_on_empty_command */
2461 override_context != NULL /* no_context_switching */);
Jim Inghame16c50a2011-02-18 00:54:25 +00002462
2463 if (print_results)
2464 {
2465 if (tmp_result.Succeeded())
Jim Ingham85e8b812011-02-19 02:53:09 +00002466 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Inghame16c50a2011-02-18 00:54:25 +00002467 }
2468
2469 if (!success || !tmp_result.Succeeded())
2470 {
Jim Inghama5038812012-04-24 02:25:07 +00002471 const char *error_msg = tmp_result.GetErrorData();
2472 if (error_msg == NULL || error_msg[0] == '\0')
2473 error_msg = "<unknown error>.\n";
Jim Inghame16c50a2011-02-18 00:54:25 +00002474 if (stop_on_error)
2475 {
Jim Inghama5038812012-04-24 02:25:07 +00002476 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2477 idx, cmd, error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002478 result.SetStatus (eReturnStatusFailed);
2479 m_debugger.SetAsyncExecution (old_async_execution);
2480 return;
2481 }
2482 else if (print_results)
2483 {
Jim Inghama5038812012-04-24 02:25:07 +00002484 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Inghame16c50a2011-02-18 00:54:25 +00002485 idx + 1,
2486 cmd,
Jim Inghama5038812012-04-24 02:25:07 +00002487 error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002488 }
2489 }
2490
Caroline Tice969ed3d2011-05-02 20:41:46 +00002491 if (result.GetImmediateOutputStream())
2492 result.GetImmediateOutputStream()->Flush();
2493
2494 if (result.GetImmediateErrorStream())
2495 result.GetImmediateErrorStream()->Flush();
2496
Jim Inghame16c50a2011-02-18 00:54:25 +00002497 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2498 // could be running (for instance in Breakpoint Commands.
2499 // So we check the return value to see if it is has running in it.
2500 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2501 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2502 {
2503 if (stop_on_continue)
2504 {
2505 // If we caused the target to proceed, and we're going to stop in that case, set the
2506 // status in our real result before returning. This is an error if the continue was not the
2507 // last command in the set of commands to be run.
2508 if (idx != num_lines - 1)
2509 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2510 idx + 1, cmd);
2511 else
2512 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2513
2514 result.SetStatus(tmp_result.GetStatus());
2515 m_debugger.SetAsyncExecution (old_async_execution);
2516
2517 return;
2518 }
2519 }
2520
2521 }
2522
2523 result.SetStatus (eReturnStatusSuccessFinishResult);
2524 m_debugger.SetAsyncExecution (old_async_execution);
2525
2526 return;
2527}
2528
2529void
2530CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2531 ExecutionContext *context,
2532 bool stop_on_continue,
2533 bool stop_on_error,
2534 bool echo_command,
2535 bool print_result,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002536 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002537 CommandReturnObject &result)
2538{
2539 if (cmd_file.Exists())
2540 {
2541 bool success;
2542 StringList commands;
2543 success = commands.ReadFileLines(cmd_file);
2544 if (!success)
2545 {
2546 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2547 result.SetStatus (eReturnStatusFailed);
2548 return;
2549 }
Enrico Granata5f5ab602012-05-31 01:09:06 +00002550 m_command_source_depth++;
2551 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2552 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002553 }
2554 else
2555 {
2556 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2557 cmd_file.GetFilename().AsCString());
2558 result.SetStatus (eReturnStatusFailed);
2559 return;
2560 }
2561}
2562
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002563ScriptInterpreter *
Enrico Granatab5887262012-10-29 21:18:03 +00002564CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002565{
Enrico Granatab5887262012-10-29 21:18:03 +00002566 if (m_script_interpreter_ap.get() != NULL)
2567 return m_script_interpreter_ap.get();
2568
2569 if (!can_create)
2570 return NULL;
2571
Enrico Granataa29bdad2012-07-10 18:23:48 +00002572 // <rdar://problem/11751427>
2573 // we need to protect the initialization of the script interpreter
2574 // otherwise we could end up with two threads both trying to create
2575 // their instance of it, and for some languages (e.g. Python)
2576 // this is a bulletproof recipe for disaster!
2577 // this needs to be a function-level static because multiple Debugger instances living in the same process
2578 // still need to be isolated and not try to initialize Python concurrently
Enrico Granata8b95df22012-07-10 19:04:14 +00002579 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2580 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granataa29bdad2012-07-10 18:23:48 +00002581
Enrico Granatab5887262012-10-29 21:18:03 +00002582 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
2583 if (log)
2584 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton66111032010-06-23 01:19:29 +00002585
Caroline Tice2f88aad2011-01-14 00:29:16 +00002586 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2587 switch (script_lang)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002588 {
Greg Claytondce502e2011-11-04 03:34:56 +00002589 case eScriptLanguagePython:
2590#ifndef LLDB_DISABLE_PYTHON
2591 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2592 break;
2593#else
2594 // Fall through to the None case when python is disabled
2595#endif
Caroline Tice2f88aad2011-01-14 00:29:16 +00002596 case eScriptLanguageNone:
2597 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2598 break;
Caroline Tice2f88aad2011-01-14 00:29:16 +00002599 };
2600
2601 return m_script_interpreter_ap.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002602}
2603
2604
2605
2606bool
2607CommandInterpreter::GetSynchronous ()
2608{
2609 return m_synchronous_execution;
2610}
2611
2612void
2613CommandInterpreter::SetSynchronous (bool value)
2614{
Johnny Chenc066ab42010-10-14 01:22:03 +00002615 m_synchronous_execution = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002616}
2617
2618void
2619CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2620 const char *word_text,
2621 const char *separator,
2622 const char *help_text,
Greg Claytonc7bece562013-01-25 18:06:21 +00002623 size_t max_word_len)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002624{
Greg Claytona7015092010-09-18 01:14:36 +00002625 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2626
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002627 int indent_size = max_word_len + strlen (separator) + 2;
2628
2629 strm.IndentMore (indent_size);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002630
2631 StreamString text_strm;
Greg Claytonc7bece562013-01-25 18:06:21 +00002632 text_strm.Printf ("%-*s %s %s", (int)max_word_len, word_text, separator, help_text);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002633
2634 size_t len = text_strm.GetSize();
2635 const char *text = text_strm.GetData();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002636 if (text[len - 1] == '\n')
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002637 {
2638 text_strm.EOL();
2639 len = text_strm.GetSize();
2640 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002641
2642 if (len < max_columns)
2643 {
2644 // Output it as a single line.
2645 strm.Printf ("%s", text);
2646 }
2647 else
2648 {
2649 // We need to break it up into multiple lines.
2650 bool first_line = true;
2651 int text_width;
Greg Claytonc7bece562013-01-25 18:06:21 +00002652 size_t start = 0;
2653 size_t end = start;
2654 const size_t final_end = strlen (text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002655
2656 while (end < final_end)
2657 {
2658 if (first_line)
2659 text_width = max_columns - 1;
2660 else
2661 text_width = max_columns - indent_size - 1;
2662
2663 // Don't start the 'text' on a space, since we're already outputting the indentation.
2664 if (!first_line)
2665 {
2666 while ((start < final_end) && (text[start] == ' '))
2667 start++;
2668 }
2669
2670 end = start + text_width;
2671 if (end > final_end)
2672 end = final_end;
2673 else
2674 {
2675 // If we're not at the end of the text, make sure we break the line on white space.
2676 while (end > start
2677 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2678 end--;
Greg Clayton67cc0632012-08-22 17:17:09 +00002679 assert (end > 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002680 }
2681
Greg Claytonc7bece562013-01-25 18:06:21 +00002682 const size_t sub_len = end - start;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002683 if (start != 0)
2684 strm.EOL();
2685 if (!first_line)
2686 strm.Indent();
2687 else
2688 first_line = false;
2689 assert (start <= final_end);
2690 assert (start + sub_len <= final_end);
2691 if (sub_len > 0)
2692 strm.Write (text + start, sub_len);
2693 start = end + 1;
2694 }
2695 }
2696 strm.EOL();
2697 strm.IndentLess(indent_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002698}
2699
2700void
Enrico Granata82a7d982011-07-07 00:38:40 +00002701CommandInterpreter::OutputHelpText (Stream &strm,
2702 const char *word_text,
2703 const char *separator,
2704 const char *help_text,
2705 uint32_t max_word_len)
2706{
2707 int indent_size = max_word_len + strlen (separator) + 2;
2708
2709 strm.IndentMore (indent_size);
2710
2711 StreamString text_strm;
2712 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2713
2714 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata82a7d982011-07-07 00:38:40 +00002715
2716 size_t len = text_strm.GetSize();
2717 const char *text = text_strm.GetData();
2718
2719 uint32_t chars_left = max_columns;
2720
2721 for (uint32_t i = 0; i < len; i++)
2722 {
2723 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2724 {
Enrico Granata82a7d982011-07-07 00:38:40 +00002725 chars_left = max_columns - indent_size;
2726 strm.EOL();
2727 strm.Indent();
2728 }
2729 else
2730 {
2731 strm.PutChar(text[i]);
2732 chars_left--;
2733 }
2734
2735 }
2736
2737 strm.EOL();
2738 strm.IndentLess(indent_size);
2739}
2740
2741void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002742CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2743 StringList &commands_help)
2744{
2745 CommandObject::CommandMap::const_iterator pos;
2746
2747 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2748 {
2749 const char *command_name = pos->first.c_str();
2750 CommandObject *cmd_obj = pos->second.get();
2751
Greg Claytona7015092010-09-18 01:14:36 +00002752 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002753 {
2754 commands_found.AppendString (command_name);
2755 commands_help.AppendString (cmd_obj->GetHelp());
2756 }
2757
2758 if (cmd_obj->IsMultiwordObject())
Greg Clayton998255b2012-10-13 02:07:45 +00002759 cmd_obj->AproposAllSubCommands (command_name,
2760 search_word,
2761 commands_found,
2762 commands_help);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002763
2764 }
2765}
Greg Clayton8b82f082011-04-12 05:54:46 +00002766
2767
2768void
2769CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2770{
Greg Clayton8b82f082011-04-12 05:54:46 +00002771 if (override_context != NULL)
2772 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002773 m_exe_ctx_ref = *override_context;
Greg Clayton8b82f082011-04-12 05:54:46 +00002774 }
2775 else
2776 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002777 const bool adopt_selected = true;
2778 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Clayton8b82f082011-04-12 05:54:46 +00002779 }
2780}
2781
Jim Inghama5a97eb2011-07-12 03:12:18 +00002782void
2783CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2784{
2785 DumpHistory (stream, 0, count - 1);
2786}
2787
2788void
2789CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2790{
Greg Clayton5521f992011-10-28 21:38:01 +00002791 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2792 for (size_t i = start; i < last_idx; i++)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002793 {
2794 if (!m_command_history[i].empty())
2795 {
2796 stream.Indent();
Greg Clayton5521f992011-10-28 21:38:01 +00002797 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Inghama5a97eb2011-07-12 03:12:18 +00002798 }
2799 }
2800}
2801
2802const char *
2803CommandInterpreter::FindHistoryString (const char *input_str) const
2804{
2805 if (input_str[0] != m_repeat_char)
2806 return NULL;
2807 if (input_str[1] == '-')
2808 {
2809 bool success;
Greg Claytonc7bece562013-01-25 18:06:21 +00002810 size_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
Jim Inghama5a97eb2011-07-12 03:12:18 +00002811 if (!success)
2812 return NULL;
2813 if (idx > m_command_history.size())
2814 return NULL;
2815 idx = m_command_history.size() - idx;
2816 return m_command_history[idx].c_str();
2817
2818 }
2819 else if (input_str[1] == m_repeat_char)
2820 {
2821 if (m_command_history.empty())
2822 return NULL;
2823 else
2824 return m_command_history.back().c_str();
2825 }
2826 else
2827 {
2828 bool success;
2829 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2830 if (!success)
2831 return NULL;
2832 if (idx >= m_command_history.size())
2833 return NULL;
2834 return m_command_history[idx].c_str();
2835 }
2836}