blob: 7dfc5d8318e5fb3a12350f0ba4c1aa04c2043207 [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"},
399 {"^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
400 {"^(-.*)$", "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;
603 CommandObjectSP ret_val;
604
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())
611 ret_val = pos->second;
612 }
613
614 if (include_aliases && HasAliases())
615 {
616 pos = m_alias_dict.find(cmd);
617 if (pos != m_alias_dict.end())
618 ret_val = pos->second;
619 }
620
621 if (HasUserCommands())
622 {
623 pos = m_user_dict.find(cmd);
624 if (pos != m_user_dict.end())
625 ret_val = pos->second;
626 }
627
Sean Callanan9a028512012-08-09 00:50:26 +0000628 if (!exact && !ret_val)
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 }
Sean Callanan9a028512012-08-09 00:50:26 +0000698 else if (matches && ret_val)
Jim Ingham279a6c22010-07-06 22:46:59 +0000699 {
700 matches->AppendString (cmd_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000701 }
702
703
704 return ret_val;
705}
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 {
874 int argc = args.GetArgumentCount();
875 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 Clayton12fc3e02010-08-26 22:05:43 +0000984 uint32_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 {
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001598 uint32_t num_matches = matches.GetSize();
1599 if (matches.GetSize() > 1) {
1600 std::string error_msg;
1601 error_msg.assign ("Ambiguous command '");
1602 error_msg.append(next_word.c_str());
1603 error_msg.append ("'.");
1604
1605 error_msg.append (" Possible matches:");
1606
1607 for (uint32_t i = 0; i < num_matches; ++i) {
1608 error_msg.append ("\n\t");
1609 error_msg.append (matches.GetStringAtIndex(i));
1610 }
1611 error_msg.append ("\n");
1612 result.AppendRawError (error_msg.c_str(), error_msg.size());
1613 } else {
1614 // We didn't have only one match, otherwise we wouldn't get here.
1615 assert(num_matches == 0);
1616 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1617 }
Caroline Tice844d2302010-12-09 22:52:49 +00001618 result.SetStatus (eReturnStatusFailed);
1619 return false;
1620 }
1621
Greg Clayton5521f992011-10-28 21:38:01 +00001622 if (cmd_obj->IsMultiwordObject ())
1623 {
1624 if (!suffix.empty())
1625 {
1626
1627 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1628 next_word.c_str(),
1629 suffix.c_str());
1630 result.SetStatus (eReturnStatusFailed);
1631 return false;
1632 }
1633 }
1634 else
1635 {
1636 // If we found a normal command, we are done
1637 done = true;
1638 if (!suffix.empty())
1639 {
1640 switch (suffix[0])
1641 {
1642 case '/':
1643 // GDB format suffixes
Greg Clayton52ec56c2011-10-29 00:57:28 +00001644 {
1645 Options *command_options = cmd_obj->GetOptions();
1646 if (command_options && command_options->SupportsLongOption("gdb-format"))
1647 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001648 std::string gdb_format_option ("--gdb-format=");
1649 gdb_format_option += (suffix.c_str() + 1);
1650
1651 bool inserted = false;
1652 std::string &cmd = revised_command_line.GetString();
1653 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1654 if (arg_terminator_idx != std::string::npos)
1655 {
1656 // Insert the gdb format option before the "--" that terminates options
1657 gdb_format_option.append(1,' ');
1658 cmd.insert(arg_terminator_idx, gdb_format_option);
1659 inserted = true;
1660 }
1661
1662 if (!inserted)
1663 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1664
1665 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1666 revised_command_line.PutCString (" --");
Greg Clayton52ec56c2011-10-29 00:57:28 +00001667 }
1668 else
1669 {
1670 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1671 cmd_obj->GetCommandName());
1672 result.SetStatus (eReturnStatusFailed);
1673 return false;
1674 }
1675 }
Greg Clayton5521f992011-10-28 21:38:01 +00001676 break;
Johnny Chen8e9383d2011-10-31 22:22:06 +00001677
1678 default:
1679 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1680 suffix.c_str());
1681 result.SetStatus (eReturnStatusFailed);
1682 return false;
1683
Greg Clayton5521f992011-10-28 21:38:01 +00001684 }
1685 }
1686 }
Caroline Tice844d2302010-12-09 22:52:49 +00001687 if (command_string.length() == 0)
1688 done = true;
1689
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001690 }
Caroline Tice844d2302010-12-09 22:52:49 +00001691
Greg Clayton5521f992011-10-28 21:38:01 +00001692 if (!command_string.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001693 revised_command_line.Printf (" %s", command_string.c_str());
1694
1695 // End of Phase 1.
1696 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1697 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1698 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1699 // wants_raw_input specifies whether the Execute method expects raw input or not.
1700
1701
1702 if (log)
1703 {
1704 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1705 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1706 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1707 }
1708
1709 // Phase 2.
1710 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1711 // CommandObject, with the appropriate arguments.
1712
1713 if (cmd_obj != NULL)
1714 {
1715 if (add_to_history)
1716 {
1717 Args command_args (revised_command_line.GetData());
1718 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1719 if (repeat_command != NULL)
1720 m_repeat_command.assign(repeat_command);
1721 else
Jim Inghama5a97eb2011-07-12 03:12:18 +00001722 m_repeat_command.assign(original_command_string.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001723
Jim Inghama5a97eb2011-07-12 03:12:18 +00001724 // Don't keep pushing the same command onto the history...
Greg Clayton5521f992011-10-28 21:38:01 +00001725 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001726 m_command_history.push_back (original_command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001727 }
1728
1729 command_string = revised_command_line.GetData();
1730 std::string command_name (cmd_obj->GetCommandName());
Caroline Tice01274c02010-12-11 08:16:56 +00001731 std::string remainder;
1732 if (actual_cmd_name_len < command_string.length())
1733 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1734 // than cmd_obj->GetCommandName(), because name completion
1735 // allows users to enter short versions of the names,
1736 // e.g. 'br s' for 'breakpoint set'.
Caroline Tice844d2302010-12-09 22:52:49 +00001737
1738 // Remove any initial spaces
1739 std::string white_space (" \t\v");
1740 size_t pos = remainder.find_first_not_of (white_space);
1741 if (pos != 0 && pos != std::string::npos)
Greg Claytona3482592011-04-22 20:58:45 +00001742 remainder.erase(0, pos);
Caroline Tice844d2302010-12-09 22:52:49 +00001743
1744 if (log)
Jason Molendabfb36ff2011-08-25 00:20:04 +00001745 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001746
Jim Ingham5a988412012-06-08 21:56:10 +00001747 cmd_obj->Execute (remainder.c_str(), result);
Caroline Tice844d2302010-12-09 22:52:49 +00001748 }
1749 else
1750 {
1751 // We didn't find the first command object, so complete the first argument.
1752 Args command_args (revised_command_line.GetData());
1753 StringList matches;
1754 int num_matches;
1755 int cursor_index = 0;
1756 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1757 bool word_complete;
1758 num_matches = HandleCompletionMatches (command_args,
1759 cursor_index,
1760 cursor_char_position,
1761 0,
1762 -1,
1763 word_complete,
1764 matches);
1765
1766 if (num_matches > 0)
1767 {
1768 std::string error_msg;
1769 error_msg.assign ("ambiguous command '");
1770 error_msg.append(command_args.GetArgumentAtIndex(0));
1771 error_msg.append ("'.");
1772
1773 error_msg.append (" Possible completions:");
1774 for (int i = 0; i < num_matches; i++)
1775 {
1776 error_msg.append ("\n\t");
1777 error_msg.append (matches.GetStringAtIndex (i));
1778 }
1779 error_msg.append ("\n");
1780 result.AppendRawError (error_msg.c_str(), error_msg.size());
1781 }
1782 else
1783 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1784
1785 result.SetStatus (eReturnStatusFailed);
1786 }
1787
Jason Molendabfb36ff2011-08-25 00:20:04 +00001788 if (log)
1789 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1790
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001791 return result.Succeeded();
1792}
1793
1794int
1795CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1796 int &cursor_index,
1797 int &cursor_char_position,
1798 int match_start_point,
1799 int max_return_elements,
Jim Ingham558ce122010-06-30 05:02:46 +00001800 bool &word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001801 StringList &matches)
1802{
1803 int num_command_matches = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001804 bool look_for_subcommand = false;
Jim Ingham558ce122010-06-30 05:02:46 +00001805
1806 // For any of the command completions a unique match will be a complete word.
1807 word_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001808
1809 if (cursor_index == -1)
1810 {
1811 // We got nothing on the command line, so return the list of commands
Jim Ingham279a6c22010-07-06 22:46:59 +00001812 bool include_aliases = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001813 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1814 }
1815 else if (cursor_index == 0)
1816 {
1817 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Ingham279a6c22010-07-06 22:46:59 +00001818 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001819 num_command_matches = matches.GetSize();
1820
1821 if (num_command_matches == 1
1822 && cmd_obj && cmd_obj->IsMultiwordObject()
1823 && matches.GetStringAtIndex(0) != NULL
1824 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1825 {
1826 look_for_subcommand = true;
1827 num_command_matches = 0;
1828 matches.DeleteStringAtIndex(0);
1829 parsed_line.AppendArgument ("");
1830 cursor_index++;
1831 cursor_char_position = 0;
1832 }
1833 }
1834
1835 if (cursor_index > 0 || look_for_subcommand)
1836 {
1837 // We are completing further on into a commands arguments, so find the command and tell it
1838 // to complete the command.
1839 // First see if there is a matching initial command:
Jim Ingham279a6c22010-07-06 22:46:59 +00001840 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001841 if (command_object == NULL)
1842 {
1843 return 0;
1844 }
1845 else
1846 {
1847 parsed_line.Shift();
1848 cursor_index--;
Greg Claytona7015092010-09-18 01:14:36 +00001849 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton66111032010-06-23 01:19:29 +00001850 cursor_index,
1851 cursor_char_position,
1852 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001853 max_return_elements,
1854 word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001855 matches);
1856 }
1857 }
1858
1859 return num_command_matches;
1860
1861}
1862
1863int
1864CommandInterpreter::HandleCompletion (const char *current_line,
1865 const char *cursor,
1866 const char *last_char,
1867 int match_start_point,
1868 int max_return_elements,
1869 StringList &matches)
1870{
1871 // We parse the argument up to the cursor, so the last argument in parsed_line is
1872 // the one containing the cursor, and the cursor is after the last character.
1873
1874 Args parsed_line(current_line, last_char - current_line);
1875 Args partial_parsed_line(current_line, cursor - current_line);
1876
Jim Inghama5a97eb2011-07-12 03:12:18 +00001877 // Don't complete comments, and if the line we are completing is just the history repeat character,
1878 // substitute the appropriate history line.
1879 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1880 if (first_arg)
1881 {
1882 if (first_arg[0] == m_comment_char)
1883 return 0;
1884 else if (first_arg[0] == m_repeat_char)
1885 {
1886 const char *history_string = FindHistoryString (first_arg);
1887 if (history_string != NULL)
1888 {
1889 matches.Clear();
1890 matches.InsertStringAtIndex(0, history_string);
1891 return -2;
1892 }
1893 else
1894 return 0;
1895
1896 }
1897 }
1898
1899
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001900 int num_args = partial_parsed_line.GetArgumentCount();
1901 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1902 int cursor_char_position;
1903
1904 if (cursor_index == -1)
1905 cursor_char_position = 0;
1906 else
1907 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamfe0c4252010-12-14 19:56:01 +00001908
1909 if (cursor > current_line && cursor[-1] == ' ')
1910 {
1911 // We are just after a space. If we are in an argument, then we will continue
1912 // parsing, but if we are between arguments, then we have to complete whatever the next
1913 // element would be.
1914 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1915 // protected by a quote) then the space will also be in the parsed argument...
1916
1917 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1918 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1919 {
1920 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1921 cursor_index++;
1922 cursor_char_position = 0;
1923 }
1924 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001925
1926 int num_command_matches;
1927
1928 matches.Clear();
1929
1930 // Only max_return_elements == -1 is supported at present:
1931 assert (max_return_elements == -1);
Jim Ingham558ce122010-06-30 05:02:46 +00001932 bool word_complete;
Greg Clayton66111032010-06-23 01:19:29 +00001933 num_command_matches = HandleCompletionMatches (parsed_line,
1934 cursor_index,
1935 cursor_char_position,
1936 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001937 max_return_elements,
1938 word_complete,
Greg Clayton66111032010-06-23 01:19:29 +00001939 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001940
1941 if (num_command_matches <= 0)
1942 return num_command_matches;
1943
1944 if (num_args == 0)
1945 {
1946 // If we got an empty string, insert nothing.
1947 matches.InsertStringAtIndex(0, "");
1948 }
1949 else
1950 {
1951 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1952 // put an empty string in element 0.
1953 std::string command_partial_str;
1954 if (cursor_index >= 0)
Jim Ingham49e80a12010-10-22 18:47:16 +00001955 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1956 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001957
1958 std::string common_prefix;
1959 matches.LongestCommonPrefix (common_prefix);
1960 int partial_name_len = command_partial_str.size();
1961
1962 // If we matched a unique single command, add a space...
Jim Ingham558ce122010-06-30 05:02:46 +00001963 // Only do this if the completer told us this was a complete word, however...
1964 if (num_command_matches == 1 && word_complete)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001965 {
1966 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1967 if (quote_char != '\0')
1968 common_prefix.push_back(quote_char);
1969
1970 common_prefix.push_back(' ');
1971 }
1972 common_prefix.erase (0, partial_name_len);
1973 matches.InsertStringAtIndex(0, common_prefix.c_str());
1974 }
1975 return num_command_matches;
1976}
1977
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001978
1979CommandInterpreter::~CommandInterpreter ()
1980{
1981}
1982
1983const char *
1984CommandInterpreter::GetPrompt ()
1985{
Caroline Ticedaccaa92010-09-20 20:44:43 +00001986 return m_debugger.GetPrompt();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001987}
1988
1989void
1990CommandInterpreter::SetPrompt (const char *new_prompt)
1991{
Caroline Ticedaccaa92010-09-20 20:44:43 +00001992 m_debugger.SetPrompt (new_prompt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001993}
1994
Jim Ingham97a6dc72010-10-04 19:49:29 +00001995size_t
Greg Clayton51b1e2d2011-02-09 01:08:52 +00001996CommandInterpreter::GetConfirmationInputReaderCallback
1997(
1998 void *baton,
1999 InputReader &reader,
2000 lldb::InputReaderAction action,
2001 const char *bytes,
2002 size_t bytes_len
2003)
Jim Ingham97a6dc72010-10-04 19:49:29 +00002004{
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002005 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002006 bool *response_ptr = (bool *) baton;
2007
2008 switch (action)
2009 {
2010 case eInputReaderActivate:
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002011 if (out_file.IsValid())
Jim Ingham97a6dc72010-10-04 19:49:29 +00002012 {
2013 if (reader.GetPrompt())
Caroline Tice31f7d462011-02-02 01:17:56 +00002014 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002015 out_file.Printf ("%s", reader.GetPrompt());
2016 out_file.Flush ();
Caroline Tice31f7d462011-02-02 01:17:56 +00002017 }
Jim Ingham97a6dc72010-10-04 19:49:29 +00002018 }
2019 break;
2020
2021 case eInputReaderDeactivate:
2022 break;
2023
2024 case eInputReaderReactivate:
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002025 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice31f7d462011-02-02 01:17:56 +00002026 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002027 out_file.Printf ("%s", reader.GetPrompt());
2028 out_file.Flush ();
Caroline Tice31f7d462011-02-02 01:17:56 +00002029 }
Jim Ingham97a6dc72010-10-04 19:49:29 +00002030 break;
Caroline Tice969ed3d2011-05-02 20:41:46 +00002031
2032 case eInputReaderAsynchronousOutputWritten:
2033 break;
2034
Jim Ingham97a6dc72010-10-04 19:49:29 +00002035 case eInputReaderGotToken:
2036 if (bytes_len == 0)
2037 {
2038 reader.SetIsDone(true);
2039 }
Jim Inghamc8b47582011-11-14 20:02:01 +00002040 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham97a6dc72010-10-04 19:49:29 +00002041 {
2042 *response_ptr = true;
2043 reader.SetIsDone(true);
2044 }
Jim Inghamc8b47582011-11-14 20:02:01 +00002045 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham97a6dc72010-10-04 19:49:29 +00002046 {
2047 *response_ptr = false;
2048 reader.SetIsDone(true);
2049 }
2050 else
2051 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002052 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham97a6dc72010-10-04 19:49:29 +00002053 {
Jim Ingham78d61482011-11-17 01:22:00 +00002054 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002055 out_file.Flush ();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002056 }
2057 }
2058 break;
2059
Caroline Ticeefed6132010-11-19 20:47:54 +00002060 case eInputReaderInterrupt:
2061 case eInputReaderEndOfFile:
2062 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
2063 reader.SetIsDone (true);
2064 break;
2065
Jim Ingham97a6dc72010-10-04 19:49:29 +00002066 case eInputReaderDone:
2067 break;
2068 }
2069
2070 return bytes_len;
2071
2072}
2073
2074bool
2075CommandInterpreter::Confirm (const char *message, bool default_answer)
2076{
Jim Ingham3bcdb292010-10-04 22:44:14 +00002077 // Check AutoConfirm first:
2078 if (m_debugger.GetAutoConfirm())
2079 return default_answer;
2080
Jim Ingham97a6dc72010-10-04 19:49:29 +00002081 InputReaderSP reader_sp (new InputReader(GetDebugger()));
2082 bool response = default_answer;
2083 if (reader_sp)
2084 {
2085 std::string prompt(message);
2086 prompt.append(": [");
2087 if (default_answer)
2088 prompt.append ("Y/n] ");
2089 else
2090 prompt.append ("y/N] ");
2091
2092 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
2093 &response, // baton
2094 eInputReaderGranularityLine, // token size, to pass to callback function
2095 NULL, // end token
2096 prompt.c_str(), // prompt
2097 true)); // echo input
2098 if (err.Success())
2099 {
2100 GetDebugger().PushInputReader (reader_sp);
2101 }
2102 reader_sp->WaitOnReaderIsDone();
2103 }
2104 return response;
2105}
2106
2107
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002108void
2109CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
2110{
Jim Ingham279a6c22010-07-06 22:46:59 +00002111 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002112
Sean Callanan9a028512012-08-09 00:50:26 +00002113 if (cmd_obj_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002114 {
2115 CommandObject *cmd_obj = cmd_obj_sp.get();
2116 if (cmd_obj->IsCrossRefObject ())
2117 cmd_obj->AddObject (object_type);
2118 }
2119}
2120
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002121OptionArgVectorSP
2122CommandInterpreter::GetAliasOptions (const char *alias_name)
2123{
2124 OptionArgMap::iterator pos;
2125 OptionArgVectorSP ret_val;
2126
2127 std::string alias (alias_name);
2128
2129 if (HasAliasOptions())
2130 {
2131 pos = m_alias_options.find (alias);
2132 if (pos != m_alias_options.end())
2133 ret_val = pos->second;
2134 }
2135
2136 return ret_val;
2137}
2138
2139void
2140CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2141{
2142 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2143 if (pos != m_alias_options.end())
2144 {
2145 m_alias_options.erase (pos);
2146 }
2147}
2148
2149void
2150CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2151{
2152 m_alias_options[alias_name] = option_arg_vector_sp;
2153}
2154
2155bool
2156CommandInterpreter::HasCommands ()
2157{
2158 return (!m_command_dict.empty());
2159}
2160
2161bool
2162CommandInterpreter::HasAliases ()
2163{
2164 return (!m_alias_dict.empty());
2165}
2166
2167bool
2168CommandInterpreter::HasUserCommands ()
2169{
2170 return (!m_user_dict.empty());
2171}
2172
2173bool
2174CommandInterpreter::HasAliasOptions ()
2175{
2176 return (!m_alias_options.empty());
2177}
2178
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002179void
Caroline Tice4ab31c92010-10-12 21:57:09 +00002180CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2181 const char *alias_name,
2182 Args &cmd_args,
Caroline Ticed9d63362010-12-07 19:58:26 +00002183 std::string &raw_input_string,
Caroline Tice4ab31c92010-10-12 21:57:09 +00002184 CommandReturnObject &result)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002185{
2186 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Ticed9d63362010-12-07 19:58:26 +00002187
2188 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002189
Caroline Ticed9d63362010-12-07 19:58:26 +00002190 // Make sure that the alias name is the 0th element in cmd_args
2191 std::string alias_name_str = alias_name;
2192 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2193 cmd_args.Unshift (alias_name);
2194
2195 Args new_args (alias_cmd_obj->GetCommandName());
2196 if (new_args.GetArgumentCount() == 2)
2197 new_args.Shift();
2198
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002199 if (option_arg_vector_sp.get())
2200 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002201 if (wants_raw_input)
2202 {
2203 // We have a command that both has command options and takes raw input. Make *sure* it has a
2204 // " -- " in the right place in the raw_input_string.
2205 size_t pos = raw_input_string.find(" -- ");
2206 if (pos == std::string::npos)
2207 {
2208 // None found; assume it goes at the beginning of the raw input string
2209 raw_input_string.insert (0, " -- ");
2210 }
2211 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002212
2213 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2214 int old_size = cmd_args.GetArgumentCount();
Caroline Tice4ab31c92010-10-12 21:57:09 +00002215 std::vector<bool> used (old_size + 1, false);
2216
2217 used[0] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002218
2219 for (int i = 0; i < option_arg_vector->size(); ++i)
2220 {
2221 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Ticed9d63362010-12-07 19:58:26 +00002222 OptionArgValue value_pair = option_pair.second;
2223 int value_type = value_pair.first;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002224 std::string option = option_pair.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00002225 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002226 if (option.compare ("<argument>") == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002227 {
2228 if (!wants_raw_input
2229 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2230 new_args.AppendArgument (value.c_str());
2231 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002232 else
2233 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002234 if (value_type != optional_argument)
2235 new_args.AppendArgument (option.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002236 if (value.compare ("<no-argument>") != 0)
2237 {
2238 int index = GetOptionArgumentPosition (value.c_str());
2239 if (index == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002240 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002241 // value was NOT a positional argument; must be a real value
Caroline Ticed9d63362010-12-07 19:58:26 +00002242 if (value_type != optional_argument)
2243 new_args.AppendArgument (value.c_str());
2244 else
2245 {
2246 char buffer[255];
2247 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2248 new_args.AppendArgument (buffer);
2249 }
2250
2251 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002252 else if (index >= cmd_args.GetArgumentCount())
2253 {
2254 result.AppendErrorWithFormat
2255 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2256 index);
2257 result.SetStatus (eReturnStatusFailed);
2258 return;
2259 }
2260 else
2261 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002262 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2263 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2264 if (strpos != std::string::npos)
2265 {
2266 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2267 }
2268
2269 if (value_type != optional_argument)
2270 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2271 else
2272 {
2273 char buffer[255];
2274 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2275 cmd_args.GetArgumentAtIndex (index));
2276 new_args.AppendArgument (buffer);
2277 }
Caroline Tice4ab31c92010-10-12 21:57:09 +00002278 used[index] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002279 }
2280 }
2281 }
2282 }
2283
2284 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2285 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002286 if (!used[j] && !wants_raw_input)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002287 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2288 }
2289
2290 cmd_args.Clear();
2291 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2292 }
2293 else
2294 {
2295 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Ticed9d63362010-12-07 19:58:26 +00002296 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2297 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2298 // input string.
2299 if (wants_raw_input)
2300 {
2301 cmd_args.Clear();
2302 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2303 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002304 return;
2305 }
2306
2307 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2308 return;
2309}
2310
2311
2312int
2313CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2314{
2315 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2316 // of zero.
2317
2318 char *cptr = (char *) in_string;
2319
2320 // Does it start with '%'
2321 if (cptr[0] == '%')
2322 {
2323 ++cptr;
2324
2325 // Is the rest of it entirely digits?
2326 if (isdigit (cptr[0]))
2327 {
2328 const char *start = cptr;
2329 while (isdigit (cptr[0]))
2330 ++cptr;
2331
2332 // We've gotten to the end of the digits; are we at the end of the string?
2333 if (cptr[0] == '\0')
2334 position = atoi (start);
2335 }
2336 }
2337
2338 return position;
2339}
2340
2341void
2342CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2343{
Jim Ingham16e0c682011-08-12 23:34:31 +00002344 FileSpec init_file;
Greg Clayton14a35512011-09-11 00:01:44 +00002345 if (in_cwd)
Jim Ingham16e0c682011-08-12 23:34:31 +00002346 {
Greg Clayton14a35512011-09-11 00:01:44 +00002347 // In the current working directory we don't load any program specific
2348 // .lldbinit files, we only look for a "./.lldbinit" file.
2349 if (m_skip_lldbinit_files)
2350 return;
2351
2352 init_file.SetFile ("./.lldbinit", true);
Jim Ingham16e0c682011-08-12 23:34:31 +00002353 }
Greg Clayton14a35512011-09-11 00:01:44 +00002354 else
Jim Ingham16e0c682011-08-12 23:34:31 +00002355 {
Greg Clayton14a35512011-09-11 00:01:44 +00002356 // If we aren't looking in the current working directory we are looking
2357 // in the home directory. We will first see if there is an application
2358 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2359 // "-" and the name of the program. If this file doesn't exist, we fall
2360 // back to just the "~/.lldbinit" file. We also obey any requests to not
2361 // load the init files.
2362 const char *init_file_path = "~/.lldbinit";
2363
2364 if (m_skip_app_init_files == false)
2365 {
2366 FileSpec program_file_spec (Host::GetProgramFileSpec());
2367 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham16e0c682011-08-12 23:34:31 +00002368
Greg Clayton14a35512011-09-11 00:01:44 +00002369 if (program_name)
2370 {
2371 char program_init_file_name[PATH_MAX];
2372 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2373 init_file.SetFile (program_init_file_name, true);
2374 if (!init_file.Exists())
2375 init_file.Clear();
2376 }
2377 }
2378
2379 if (!init_file && !m_skip_lldbinit_files)
2380 init_file.SetFile (init_file_path, true);
2381 }
2382
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002383 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2384 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2385
2386 if (init_file.Exists())
2387 {
Jim Inghame16c50a2011-02-18 00:54:25 +00002388 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2389 bool stop_on_continue = true;
2390 bool stop_on_error = false;
2391 bool echo_commands = false;
2392 bool print_results = false;
2393
Enrico Granata5f5ab602012-05-31 01:09:06 +00002394 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002395 }
2396 else
2397 {
2398 // nothing to be done if the file doesn't exist
2399 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2400 }
2401}
2402
Greg Clayton8b82f082011-04-12 05:54:46 +00002403PlatformSP
2404CommandInterpreter::GetPlatform (bool prefer_target_platform)
2405{
2406 PlatformSP platform_sp;
Greg Claytonc14ee322011-09-22 04:58:26 +00002407 if (prefer_target_platform)
2408 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002409 ExecutionContext exe_ctx(GetExecutionContext());
2410 Target *target = exe_ctx.GetTargetPtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002411 if (target)
2412 platform_sp = target->GetPlatform();
2413 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002414
2415 if (!platform_sp)
2416 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2417 return platform_sp;
2418}
2419
Jim Inghame16c50a2011-02-18 00:54:25 +00002420void
Jim Inghambad87fe2011-03-11 01:51:49 +00002421CommandInterpreter::HandleCommands (const StringList &commands,
Jim Inghame16c50a2011-02-18 00:54:25 +00002422 ExecutionContext *override_context,
2423 bool stop_on_continue,
2424 bool stop_on_error,
2425 bool echo_commands,
2426 bool print_results,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002427 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002428 CommandReturnObject &result)
2429{
2430 size_t num_lines = commands.GetSize();
Jim Inghame16c50a2011-02-18 00:54:25 +00002431
2432 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2433 // Make sure you reset this value anywhere you return from the function.
2434
2435 bool old_async_execution = m_debugger.GetAsyncExecution();
2436
2437 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2438 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2439
2440 if (override_context != NULL)
Greg Clayton8b82f082011-04-12 05:54:46 +00002441 UpdateExecutionContext (override_context);
Jim Inghame16c50a2011-02-18 00:54:25 +00002442
2443 if (!stop_on_continue)
2444 {
2445 m_debugger.SetAsyncExecution (false);
2446 }
2447
2448 for (int idx = 0; idx < num_lines; idx++)
2449 {
2450 const char *cmd = commands.GetStringAtIndex(idx);
2451 if (cmd[0] == '\0')
2452 continue;
2453
Jim Inghame16c50a2011-02-18 00:54:25 +00002454 if (echo_commands)
2455 {
2456 result.AppendMessageWithFormat ("%s %s\n",
2457 GetPrompt(),
2458 cmd);
2459 }
2460
Greg Clayton9d0402b2011-02-20 02:15:07 +00002461 CommandReturnObject tmp_result;
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002462 // If override_context is not NULL, pass no_context_switching = true for
2463 // HandleCommand() since we updated our context already.
Enrico Granata5f5ab602012-05-31 01:09:06 +00002464 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002465 NULL, /* override_context */
2466 true, /* repeat_on_empty_command */
2467 override_context != NULL /* no_context_switching */);
Jim Inghame16c50a2011-02-18 00:54:25 +00002468
2469 if (print_results)
2470 {
2471 if (tmp_result.Succeeded())
Jim Ingham85e8b812011-02-19 02:53:09 +00002472 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Inghame16c50a2011-02-18 00:54:25 +00002473 }
2474
2475 if (!success || !tmp_result.Succeeded())
2476 {
Jim Inghama5038812012-04-24 02:25:07 +00002477 const char *error_msg = tmp_result.GetErrorData();
2478 if (error_msg == NULL || error_msg[0] == '\0')
2479 error_msg = "<unknown error>.\n";
Jim Inghame16c50a2011-02-18 00:54:25 +00002480 if (stop_on_error)
2481 {
Jim Inghama5038812012-04-24 02:25:07 +00002482 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2483 idx, cmd, error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002484 result.SetStatus (eReturnStatusFailed);
2485 m_debugger.SetAsyncExecution (old_async_execution);
2486 return;
2487 }
2488 else if (print_results)
2489 {
Jim Inghama5038812012-04-24 02:25:07 +00002490 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Inghame16c50a2011-02-18 00:54:25 +00002491 idx + 1,
2492 cmd,
Jim Inghama5038812012-04-24 02:25:07 +00002493 error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002494 }
2495 }
2496
Caroline Tice969ed3d2011-05-02 20:41:46 +00002497 if (result.GetImmediateOutputStream())
2498 result.GetImmediateOutputStream()->Flush();
2499
2500 if (result.GetImmediateErrorStream())
2501 result.GetImmediateErrorStream()->Flush();
2502
Jim Inghame16c50a2011-02-18 00:54:25 +00002503 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2504 // could be running (for instance in Breakpoint Commands.
2505 // So we check the return value to see if it is has running in it.
2506 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2507 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2508 {
2509 if (stop_on_continue)
2510 {
2511 // If we caused the target to proceed, and we're going to stop in that case, set the
2512 // status in our real result before returning. This is an error if the continue was not the
2513 // last command in the set of commands to be run.
2514 if (idx != num_lines - 1)
2515 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2516 idx + 1, cmd);
2517 else
2518 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2519
2520 result.SetStatus(tmp_result.GetStatus());
2521 m_debugger.SetAsyncExecution (old_async_execution);
2522
2523 return;
2524 }
2525 }
2526
2527 }
2528
2529 result.SetStatus (eReturnStatusSuccessFinishResult);
2530 m_debugger.SetAsyncExecution (old_async_execution);
2531
2532 return;
2533}
2534
2535void
2536CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2537 ExecutionContext *context,
2538 bool stop_on_continue,
2539 bool stop_on_error,
2540 bool echo_command,
2541 bool print_result,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002542 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002543 CommandReturnObject &result)
2544{
2545 if (cmd_file.Exists())
2546 {
2547 bool success;
2548 StringList commands;
2549 success = commands.ReadFileLines(cmd_file);
2550 if (!success)
2551 {
2552 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2553 result.SetStatus (eReturnStatusFailed);
2554 return;
2555 }
Enrico Granata5f5ab602012-05-31 01:09:06 +00002556 m_command_source_depth++;
2557 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2558 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002559 }
2560 else
2561 {
2562 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2563 cmd_file.GetFilename().AsCString());
2564 result.SetStatus (eReturnStatusFailed);
2565 return;
2566 }
2567}
2568
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002569ScriptInterpreter *
Enrico Granatab5887262012-10-29 21:18:03 +00002570CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002571{
Enrico Granatab5887262012-10-29 21:18:03 +00002572 if (m_script_interpreter_ap.get() != NULL)
2573 return m_script_interpreter_ap.get();
2574
2575 if (!can_create)
2576 return NULL;
2577
Enrico Granataa29bdad2012-07-10 18:23:48 +00002578 // <rdar://problem/11751427>
2579 // we need to protect the initialization of the script interpreter
2580 // otherwise we could end up with two threads both trying to create
2581 // their instance of it, and for some languages (e.g. Python)
2582 // this is a bulletproof recipe for disaster!
2583 // this needs to be a function-level static because multiple Debugger instances living in the same process
2584 // still need to be isolated and not try to initialize Python concurrently
Enrico Granata8b95df22012-07-10 19:04:14 +00002585 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2586 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granataa29bdad2012-07-10 18:23:48 +00002587
Enrico Granatab5887262012-10-29 21:18:03 +00002588 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
2589 if (log)
2590 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton66111032010-06-23 01:19:29 +00002591
Caroline Tice2f88aad2011-01-14 00:29:16 +00002592 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2593 switch (script_lang)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002594 {
Greg Claytondce502e2011-11-04 03:34:56 +00002595 case eScriptLanguagePython:
2596#ifndef LLDB_DISABLE_PYTHON
2597 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2598 break;
2599#else
2600 // Fall through to the None case when python is disabled
2601#endif
Caroline Tice2f88aad2011-01-14 00:29:16 +00002602 case eScriptLanguageNone:
2603 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2604 break;
Caroline Tice2f88aad2011-01-14 00:29:16 +00002605 };
2606
2607 return m_script_interpreter_ap.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002608}
2609
2610
2611
2612bool
2613CommandInterpreter::GetSynchronous ()
2614{
2615 return m_synchronous_execution;
2616}
2617
2618void
2619CommandInterpreter::SetSynchronous (bool value)
2620{
Johnny Chenc066ab42010-10-14 01:22:03 +00002621 m_synchronous_execution = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002622}
2623
2624void
2625CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2626 const char *word_text,
2627 const char *separator,
2628 const char *help_text,
2629 uint32_t max_word_len)
2630{
Greg Claytona7015092010-09-18 01:14:36 +00002631 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2632
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002633 int indent_size = max_word_len + strlen (separator) + 2;
2634
2635 strm.IndentMore (indent_size);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002636
2637 StreamString text_strm;
2638 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2639
2640 size_t len = text_strm.GetSize();
2641 const char *text = text_strm.GetData();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002642 if (text[len - 1] == '\n')
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002643 {
2644 text_strm.EOL();
2645 len = text_strm.GetSize();
2646 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002647
2648 if (len < max_columns)
2649 {
2650 // Output it as a single line.
2651 strm.Printf ("%s", text);
2652 }
2653 else
2654 {
2655 // We need to break it up into multiple lines.
2656 bool first_line = true;
2657 int text_width;
2658 int start = 0;
2659 int end = start;
2660 int final_end = strlen (text);
2661 int sub_len;
2662
2663 while (end < final_end)
2664 {
2665 if (first_line)
2666 text_width = max_columns - 1;
2667 else
2668 text_width = max_columns - indent_size - 1;
2669
2670 // Don't start the 'text' on a space, since we're already outputting the indentation.
2671 if (!first_line)
2672 {
2673 while ((start < final_end) && (text[start] == ' '))
2674 start++;
2675 }
2676
2677 end = start + text_width;
2678 if (end > final_end)
2679 end = final_end;
2680 else
2681 {
2682 // If we're not at the end of the text, make sure we break the line on white space.
2683 while (end > start
2684 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2685 end--;
Greg Clayton67cc0632012-08-22 17:17:09 +00002686 assert (end > 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002687 }
2688
2689 sub_len = end - start;
2690 if (start != 0)
2691 strm.EOL();
2692 if (!first_line)
2693 strm.Indent();
2694 else
2695 first_line = false;
2696 assert (start <= final_end);
2697 assert (start + sub_len <= final_end);
2698 if (sub_len > 0)
2699 strm.Write (text + start, sub_len);
2700 start = end + 1;
2701 }
2702 }
2703 strm.EOL();
2704 strm.IndentLess(indent_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002705}
2706
2707void
Enrico Granata82a7d982011-07-07 00:38:40 +00002708CommandInterpreter::OutputHelpText (Stream &strm,
2709 const char *word_text,
2710 const char *separator,
2711 const char *help_text,
2712 uint32_t max_word_len)
2713{
2714 int indent_size = max_word_len + strlen (separator) + 2;
2715
2716 strm.IndentMore (indent_size);
2717
2718 StreamString text_strm;
2719 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2720
2721 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata82a7d982011-07-07 00:38:40 +00002722
2723 size_t len = text_strm.GetSize();
2724 const char *text = text_strm.GetData();
2725
2726 uint32_t chars_left = max_columns;
2727
2728 for (uint32_t i = 0; i < len; i++)
2729 {
2730 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2731 {
Enrico Granata82a7d982011-07-07 00:38:40 +00002732 chars_left = max_columns - indent_size;
2733 strm.EOL();
2734 strm.Indent();
2735 }
2736 else
2737 {
2738 strm.PutChar(text[i]);
2739 chars_left--;
2740 }
2741
2742 }
2743
2744 strm.EOL();
2745 strm.IndentLess(indent_size);
2746}
2747
2748void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002749CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2750 StringList &commands_help)
2751{
2752 CommandObject::CommandMap::const_iterator pos;
2753
2754 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2755 {
2756 const char *command_name = pos->first.c_str();
2757 CommandObject *cmd_obj = pos->second.get();
2758
Greg Claytona7015092010-09-18 01:14:36 +00002759 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002760 {
2761 commands_found.AppendString (command_name);
2762 commands_help.AppendString (cmd_obj->GetHelp());
2763 }
2764
2765 if (cmd_obj->IsMultiwordObject())
Greg Clayton998255b2012-10-13 02:07:45 +00002766 cmd_obj->AproposAllSubCommands (command_name,
2767 search_word,
2768 commands_found,
2769 commands_help);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002770
2771 }
2772}
Greg Clayton8b82f082011-04-12 05:54:46 +00002773
2774
2775void
2776CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2777{
Greg Clayton8b82f082011-04-12 05:54:46 +00002778 if (override_context != NULL)
2779 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002780 m_exe_ctx_ref = *override_context;
Greg Clayton8b82f082011-04-12 05:54:46 +00002781 }
2782 else
2783 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002784 const bool adopt_selected = true;
2785 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Clayton8b82f082011-04-12 05:54:46 +00002786 }
2787}
2788
Jim Inghama5a97eb2011-07-12 03:12:18 +00002789void
2790CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2791{
2792 DumpHistory (stream, 0, count - 1);
2793}
2794
2795void
2796CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2797{
Greg Clayton5521f992011-10-28 21:38:01 +00002798 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2799 for (size_t i = start; i < last_idx; i++)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002800 {
2801 if (!m_command_history[i].empty())
2802 {
2803 stream.Indent();
Greg Clayton5521f992011-10-28 21:38:01 +00002804 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Inghama5a97eb2011-07-12 03:12:18 +00002805 }
2806 }
2807}
2808
2809const char *
2810CommandInterpreter::FindHistoryString (const char *input_str) const
2811{
2812 if (input_str[0] != m_repeat_char)
2813 return NULL;
2814 if (input_str[1] == '-')
2815 {
2816 bool success;
2817 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2818 if (!success)
2819 return NULL;
2820 if (idx > m_command_history.size())
2821 return NULL;
2822 idx = m_command_history.size() - idx;
2823 return m_command_history[idx].c_str();
2824
2825 }
2826 else if (input_str[1] == m_repeat_char)
2827 {
2828 if (m_command_history.empty())
2829 return NULL;
2830 else
2831 return m_command_history.back().c_str();
2832 }
2833 else
2834 {
2835 bool success;
2836 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2837 if (!success)
2838 return NULL;
2839 if (idx >= m_command_history.size())
2840 return NULL;
2841 return m_command_history[idx].c_str();
2842 }
2843}