blob: 9f1c6cc7f504755cff5be10a4c632df35b7e00d9 [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." },
75 { NULL , OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL }
76};
77
78enum
79{
80 ePropertyExpandRegexAliases = 0
81};
82
Jim Ingham4bddaeb2012-02-16 06:50:00 +000083ConstString &
84CommandInterpreter::GetStaticBroadcasterClass ()
85{
86 static ConstString class_name ("lldb.commandInterpreter");
87 return class_name;
88}
89
Chris Lattner30fdc8d2010-06-08 16:52:24 +000090CommandInterpreter::CommandInterpreter
91(
Greg Clayton66111032010-06-23 01:19:29 +000092 Debugger &debugger,
Chris Lattner30fdc8d2010-06-08 16:52:24 +000093 ScriptLanguage script_language,
Greg Clayton66111032010-06-23 01:19:29 +000094 bool synchronous_execution
Chris Lattner30fdc8d2010-06-08 16:52:24 +000095) :
Jim Ingham4bddaeb2012-02-16 06:50:00 +000096 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton754a9362012-08-23 00:22:02 +000097 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton66111032010-06-23 01:19:29 +000098 m_debugger (debugger),
Greg Clayton6eee5aa2010-10-11 01:05:37 +000099 m_synchronous_execution (synchronous_execution),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000100 m_skip_lldbinit_files (false),
Jim Ingham16e0c682011-08-12 23:34:31 +0000101 m_skip_app_init_files (false),
Jim Inghame16c50a2011-02-18 00:54:25 +0000102 m_script_interpreter_ap (),
Caroline Ticed61c10b2011-06-16 16:27:19 +0000103 m_comment_char ('#'),
Jim Inghama5a97eb2011-07-12 03:12:18 +0000104 m_repeat_char ('!'),
Johnny Chen4ac1d9e2012-08-09 22:06:10 +0000105 m_batch_command_mode (false),
Enrico Granata5f5ab602012-05-31 01:09:06 +0000106 m_truncation_warning(eNoTruncation),
107 m_command_source_depth (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000108{
Greg Clayton67cc0632012-08-22 17:17:09 +0000109 debugger.SetScriptLanguage (script_language);
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000110 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
111 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton67cc0632012-08-22 17:17:09 +0000112 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000113 CheckInWithManager ();
Greg Clayton754a9362012-08-23 00:22:02 +0000114 m_collection_sp->Initialize (g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000115}
116
Greg Clayton754a9362012-08-23 00:22:02 +0000117bool
118CommandInterpreter::GetExpandRegexAliases () const
119{
120 const uint32_t idx = ePropertyExpandRegexAliases;
121 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
122}
123
124
125
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000126void
127CommandInterpreter::Initialize ()
128{
129 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
130
131 CommandReturnObject result;
132
133 LoadCommandDictionary ();
134
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000135 // Set up some initial aliases.
Caroline Ticeca90c472011-05-06 21:37:15 +0000136 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
137 if (cmd_obj_sp)
138 {
139 AddAlias ("q", cmd_obj_sp);
140 AddAlias ("exit", cmd_obj_sp);
141 }
Sean Callanan247e62a2012-05-04 23:15:02 +0000142
Johnny Chen6d675242012-08-24 18:15:45 +0000143 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callanan247e62a2012-05-04 23:15:02 +0000144 if (cmd_obj_sp)
145 {
146 AddAlias ("attach", cmd_obj_sp);
147 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000148
Johnny Chen6d675242012-08-24 18:15:45 +0000149 cmd_obj_sp = GetCommandSPExact ("process detach",false);
150 if (cmd_obj_sp)
151 {
152 AddAlias ("detach", cmd_obj_sp);
153 }
154
Caroline Ticeca90c472011-05-06 21:37:15 +0000155 cmd_obj_sp = GetCommandSPExact ("process continue", false);
156 if (cmd_obj_sp)
157 {
158 AddAlias ("c", cmd_obj_sp);
159 AddAlias ("continue", cmd_obj_sp);
160 }
161
162 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
163 if (cmd_obj_sp)
164 AddAlias ("b", cmd_obj_sp);
165
Jim Inghamca36cd12012-10-05 19:16:31 +0000166 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
167 if (cmd_obj_sp)
168 AddAlias ("tbreak", cmd_obj_sp);
169
Caroline Ticeca90c472011-05-06 21:37:15 +0000170 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
171 if (cmd_obj_sp)
Jason Molendaf385f122011-10-22 00:47:41 +0000172 {
173 AddAlias ("stepi", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000174 AddAlias ("si", cmd_obj_sp);
Jason Molendaf385f122011-10-22 00:47:41 +0000175 }
176
177 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
178 if (cmd_obj_sp)
179 {
180 AddAlias ("nexti", cmd_obj_sp);
181 AddAlias ("ni", cmd_obj_sp);
182 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000183
184 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
185 if (cmd_obj_sp)
186 {
187 AddAlias ("s", cmd_obj_sp);
188 AddAlias ("step", cmd_obj_sp);
189 }
190
191 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
192 if (cmd_obj_sp)
193 {
194 AddAlias ("n", cmd_obj_sp);
195 AddAlias ("next", cmd_obj_sp);
196 }
197
198 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
199 if (cmd_obj_sp)
200 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000201 AddAlias ("finish", cmd_obj_sp);
202 }
203
Jim Ingham6d6d1072011-12-02 01:12:59 +0000204 cmd_obj_sp = GetCommandSPExact ("frame select", false);
205 if (cmd_obj_sp)
206 {
207 AddAlias ("f", cmd_obj_sp);
208 }
209
Jim Inghamca36cd12012-10-05 19:16:31 +0000210 cmd_obj_sp = GetCommandSPExact ("thread select", false);
211 if (cmd_obj_sp)
212 {
213 AddAlias ("t", cmd_obj_sp);
214 }
215
Caroline Ticeca90c472011-05-06 21:37:15 +0000216 cmd_obj_sp = GetCommandSPExact ("source list", false);
217 if (cmd_obj_sp)
218 {
219 AddAlias ("l", cmd_obj_sp);
220 AddAlias ("list", cmd_obj_sp);
221 }
222
223 cmd_obj_sp = GetCommandSPExact ("memory read", false);
224 if (cmd_obj_sp)
225 AddAlias ("x", cmd_obj_sp);
226
227 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
228 if (cmd_obj_sp)
229 AddAlias ("up", cmd_obj_sp);
230
231 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
232 if (cmd_obj_sp)
233 AddAlias ("down", cmd_obj_sp);
234
Jason Molenda0c8e0062011-10-25 02:11:20 +0000235 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000236 if (cmd_obj_sp)
237 AddAlias ("display", cmd_obj_sp);
Jim Ingham7e18e422011-10-24 18:37:00 +0000238
239 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
240 if (cmd_obj_sp)
241 AddAlias ("dis", cmd_obj_sp);
242
243 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
244 if (cmd_obj_sp)
245 AddAlias ("di", cmd_obj_sp);
246
247
Jason Molendabc7748b2011-10-22 01:30:52 +0000248
Jason Molenda0c8e0062011-10-25 02:11:20 +0000249 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000250 if (cmd_obj_sp)
251 AddAlias ("undisplay", cmd_obj_sp);
252
Jim Ingham71bf2992012-10-10 16:51:31 +0000253 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
254 if (cmd_obj_sp)
255 AddAlias ("bt", cmd_obj_sp);
256
Caroline Ticeca90c472011-05-06 21:37:15 +0000257 cmd_obj_sp = GetCommandSPExact ("target create", false);
258 if (cmd_obj_sp)
259 AddAlias ("file", cmd_obj_sp);
260
261 cmd_obj_sp = GetCommandSPExact ("target modules", false);
262 if (cmd_obj_sp)
263 AddAlias ("image", cmd_obj_sp);
264
265
266 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghamffba2292011-03-22 02:29:32 +0000267
Caroline Ticeca90c472011-05-06 21:37:15 +0000268 cmd_obj_sp = GetCommandSPExact ("expression", false);
269 if (cmd_obj_sp)
270 {
271 AddAlias ("expr", cmd_obj_sp);
272
273 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
274 AddAlias ("p", cmd_obj_sp);
275 AddAlias ("print", cmd_obj_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000276 AddAlias ("call", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000277 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
278 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000279 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000280
281 alias_arguments_vector_sp.reset (new OptionArgVector);
Enrico Granata7b8c5132012-12-12 03:23:37 +0000282 ProcessAliasOptionsArgs (cmd_obj_sp, "-O --", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000283 AddAlias ("po", cmd_obj_sp);
284 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
285 }
286
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000287 cmd_obj_sp = GetCommandSPExact ("process kill", false);
288 if (cmd_obj_sp)
Greg Claytone86fd742012-09-27 00:02:27 +0000289 {
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000290 AddAlias ("kill", cmd_obj_sp);
Greg Claytone86fd742012-09-27 00:02:27 +0000291 }
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000292
Caroline Ticeca90c472011-05-06 21:37:15 +0000293 cmd_obj_sp = GetCommandSPExact ("process launch", false);
294 if (cmd_obj_sp)
295 {
296 alias_arguments_vector_sp.reset (new OptionArgVector);
Jason Molenda85da3122012-07-06 02:46:23 +0000297#if defined (__arm__)
298 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
299#else
Greg Clayton0ca92a12012-05-18 00:04:38 +0000300 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
Jason Molenda85da3122012-07-06 02:46:23 +0000301#endif
Caroline Ticeca90c472011-05-06 21:37:15 +0000302 AddAlias ("r", cmd_obj_sp);
303 AddAlias ("run", cmd_obj_sp);
304 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
305 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
306 }
Greg Clayton843d62d2012-03-29 21:47:51 +0000307
308 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
309 if (cmd_obj_sp)
310 {
311 AddAlias ("add-dsym", cmd_obj_sp);
312 }
Sean Callananfc732752012-05-21 18:25:19 +0000313
314 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
315 if (cmd_obj_sp)
316 {
317 alias_arguments_vector_sp.reset (new OptionArgVector);
318 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
Jim Ingham06d282d2012-10-18 23:24:12 +0000319 AddAlias ("rbreak", cmd_obj_sp);
320 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
Sean Callananfc732752012-05-21 18:25:19 +0000321 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000322}
323
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000324const char *
325CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
326{
327 // This function has not yet been implemented.
328
329 // Look for any embedded script command
330 // If found,
331 // get interpreter object from the command dictionary,
332 // call execute_one_command on it,
333 // get the results as a string,
334 // substitute that string for current stuff.
335
336 return arg;
337}
338
339
340void
341CommandInterpreter::LoadCommandDictionary ()
342{
343 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
344
345 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
346 //
347 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
348 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
349 // the cross-referencing stuff) are created!!!
350 //
351 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
352
353
354 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
355 // are created. This is so that when another command is created that needs to go into a crossref object,
356 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
357 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
358
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000359 // Non-CommandObjectCrossref commands can now be created.
360
Caroline Ticedaccaa92010-09-20 20:44:43 +0000361 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000362
Greg Claytona7015092010-09-18 01:14:36 +0000363 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000364 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000365 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chenb89982d2011-04-21 00:39:18 +0000366 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000367 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
368 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Clayton7260f622011-04-18 08:33:37 +0000369// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000370 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000371 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytoneffe5c92011-05-03 22:09:39 +0000372 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000373 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
374 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonded470d2011-03-19 01:12:21 +0000375 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata21dfcd92012-09-28 23:57:51 +0000376 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000377 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000378 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000379 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000380 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000381 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Inghamebc09c32010-07-07 03:36:20 +0000382 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000383 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
384 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata223383e2011-08-16 23:24:13 +0000385 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen31c39da2010-12-23 20:21:44 +0000386 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chenf04ee932011-09-22 18:04:58 +0000387 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000388
Jim Inghamca36cd12012-10-05 19:16:31 +0000389 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
390 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
391 {"^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
392 {"^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
393 {"^(-.*)$", "breakpoint set %1"},
394 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
395 {"^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"}};
396
397 size_t num_regexes = sizeof break_regexes/sizeof(char *[2]);
398
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000399 std::auto_ptr<CommandObjectRegexCommand>
Greg Claytona7015092010-09-18 01:14:36 +0000400 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000401 "_regexp-break",
Johnny Chenb417dcd2012-08-23 00:32:22 +0000402 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
403 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Jim Inghamca36cd12012-10-05 19:16:31 +0000404
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000405 if (break_regex_cmd_ap.get())
406 {
Jim Inghamca36cd12012-10-05 19:16:31 +0000407 bool success = true;
408 for (size_t i = 0; i < num_regexes; i++)
409 {
410 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
411 if (!success)
412 break;
413 }
414 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
415
416 if (success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000417 {
418 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
419 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
420 }
421 }
Jim Inghamffba2292011-03-22 02:29:32 +0000422
423 std::auto_ptr<CommandObjectRegexCommand>
Jim Inghamca36cd12012-10-05 19:16:31 +0000424 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
425 "_regexp-tbreak",
426 "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
427 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
428
429 if (tbreak_regex_cmd_ap.get())
430 {
431 bool success = true;
432 for (size_t i = 0; i < num_regexes; i++)
433 {
434 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
435 char buffer[1024];
436 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
437 assert (num_printed < 1024);
438 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
439 if (!success)
440 break;
441 }
442 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
443
444 if (success)
445 {
446 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
447 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
448 }
449 }
450
451 std::auto_ptr<CommandObjectRegexCommand>
Johnny Chen6d675242012-08-24 18:15:45 +0000452 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
453 "_regexp-attach",
454 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.",
455 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]", 2));
456 if (attach_regex_cmd_ap.get())
457 {
Greg Clayton3cb4c7d2012-12-15 01:19:07 +0000458 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
459 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
460 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
461 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
Johnny Chen6d675242012-08-24 18:15:45 +0000462 {
463 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
464 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
465 }
466 }
467
468 std::auto_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000469 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000470 "_regexp-down",
471 "Go down \"n\" frames in the stack (1 frame by default).",
472 "_regexp-down [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000473 if (down_regex_cmd_ap.get())
474 {
475 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
476 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
477 {
478 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
479 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
480 }
481 }
482
483 std::auto_ptr<CommandObjectRegexCommand>
484 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000485 "_regexp-up",
486 "Go up \"n\" frames in the stack (1 frame by default).",
487 "_regexp-up [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000488 if (up_regex_cmd_ap.get())
489 {
490 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
491 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
492 {
493 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
494 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
495 }
496 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000497
498 std::auto_ptr<CommandObjectRegexCommand>
499 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda0c8e0062011-10-25 02:11:20 +0000500 "_regexp-display",
Jason Molendabc7748b2011-10-22 01:30:52 +0000501 "Add an expression evaluation stop-hook.",
Jason Molenda0c8e0062011-10-25 02:11:20 +0000502 "_regexp-display expression", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000503 if (display_regex_cmd_ap.get())
504 {
505 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
506 {
507 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
508 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
509 }
510 }
511
512 std::auto_ptr<CommandObjectRegexCommand>
513 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda0c8e0062011-10-25 02:11:20 +0000514 "_regexp-undisplay",
Jason Molendabc7748b2011-10-22 01:30:52 +0000515 "Remove an expression evaluation stop-hook.",
Jason Molenda0c8e0062011-10-25 02:11:20 +0000516 "_regexp-undisplay stop-hook-number", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000517 if (undisplay_regex_cmd_ap.get())
518 {
519 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
520 {
521 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
522 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
523 }
524 }
525
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000526 std::auto_ptr<CommandObjectRegexCommand>
527 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
528 "gdb-remote",
Jason Molendaa7dcb332012-10-23 03:05:16 +0000529 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
530 "gdb-remote [<hostname>:]<portnum>", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000531 if (connect_gdb_remote_cmd_ap.get())
532 {
533 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
534 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
535 {
536 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
537 m_command_dict[command_sp->GetCommandName ()] = command_sp;
538 }
539 }
540
541 std::auto_ptr<CommandObjectRegexCommand>
542 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
543 "kdp-remote",
Jason Molendaa7dcb332012-10-23 03:05:16 +0000544 "Connect to a remote KDP server. udp port 41139 is the default port number.",
545 "kdp-remote <hostname>[:<portnum>]", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000546 if (connect_kdp_remote_cmd_ap.get())
547 {
548 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molendac36b1842012-09-27 02:47:55 +0000549 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000550 {
551 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
552 m_command_dict[command_sp->GetCommandName ()] = command_sp;
553 }
554 }
555
Jason Molenda4cddfed2012-10-05 05:29:32 +0000556 std::auto_ptr<CommandObjectRegexCommand>
557 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jim Ingham71bf2992012-10-10 16:51:31 +0000558 "_regexp-bt",
Jason Molenda4cddfed2012-10-05 05:29:32 +0000559 "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.",
560 "bt [<digit>|all]", 2));
561 if (bt_regex_cmd_ap.get())
562 {
563 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
564 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
565 // so now "bt 3" is the preferred form, in line with gdb.
566 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
567 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
568 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
569 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
570 {
571 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
572 m_command_dict[command_sp->GetCommandName ()] = command_sp;
573 }
574 }
575
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000576}
577
578int
579CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
580 StringList &matches)
581{
582 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
583
584 if (include_aliases)
585 {
586 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
587 }
588
589 return matches.GetSize();
590}
591
592CommandObjectSP
593CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
594{
595 CommandObject::CommandMap::iterator pos;
596 CommandObjectSP ret_val;
597
598 std::string cmd(cmd_cstr);
599
600 if (HasCommands())
601 {
602 pos = m_command_dict.find(cmd);
603 if (pos != m_command_dict.end())
604 ret_val = pos->second;
605 }
606
607 if (include_aliases && HasAliases())
608 {
609 pos = m_alias_dict.find(cmd);
610 if (pos != m_alias_dict.end())
611 ret_val = pos->second;
612 }
613
614 if (HasUserCommands())
615 {
616 pos = m_user_dict.find(cmd);
617 if (pos != m_user_dict.end())
618 ret_val = pos->second;
619 }
620
Sean Callanan9a028512012-08-09 00:50:26 +0000621 if (!exact && !ret_val)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000622 {
Jim Ingham279a6c22010-07-06 22:46:59 +0000623 // We will only get into here if we didn't find any exact matches.
624
625 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
626
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000627 StringList local_matches;
628 if (matches == NULL)
629 matches = &local_matches;
630
Jim Ingham279a6c22010-07-06 22:46:59 +0000631 unsigned int num_cmd_matches = 0;
632 unsigned int num_alias_matches = 0;
633 unsigned int num_user_matches = 0;
634
635 // Look through the command dictionaries one by one, and if we get only one match from any of
636 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
637
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000638 if (HasCommands())
639 {
640 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
641 }
642
643 if (num_cmd_matches == 1)
644 {
645 cmd.assign(matches->GetStringAtIndex(0));
646 pos = m_command_dict.find(cmd);
647 if (pos != m_command_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000648 real_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000649 }
650
Jim Ingham490ac552010-06-24 20:28:42 +0000651 if (include_aliases && HasAliases())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000652 {
653 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
654
655 }
656
Jim Ingham279a6c22010-07-06 22:46:59 +0000657 if (num_alias_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000658 {
659 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
660 pos = m_alias_dict.find(cmd);
661 if (pos != m_alias_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000662 alias_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000663 }
664
Jim Ingham490ac552010-06-24 20:28:42 +0000665 if (HasUserCommands())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000666 {
667 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
668 }
669
Jim Ingham279a6c22010-07-06 22:46:59 +0000670 if (num_user_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000671 {
672 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
673
674 pos = m_user_dict.find (cmd);
675 if (pos != m_user_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000676 user_match_sp = pos->second;
677 }
678
679 // If we got exactly one match, return that, otherwise return the match list.
680
681 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
682 {
683 if (num_cmd_matches)
684 return real_match_sp;
685 else if (num_alias_matches)
686 return alias_match_sp;
687 else
688 return user_match_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000689 }
690 }
Sean Callanan9a028512012-08-09 00:50:26 +0000691 else if (matches && ret_val)
Jim Ingham279a6c22010-07-06 22:46:59 +0000692 {
693 matches->AppendString (cmd_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000694 }
695
696
697 return ret_val;
698}
699
Greg Claytonde164aa2011-04-20 16:37:46 +0000700bool
701CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
702{
703 if (name && name[0])
704 {
705 std::string name_sstr(name);
Enrico Granatae00af802012-10-01 17:19:37 +0000706 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
707 if (found && !can_replace)
708 return false;
709 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata21dfcd92012-09-28 23:57:51 +0000710 return false;
Greg Claytonde164aa2011-04-20 16:37:46 +0000711 m_command_dict[name_sstr] = cmd_sp;
712 return true;
713 }
714 return false;
715}
716
Enrico Granata223383e2011-08-16 23:24:13 +0000717bool
Enrico Granata0a305db2011-11-07 22:57:04 +0000718CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata223383e2011-08-16 23:24:13 +0000719 const lldb::CommandObjectSP &cmd_sp,
720 bool can_replace)
721{
Enrico Granata0a305db2011-11-07 22:57:04 +0000722 if (!name.empty())
Enrico Granata223383e2011-08-16 23:24:13 +0000723 {
Enrico Granata0a305db2011-11-07 22:57:04 +0000724
725 const char* name_cstr = name.c_str();
726
727 // do not allow replacement of internal commands
728 if (CommandExists(name_cstr))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000729 {
730 if (can_replace == false)
731 return false;
732 if (m_command_dict[name]->IsRemovable() == false)
733 return false;
734 }
Enrico Granata0a305db2011-11-07 22:57:04 +0000735
Enrico Granata21dfcd92012-09-28 23:57:51 +0000736 if (UserCommandExists(name_cstr))
737 {
738 if (can_replace == false)
739 return false;
740 if (m_user_dict[name]->IsRemovable() == false)
741 return false;
742 }
743
Enrico Granata0a305db2011-11-07 22:57:04 +0000744 m_user_dict[name] = cmd_sp;
Enrico Granata223383e2011-08-16 23:24:13 +0000745 return true;
746 }
747 return false;
748}
Greg Claytonde164aa2011-04-20 16:37:46 +0000749
Jim Ingham279a6c22010-07-06 22:46:59 +0000750CommandObjectSP
751CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000752{
Caroline Tice472362e2010-12-14 18:51:39 +0000753 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
754 CommandObjectSP ret_val; // Possibly empty return value.
755
756 if (cmd_cstr == NULL)
757 return ret_val;
758
759 if (cmd_words.GetArgumentCount() == 1)
760 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
761 else
762 {
763 // We have a multi-word command (seemingly), so we need to do more work.
764 // First, get the cmd_obj_sp for the first word in the command.
765 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
766 if (cmd_obj_sp.get() != NULL)
767 {
768 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
769 // command name), and find the appropriate sub-command SP for each command word....
770 size_t end = cmd_words.GetArgumentCount();
771 for (size_t j= 1; j < end; ++j)
772 {
773 if (cmd_obj_sp->IsMultiwordObject())
774 {
Greg Clayton998255b2012-10-13 02:07:45 +0000775 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Caroline Tice472362e2010-12-14 18:51:39 +0000776 if (cmd_obj_sp.get() == NULL)
777 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
778 return ret_val;
779 }
780 else
781 // We have more words in the command name, but we don't have a multiword object. Fail and return
782 // empty 'ret_val'.
783 return ret_val;
784 }
785 // We successfully looped through all the command words and got valid command objects for them. Assign the
786 // last object retrieved to 'ret_val'.
787 ret_val = cmd_obj_sp;
788 }
789 }
790 return ret_val;
Jim Ingham279a6c22010-07-06 22:46:59 +0000791}
792
793CommandObject *
794CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
795{
796 return GetCommandSPExact (cmd_cstr, include_aliases).get();
797}
798
799CommandObject *
800CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
801{
802 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
803
804 // If we didn't find an exact match to the command string in the commands, look in
805 // the aliases.
806
807 if (command_obj == NULL)
808 {
809 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
810 }
811
812 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
813 // in both the commands and the aliases.
814
815 if (command_obj == NULL)
816 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
817
818 return command_obj;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000819}
820
821bool
822CommandInterpreter::CommandExists (const char *cmd)
823{
824 return m_command_dict.find(cmd) != m_command_dict.end();
825}
826
827bool
Caroline Ticeca90c472011-05-06 21:37:15 +0000828CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
829 const char *options_args,
830 OptionArgVectorSP &option_arg_vector_sp)
831{
832 bool success = true;
833 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
834
835 if (!options_args || (strlen (options_args) < 1))
836 return true;
837
838 std::string options_string (options_args);
839 Args args (options_args);
840 CommandReturnObject result;
841 // Check to see if the command being aliased can take any command options.
842 Options *options = cmd_obj_sp->GetOptions ();
843 if (options)
844 {
845 // See if any options were specified as part of the alias; if so, handle them appropriately.
846 options->NotifyOptionParsingStarting ();
847 args.Unshift ("dummy_arg");
848 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
849 args.Shift ();
850 if (result.Succeeded())
851 options->VerifyPartialOptions (result);
852 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
853 {
854 result.AppendError ("Unable to create requested alias.\n");
855 return false;
856 }
857 }
858
Greg Clayton5521f992011-10-28 21:38:01 +0000859 if (!options_string.empty())
Caroline Ticeca90c472011-05-06 21:37:15 +0000860 {
861 if (cmd_obj_sp->WantsRawCommandString ())
862 option_arg_vector->push_back (OptionArgPair ("<argument>",
863 OptionArgValue (-1,
864 options_string)));
865 else
866 {
867 int argc = args.GetArgumentCount();
868 for (size_t i = 0; i < argc; ++i)
869 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
870 option_arg_vector->push_back
871 (OptionArgPair ("<argument>",
872 OptionArgValue (-1,
873 std::string (args.GetArgumentAtIndex (i)))));
874 }
875 }
876
877 return success;
878}
879
880bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000881CommandInterpreter::AliasExists (const char *cmd)
882{
883 return m_alias_dict.find(cmd) != m_alias_dict.end();
884}
885
886bool
887CommandInterpreter::UserCommandExists (const char *cmd)
888{
889 return m_user_dict.find(cmd) != m_user_dict.end();
890}
891
892void
893CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
894{
Jim Ingham279a6c22010-07-06 22:46:59 +0000895 command_obj_sp->SetIsAlias (true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000896 m_alias_dict[alias_name] = command_obj_sp;
897}
898
899bool
900CommandInterpreter::RemoveAlias (const char *alias_name)
901{
902 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
903 if (pos != m_alias_dict.end())
904 {
905 m_alias_dict.erase(pos);
906 return true;
907 }
908 return false;
909}
910bool
911CommandInterpreter::RemoveUser (const char *alias_name)
912{
913 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
914 if (pos != m_user_dict.end())
915 {
916 m_user_dict.erase(pos);
917 return true;
918 }
919 return false;
920}
921
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000922void
923CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
924{
925 help_string.Printf ("'%s", command_name);
926 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
927
Sean Callanan9a028512012-08-09 00:50:26 +0000928 if (option_arg_vector_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000929 {
930 OptionArgVector *options = option_arg_vector_sp.get();
931 for (int i = 0; i < options->size(); ++i)
932 {
933 OptionArgPair cur_option = (*options)[i];
934 std::string opt = cur_option.first;
Caroline Ticed9d63362010-12-07 19:58:26 +0000935 OptionArgValue value_pair = cur_option.second;
936 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000937 if (opt.compare("<argument>") == 0)
938 {
939 help_string.Printf (" %s", value.c_str());
940 }
941 else
942 {
943 help_string.Printf (" %s", opt.c_str());
944 if ((value.compare ("<no-argument>") != 0)
945 && (value.compare ("<need-argument") != 0))
946 {
947 help_string.Printf (" %s", value.c_str());
948 }
949 }
950 }
951 }
952
953 help_string.Printf ("'");
954}
955
Greg Clayton12fc3e02010-08-26 22:05:43 +0000956size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000957CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
958{
959 CommandObject::CommandMap::const_iterator pos;
Greg Clayton12fc3e02010-08-26 22:05:43 +0000960 CommandObject::CommandMap::const_iterator end = dict.end();
961 size_t max_len = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000962
Greg Clayton12fc3e02010-08-26 22:05:43 +0000963 for (pos = dict.begin(); pos != end; ++pos)
964 {
965 size_t len = pos->first.size();
966 if (max_len < len)
967 max_len = len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000968 }
Greg Clayton12fc3e02010-08-26 22:05:43 +0000969 return max_len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000970}
971
972void
Enrico Granata223383e2011-08-16 23:24:13 +0000973CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata08633ee2011-09-09 17:49:36 +0000974 uint32_t cmd_types)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000975{
976 CommandObject::CommandMap::const_iterator pos;
Greg Clayton12fc3e02010-08-26 22:05:43 +0000977 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata223383e2011-08-16 23:24:13 +0000978
979 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000980 {
Enrico Granata223383e2011-08-16 23:24:13 +0000981
982 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
983 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000984
Enrico Granata223383e2011-08-16 23:24:13 +0000985 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
986 {
987 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
988 max_len);
989 }
990 result.AppendMessage("");
991
992 }
993
Greg Clayton5521f992011-10-28 21:38:01 +0000994 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000995 {
Jim Ingham49e80a12010-10-22 18:47:16 +0000996 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chenb89982d2011-04-21 00:39:18 +0000997 "(see 'help command alias' for more info):");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000998 result.AppendMessage("");
Greg Clayton12fc3e02010-08-26 22:05:43 +0000999 max_len = FindLongestCommandWord (m_alias_dict);
1000
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001001 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1002 {
1003 StreamString sstr;
1004 StreamString translation_and_help;
1005 std::string entry_name = pos->first;
1006 std::string second_entry = pos->second.get()->GetCommandName();
1007 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1008
1009 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1010 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1011 translation_and_help.GetData(), max_len);
1012 }
1013 result.AppendMessage("");
1014 }
1015
Greg Clayton5521f992011-10-28 21:38:01 +00001016 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001017 {
1018 result.AppendMessage ("The following is a list of your current user-defined commands:");
1019 result.AppendMessage("");
Enrico Granata223383e2011-08-16 23:24:13 +00001020 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001021 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1022 {
Enrico Granata223383e2011-08-16 23:24:13 +00001023 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1024 max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001025 }
1026 result.AppendMessage("");
1027 }
1028
1029 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1030}
1031
Caroline Tice844d2302010-12-09 22:52:49 +00001032CommandObject *
1033CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001034{
Caroline Tice844d2302010-12-09 22:52:49 +00001035 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1036 // eventually be invoked by the given command line.
1037
1038 CommandObject *cmd_obj = NULL;
1039 std::string white_space (" \t\v");
1040 size_t start = command_string.find_first_not_of (white_space);
1041 size_t end = 0;
1042 bool done = false;
1043 while (!done)
1044 {
1045 if (start != std::string::npos)
1046 {
1047 // Get the next word from command_string.
1048 end = command_string.find_first_of (white_space, start);
1049 if (end == std::string::npos)
1050 end = command_string.size();
1051 std::string cmd_word = command_string.substr (start, end - start);
1052
1053 if (cmd_obj == NULL)
1054 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1055 // command or alias.
1056 cmd_obj = GetCommandObject (cmd_word.c_str());
1057 else if (cmd_obj->IsMultiwordObject ())
1058 {
1059 // 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 +00001060 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001061 if (sub_cmd_obj)
1062 cmd_obj = sub_cmd_obj;
1063 else // cmd_word was not a valid sub-command word, so we are donee
1064 done = true;
1065 }
1066 else
1067 // We have a cmd_obj and it is not a multi-word object, so we are done.
1068 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001069
Caroline Tice844d2302010-12-09 22:52:49 +00001070 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1071 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1072 // next word.
1073
1074 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1075 done = true;
1076 else
1077 start = command_string.find_first_not_of (white_space, end);
1078 }
1079 else
1080 // Unable to find any more words.
1081 done = true;
1082 }
1083
1084 if (end == command_string.size())
1085 command_string.clear();
1086 else
1087 command_string = command_string.substr(end);
1088
1089 return cmd_obj;
1090}
1091
Greg Clayton51964162011-10-25 00:36:27 +00001092static const char *k_white_space = " \t\v";
Greg Clayton5521f992011-10-28 21:38:01 +00001093static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton51964162011-10-25 00:36:27 +00001094static void
1095StripLeadingSpaces (std::string &s)
Caroline Tice844d2302010-12-09 22:52:49 +00001096{
Greg Clayton51964162011-10-25 00:36:27 +00001097 if (!s.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001098 {
Greg Clayton51964162011-10-25 00:36:27 +00001099 size_t pos = s.find_first_not_of (k_white_space);
1100 if (pos == std::string::npos)
1101 s.clear();
1102 else if (pos == 0)
1103 return;
1104 s.erase (0, pos);
1105 }
1106}
1107
Greg Clayton93c62e62011-11-09 23:25:03 +00001108static size_t
1109FindArgumentTerminator (const std::string &s)
1110{
Greg Clayton93c62e62011-11-09 23:25:03 +00001111 const size_t s_len = s.size();
1112 size_t offset = 0;
1113 while (offset < s_len)
1114 {
1115 size_t pos = s.find ("--", offset);
1116 if (pos == std::string::npos)
1117 break;
1118 if (pos > 0)
1119 {
1120 if (isspace(s[pos-1]))
1121 {
1122 // Check if the string ends "\s--" (where \s is a space character)
1123 // or if we have "\s--\s".
1124 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1125 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001126 return pos;
1127 }
1128 }
1129 }
1130 offset = pos + 2;
1131 }
Greg Clayton93c62e62011-11-09 23:25:03 +00001132 return std::string::npos;
1133}
1134
Greg Clayton51964162011-10-25 00:36:27 +00001135static bool
Greg Clayton5521f992011-10-28 21:38:01 +00001136ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton51964162011-10-25 00:36:27 +00001137{
Greg Clayton5521f992011-10-28 21:38:01 +00001138 command.clear();
1139 suffix.clear();
Greg Clayton51964162011-10-25 00:36:27 +00001140 StripLeadingSpaces (command_string);
1141
1142 bool result = false;
1143 quote_char = '\0';
1144
1145 if (!command_string.empty())
1146 {
1147 const char first_char = command_string[0];
1148 if (first_char == '\'' || first_char == '"')
Caroline Tice844d2302010-12-09 22:52:49 +00001149 {
Greg Clayton51964162011-10-25 00:36:27 +00001150 quote_char = first_char;
1151 const size_t end_quote_pos = command_string.find (quote_char, 1);
1152 if (end_quote_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001153 {
Greg Clayton5521f992011-10-28 21:38:01 +00001154 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001155 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001156 }
1157 else
1158 {
Greg Clayton5521f992011-10-28 21:38:01 +00001159 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton51964162011-10-25 00:36:27 +00001160 if (end_quote_pos + 1 < command_string.size())
1161 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1162 else
1163 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001164 }
Caroline Tice844d2302010-12-09 22:52:49 +00001165 }
1166 else
1167 {
Greg Clayton51964162011-10-25 00:36:27 +00001168 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1169 if (first_space_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001170 {
Greg Clayton5521f992011-10-28 21:38:01 +00001171 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001172 command_string.erase();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001173 }
1174 else
1175 {
Greg Clayton5521f992011-10-28 21:38:01 +00001176 command.assign (command_string, 0, first_space_pos);
1177 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice2b5e8502011-05-11 16:07:06 +00001178 }
Caroline Tice844d2302010-12-09 22:52:49 +00001179 }
Greg Clayton51964162011-10-25 00:36:27 +00001180 result = true;
Caroline Tice844d2302010-12-09 22:52:49 +00001181 }
Greg Clayton5521f992011-10-28 21:38:01 +00001182
1183
1184 if (!command.empty())
1185 {
1186 // actual commands can't start with '-' or '_'
1187 if (command[0] != '-' && command[0] != '_')
1188 {
1189 size_t pos = command.find_first_not_of(k_valid_command_chars);
1190 if (pos > 0 && pos != std::string::npos)
1191 {
1192 suffix.assign (command.begin() + pos, command.end());
1193 command.erase (pos);
1194 }
1195 }
1196 }
Greg Clayton51964162011-10-25 00:36:27 +00001197
1198 return result;
Caroline Tice844d2302010-12-09 22:52:49 +00001199}
1200
Greg Clayton5521f992011-10-28 21:38:01 +00001201CommandObject *
1202CommandInterpreter::BuildAliasResult (const char *alias_name,
1203 std::string &raw_input_string,
1204 std::string &alias_result,
1205 CommandReturnObject &result)
Caroline Tice844d2302010-12-09 22:52:49 +00001206{
Greg Clayton5521f992011-10-28 21:38:01 +00001207 CommandObject *alias_cmd_obj = NULL;
Caroline Tice844d2302010-12-09 22:52:49 +00001208 Args cmd_args (raw_input_string.c_str());
1209 alias_cmd_obj = GetCommandObject (alias_name);
1210 StreamString result_str;
1211
1212 if (alias_cmd_obj)
1213 {
1214 std::string alias_name_str = alias_name;
1215 if ((cmd_args.GetArgumentCount() == 0)
1216 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1217 cmd_args.Unshift (alias_name);
1218
1219 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1220 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1221
1222 if (option_arg_vector_sp.get())
1223 {
1224 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1225
1226 for (int i = 0; i < option_arg_vector->size(); ++i)
1227 {
1228 OptionArgPair option_pair = (*option_arg_vector)[i];
1229 OptionArgValue value_pair = option_pair.second;
1230 int value_type = value_pair.first;
1231 std::string option = option_pair.first;
1232 std::string value = value_pair.second;
1233 if (option.compare ("<argument>") == 0)
1234 result_str.Printf (" %s", value.c_str());
1235 else
1236 {
1237 result_str.Printf (" %s", option.c_str());
1238 if (value_type != optional_argument)
1239 result_str.Printf (" ");
1240 if (value.compare ("<no_argument>") != 0)
1241 {
1242 int index = GetOptionArgumentPosition (value.c_str());
1243 if (index == 0)
1244 result_str.Printf ("%s", value.c_str());
1245 else if (index >= cmd_args.GetArgumentCount())
1246 {
1247
1248 result.AppendErrorWithFormat
1249 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1250 index);
1251 result.SetStatus (eReturnStatusFailed);
Greg Clayton5521f992011-10-28 21:38:01 +00001252 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001253 }
1254 else
1255 {
1256 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1257 if (strpos != std::string::npos)
1258 raw_input_string = raw_input_string.erase (strpos,
1259 strlen (cmd_args.GetArgumentAtIndex (index)));
1260 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1261 }
1262 }
1263 }
1264 }
1265 }
1266
1267 alias_result = result_str.GetData();
1268 }
Greg Clayton5521f992011-10-28 21:38:01 +00001269 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001270}
1271
Greg Clayton5a314712011-10-14 07:41:33 +00001272Error
1273CommandInterpreter::PreprocessCommand (std::string &command)
1274{
1275 // The command preprocessor needs to do things to the command
1276 // line before any parsing of arguments or anything else is done.
1277 // The only current stuff that gets proprocessed is anyting enclosed
1278 // in backtick ('`') characters is evaluated as an expression and
1279 // the result of the expression must be a scalar that can be substituted
1280 // into the command. An example would be:
1281 // (lldb) memory read `$rsp + 20`
1282 Error error; // Error for any expressions that might not evaluate
1283 size_t start_backtick;
1284 size_t pos = 0;
1285 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1286 {
1287 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1288 {
1289 // The backtick was preceeded by a '\' character, remove the slash
1290 // and don't treat the backtick as the start of an expression
1291 command.erase(start_backtick-1, 1);
1292 // No need to add one to start_backtick since we just deleted a char
1293 pos = start_backtick;
1294 }
1295 else
1296 {
1297 const size_t expr_content_start = start_backtick + 1;
1298 const size_t end_backtick = command.find ('`', expr_content_start);
1299 if (end_backtick == std::string::npos)
1300 return error;
1301 else if (end_backtick == expr_content_start)
1302 {
1303 // Empty expression (two backticks in a row)
1304 command.erase (start_backtick, 2);
1305 }
1306 else
1307 {
1308 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1309
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00001310 ExecutionContext exe_ctx(GetExecutionContext());
1311 Target *target = exe_ctx.GetTargetPtr();
Johnny Chen51ea0ad2011-10-29 00:21:50 +00001312 // Get a dummy target to allow for calculator mode while processing backticks.
1313 // This also helps break the infinite loop caused when target is null.
1314 if (!target)
1315 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Clayton5a314712011-10-14 07:41:33 +00001316 if (target)
1317 {
Greg Clayton5a314712011-10-14 07:41:33 +00001318 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001319
Jim Ingham35e1bda2012-10-16 21:41:58 +00001320 EvaluateExpressionOptions options;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001321 options.SetCoerceToId(false)
1322 .SetUnwindOnError(true)
1323 .SetKeepInMemory(false)
Jim Ingham35e1bda2012-10-16 21:41:58 +00001324 .SetRunOthers(true)
1325 .SetTimeoutUsec(0);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001326
Greg Clayton5a314712011-10-14 07:41:33 +00001327 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad4439aa2012-09-05 20:41:26 +00001328 exe_ctx.GetFramePtr(),
Enrico Granata3372f582012-07-16 23:10:35 +00001329 expr_result_valobj_sp,
Enrico Granatad4439aa2012-09-05 20:41:26 +00001330 options);
1331
Greg Clayton5a314712011-10-14 07:41:33 +00001332 if (expr_result == eExecutionCompleted)
1333 {
1334 Scalar scalar;
1335 if (expr_result_valobj_sp->ResolveValue (scalar))
1336 {
1337 command.erase (start_backtick, end_backtick - start_backtick + 1);
1338 StreamString value_strm;
1339 const bool show_type = false;
1340 scalar.GetValue (&value_strm, show_type);
1341 size_t value_string_size = value_strm.GetSize();
1342 if (value_string_size)
1343 {
1344 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1345 pos = start_backtick + value_string_size;
1346 continue;
1347 }
1348 else
1349 {
1350 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1351 }
1352 }
1353 else
1354 {
1355 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1356 }
1357 }
1358 else
1359 {
1360 if (expr_result_valobj_sp)
1361 error = expr_result_valobj_sp->GetError();
1362 if (error.Success())
1363 {
1364
1365 switch (expr_result)
1366 {
1367 case eExecutionSetupError:
1368 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1369 break;
1370 case eExecutionCompleted:
1371 break;
1372 case eExecutionDiscarded:
1373 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1374 break;
1375 case eExecutionInterrupted:
1376 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1377 break;
1378 case eExecutionTimedOut:
1379 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1380 break;
1381 }
1382 }
1383 }
1384 }
1385 }
1386 if (error.Fail())
1387 break;
1388 }
1389 }
1390 return error;
1391}
1392
1393
Caroline Tice844d2302010-12-09 22:52:49 +00001394bool
1395CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata5f5ab602012-05-31 01:09:06 +00001396 LazyBool lazy_add_to_history,
Caroline Tice844d2302010-12-09 22:52:49 +00001397 CommandReturnObject &result,
Jim Inghame16c50a2011-02-18 00:54:25 +00001398 ExecutionContext *override_context,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001399 bool repeat_on_empty_command,
1400 bool no_context_switching)
Jim Inghame16c50a2011-02-18 00:54:25 +00001401
Caroline Tice844d2302010-12-09 22:52:49 +00001402{
Jim Inghame16c50a2011-02-18 00:54:25 +00001403
Caroline Tice844d2302010-12-09 22:52:49 +00001404 bool done = false;
1405 CommandObject *cmd_obj = NULL;
Caroline Tice844d2302010-12-09 22:52:49 +00001406 bool wants_raw_input = false;
1407 std::string command_string (command_line);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001408 std::string original_command_string (command_line);
Caroline Tice844d2302010-12-09 22:52:49 +00001409
1410 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001411 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1412
1413 // Make a scoped cleanup object that will clear the crash description string
1414 // on exit of this function.
Enrico Granataf9fa6ee2011-07-12 00:18:11 +00001415 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001416
Caroline Tice844d2302010-12-09 22:52:49 +00001417 if (log)
1418 log->Printf ("Processing command: %s", command_line);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001419
Jim Ingham30244832010-11-04 23:08:45 +00001420 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1421
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001422 if (!no_context_switching)
1423 UpdateExecutionContext (override_context);
Enrico Granata5f5ab602012-05-31 01:09:06 +00001424
1425 // <rdar://problem/11328896>
1426 bool add_to_history;
1427 if (lazy_add_to_history == eLazyBoolCalculate)
1428 add_to_history = (m_command_source_depth == 0);
1429 else
1430 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1431
Jim Inghame16c50a2011-02-18 00:54:25 +00001432 bool empty_command = false;
1433 bool comment_command = false;
1434 if (command_string.empty())
1435 empty_command = true;
1436 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001437 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001438 const char *k_space_characters = "\t\n\v\f\r ";
1439
1440 size_t non_space = command_string.find_first_not_of (k_space_characters);
1441 // Check for empty line or comment line (lines whose first
1442 // non-space character is the comment character for this interpreter)
1443 if (non_space == std::string::npos)
1444 empty_command = true;
1445 else if (command_string[non_space] == m_comment_char)
1446 comment_command = true;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001447 else if (command_string[non_space] == m_repeat_char)
1448 {
1449 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1450 if (history_string == NULL)
1451 {
1452 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1453 result.SetStatus(eReturnStatusFailed);
1454 return false;
1455 }
1456 add_to_history = false;
1457 command_string = history_string;
1458 original_command_string = history_string;
1459 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001460 }
1461
1462 if (empty_command)
1463 {
1464 if (repeat_on_empty_command)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001465 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001466 if (m_command_history.empty())
1467 {
1468 result.AppendError ("empty command");
1469 result.SetStatus(eReturnStatusFailed);
1470 return false;
1471 }
1472 else
1473 {
1474 command_line = m_repeat_command.c_str();
1475 command_string = command_line;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001476 original_command_string = command_line;
Jim Inghame16c50a2011-02-18 00:54:25 +00001477 if (m_repeat_command.empty())
1478 {
1479 result.AppendErrorWithFormat("No auto repeat.\n");
1480 result.SetStatus (eReturnStatusFailed);
1481 return false;
1482 }
1483 }
1484 add_to_history = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001485 }
1486 else
1487 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001488 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1489 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001490 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001491 }
1492 else if (comment_command)
1493 {
1494 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1495 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001496 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001497
Greg Clayton5a314712011-10-14 07:41:33 +00001498
1499 Error error (PreprocessCommand (command_string));
1500
1501 if (error.Fail())
1502 {
1503 result.AppendError (error.AsCString());
1504 result.SetStatus(eReturnStatusFailed);
1505 return false;
1506 }
Caroline Tice844d2302010-12-09 22:52:49 +00001507 // Phase 1.
1508
1509 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1510 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1511 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1512 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1513 // 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 +00001514 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Tice844d2302010-12-09 22:52:49 +00001515 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Ticed9d63362010-12-07 19:58:26 +00001516
Caroline Tice844d2302010-12-09 22:52:49 +00001517 StreamString revised_command_line;
Caroline Tice01274c02010-12-11 08:16:56 +00001518 size_t actual_cmd_name_len = 0;
Greg Clayton5521f992011-10-28 21:38:01 +00001519 std::string next_word;
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001520 StringList matches;
Caroline Tice844d2302010-12-09 22:52:49 +00001521 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001522 {
Caroline Tice2b5e8502011-05-11 16:07:06 +00001523 char quote_char = '\0';
Greg Clayton5521f992011-10-28 21:38:01 +00001524 std::string suffix;
1525 ExtractCommand (command_string, next_word, suffix, quote_char);
1526 if (cmd_obj == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001527 {
Greg Clayton5521f992011-10-28 21:38:01 +00001528 if (AliasExists (next_word.c_str()))
Caroline Tice472362e2010-12-14 18:51:39 +00001529 {
Greg Clayton5521f992011-10-28 21:38:01 +00001530 std::string alias_result;
1531 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1532 revised_command_line.Printf ("%s", alias_result.c_str());
1533 if (cmd_obj)
1534 {
1535 wants_raw_input = cmd_obj->WantsRawCommandString ();
1536 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1537 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001538 }
1539 else
1540 {
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001541 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton5521f992011-10-28 21:38:01 +00001542 if (cmd_obj)
1543 {
1544 actual_cmd_name_len += next_word.length();
1545 revised_command_line.Printf ("%s", next_word.c_str());
1546 wants_raw_input = cmd_obj->WantsRawCommandString ();
1547 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001548 else
Greg Clayton5521f992011-10-28 21:38:01 +00001549 {
1550 revised_command_line.Printf ("%s", next_word.c_str());
1551 }
Caroline Tice844d2302010-12-09 22:52:49 +00001552 }
1553 }
1554 else
1555 {
Greg Clayton5521f992011-10-28 21:38:01 +00001556 if (cmd_obj->IsMultiwordObject ())
1557 {
Greg Clayton998255b2012-10-13 02:07:45 +00001558 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
Greg Clayton5521f992011-10-28 21:38:01 +00001559 if (sub_cmd_obj)
1560 {
1561 actual_cmd_name_len += next_word.length() + 1;
1562 revised_command_line.Printf (" %s", next_word.c_str());
1563 cmd_obj = sub_cmd_obj;
1564 wants_raw_input = cmd_obj->WantsRawCommandString ();
1565 }
1566 else
1567 {
1568 if (quote_char)
1569 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1570 else
1571 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1572 done = true;
1573 }
1574 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001575 else
Greg Clayton5521f992011-10-28 21:38:01 +00001576 {
1577 if (quote_char)
1578 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1579 else
1580 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1581 done = true;
1582 }
Caroline Tice844d2302010-12-09 22:52:49 +00001583 }
1584
1585 if (cmd_obj == NULL)
1586 {
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001587 uint32_t num_matches = matches.GetSize();
1588 if (matches.GetSize() > 1) {
1589 std::string error_msg;
1590 error_msg.assign ("Ambiguous command '");
1591 error_msg.append(next_word.c_str());
1592 error_msg.append ("'.");
1593
1594 error_msg.append (" Possible matches:");
1595
1596 for (uint32_t i = 0; i < num_matches; ++i) {
1597 error_msg.append ("\n\t");
1598 error_msg.append (matches.GetStringAtIndex(i));
1599 }
1600 error_msg.append ("\n");
1601 result.AppendRawError (error_msg.c_str(), error_msg.size());
1602 } else {
1603 // We didn't have only one match, otherwise we wouldn't get here.
1604 assert(num_matches == 0);
1605 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1606 }
Caroline Tice844d2302010-12-09 22:52:49 +00001607 result.SetStatus (eReturnStatusFailed);
1608 return false;
1609 }
1610
Greg Clayton5521f992011-10-28 21:38:01 +00001611 if (cmd_obj->IsMultiwordObject ())
1612 {
1613 if (!suffix.empty())
1614 {
1615
1616 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1617 next_word.c_str(),
1618 suffix.c_str());
1619 result.SetStatus (eReturnStatusFailed);
1620 return false;
1621 }
1622 }
1623 else
1624 {
1625 // If we found a normal command, we are done
1626 done = true;
1627 if (!suffix.empty())
1628 {
1629 switch (suffix[0])
1630 {
1631 case '/':
1632 // GDB format suffixes
Greg Clayton52ec56c2011-10-29 00:57:28 +00001633 {
1634 Options *command_options = cmd_obj->GetOptions();
1635 if (command_options && command_options->SupportsLongOption("gdb-format"))
1636 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001637 std::string gdb_format_option ("--gdb-format=");
1638 gdb_format_option += (suffix.c_str() + 1);
1639
1640 bool inserted = false;
1641 std::string &cmd = revised_command_line.GetString();
1642 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1643 if (arg_terminator_idx != std::string::npos)
1644 {
1645 // Insert the gdb format option before the "--" that terminates options
1646 gdb_format_option.append(1,' ');
1647 cmd.insert(arg_terminator_idx, gdb_format_option);
1648 inserted = true;
1649 }
1650
1651 if (!inserted)
1652 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1653
1654 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1655 revised_command_line.PutCString (" --");
Greg Clayton52ec56c2011-10-29 00:57:28 +00001656 }
1657 else
1658 {
1659 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1660 cmd_obj->GetCommandName());
1661 result.SetStatus (eReturnStatusFailed);
1662 return false;
1663 }
1664 }
Greg Clayton5521f992011-10-28 21:38:01 +00001665 break;
Johnny Chen8e9383d2011-10-31 22:22:06 +00001666
1667 default:
1668 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1669 suffix.c_str());
1670 result.SetStatus (eReturnStatusFailed);
1671 return false;
1672
Greg Clayton5521f992011-10-28 21:38:01 +00001673 }
1674 }
1675 }
Caroline Tice844d2302010-12-09 22:52:49 +00001676 if (command_string.length() == 0)
1677 done = true;
1678
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001679 }
Caroline Tice844d2302010-12-09 22:52:49 +00001680
Greg Clayton5521f992011-10-28 21:38:01 +00001681 if (!command_string.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001682 revised_command_line.Printf (" %s", command_string.c_str());
1683
1684 // End of Phase 1.
1685 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1686 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1687 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1688 // wants_raw_input specifies whether the Execute method expects raw input or not.
1689
1690
1691 if (log)
1692 {
1693 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1694 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1695 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1696 }
1697
1698 // Phase 2.
1699 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1700 // CommandObject, with the appropriate arguments.
1701
1702 if (cmd_obj != NULL)
1703 {
1704 if (add_to_history)
1705 {
1706 Args command_args (revised_command_line.GetData());
1707 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1708 if (repeat_command != NULL)
1709 m_repeat_command.assign(repeat_command);
1710 else
Jim Inghama5a97eb2011-07-12 03:12:18 +00001711 m_repeat_command.assign(original_command_string.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001712
Jim Inghama5a97eb2011-07-12 03:12:18 +00001713 // Don't keep pushing the same command onto the history...
Greg Clayton5521f992011-10-28 21:38:01 +00001714 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001715 m_command_history.push_back (original_command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001716 }
1717
1718 command_string = revised_command_line.GetData();
1719 std::string command_name (cmd_obj->GetCommandName());
Caroline Tice01274c02010-12-11 08:16:56 +00001720 std::string remainder;
1721 if (actual_cmd_name_len < command_string.length())
1722 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1723 // than cmd_obj->GetCommandName(), because name completion
1724 // allows users to enter short versions of the names,
1725 // e.g. 'br s' for 'breakpoint set'.
Caroline Tice844d2302010-12-09 22:52:49 +00001726
1727 // Remove any initial spaces
1728 std::string white_space (" \t\v");
1729 size_t pos = remainder.find_first_not_of (white_space);
1730 if (pos != 0 && pos != std::string::npos)
Greg Claytona3482592011-04-22 20:58:45 +00001731 remainder.erase(0, pos);
Caroline Tice844d2302010-12-09 22:52:49 +00001732
1733 if (log)
Jason Molendabfb36ff2011-08-25 00:20:04 +00001734 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001735
Jim Ingham5a988412012-06-08 21:56:10 +00001736 cmd_obj->Execute (remainder.c_str(), result);
Caroline Tice844d2302010-12-09 22:52:49 +00001737 }
1738 else
1739 {
1740 // We didn't find the first command object, so complete the first argument.
1741 Args command_args (revised_command_line.GetData());
1742 StringList matches;
1743 int num_matches;
1744 int cursor_index = 0;
1745 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1746 bool word_complete;
1747 num_matches = HandleCompletionMatches (command_args,
1748 cursor_index,
1749 cursor_char_position,
1750 0,
1751 -1,
1752 word_complete,
1753 matches);
1754
1755 if (num_matches > 0)
1756 {
1757 std::string error_msg;
1758 error_msg.assign ("ambiguous command '");
1759 error_msg.append(command_args.GetArgumentAtIndex(0));
1760 error_msg.append ("'.");
1761
1762 error_msg.append (" Possible completions:");
1763 for (int i = 0; i < num_matches; i++)
1764 {
1765 error_msg.append ("\n\t");
1766 error_msg.append (matches.GetStringAtIndex (i));
1767 }
1768 error_msg.append ("\n");
1769 result.AppendRawError (error_msg.c_str(), error_msg.size());
1770 }
1771 else
1772 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1773
1774 result.SetStatus (eReturnStatusFailed);
1775 }
1776
Jason Molendabfb36ff2011-08-25 00:20:04 +00001777 if (log)
1778 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1779
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001780 return result.Succeeded();
1781}
1782
1783int
1784CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1785 int &cursor_index,
1786 int &cursor_char_position,
1787 int match_start_point,
1788 int max_return_elements,
Jim Ingham558ce122010-06-30 05:02:46 +00001789 bool &word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001790 StringList &matches)
1791{
1792 int num_command_matches = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001793 bool look_for_subcommand = false;
Jim Ingham558ce122010-06-30 05:02:46 +00001794
1795 // For any of the command completions a unique match will be a complete word.
1796 word_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001797
1798 if (cursor_index == -1)
1799 {
1800 // We got nothing on the command line, so return the list of commands
Jim Ingham279a6c22010-07-06 22:46:59 +00001801 bool include_aliases = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001802 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1803 }
1804 else if (cursor_index == 0)
1805 {
1806 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Ingham279a6c22010-07-06 22:46:59 +00001807 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001808 num_command_matches = matches.GetSize();
1809
1810 if (num_command_matches == 1
1811 && cmd_obj && cmd_obj->IsMultiwordObject()
1812 && matches.GetStringAtIndex(0) != NULL
1813 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1814 {
1815 look_for_subcommand = true;
1816 num_command_matches = 0;
1817 matches.DeleteStringAtIndex(0);
1818 parsed_line.AppendArgument ("");
1819 cursor_index++;
1820 cursor_char_position = 0;
1821 }
1822 }
1823
1824 if (cursor_index > 0 || look_for_subcommand)
1825 {
1826 // We are completing further on into a commands arguments, so find the command and tell it
1827 // to complete the command.
1828 // First see if there is a matching initial command:
Jim Ingham279a6c22010-07-06 22:46:59 +00001829 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001830 if (command_object == NULL)
1831 {
1832 return 0;
1833 }
1834 else
1835 {
1836 parsed_line.Shift();
1837 cursor_index--;
Greg Claytona7015092010-09-18 01:14:36 +00001838 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton66111032010-06-23 01:19:29 +00001839 cursor_index,
1840 cursor_char_position,
1841 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001842 max_return_elements,
1843 word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001844 matches);
1845 }
1846 }
1847
1848 return num_command_matches;
1849
1850}
1851
1852int
1853CommandInterpreter::HandleCompletion (const char *current_line,
1854 const char *cursor,
1855 const char *last_char,
1856 int match_start_point,
1857 int max_return_elements,
1858 StringList &matches)
1859{
1860 // We parse the argument up to the cursor, so the last argument in parsed_line is
1861 // the one containing the cursor, and the cursor is after the last character.
1862
1863 Args parsed_line(current_line, last_char - current_line);
1864 Args partial_parsed_line(current_line, cursor - current_line);
1865
Jim Inghama5a97eb2011-07-12 03:12:18 +00001866 // Don't complete comments, and if the line we are completing is just the history repeat character,
1867 // substitute the appropriate history line.
1868 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1869 if (first_arg)
1870 {
1871 if (first_arg[0] == m_comment_char)
1872 return 0;
1873 else if (first_arg[0] == m_repeat_char)
1874 {
1875 const char *history_string = FindHistoryString (first_arg);
1876 if (history_string != NULL)
1877 {
1878 matches.Clear();
1879 matches.InsertStringAtIndex(0, history_string);
1880 return -2;
1881 }
1882 else
1883 return 0;
1884
1885 }
1886 }
1887
1888
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001889 int num_args = partial_parsed_line.GetArgumentCount();
1890 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1891 int cursor_char_position;
1892
1893 if (cursor_index == -1)
1894 cursor_char_position = 0;
1895 else
1896 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamfe0c4252010-12-14 19:56:01 +00001897
1898 if (cursor > current_line && cursor[-1] == ' ')
1899 {
1900 // We are just after a space. If we are in an argument, then we will continue
1901 // parsing, but if we are between arguments, then we have to complete whatever the next
1902 // element would be.
1903 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1904 // protected by a quote) then the space will also be in the parsed argument...
1905
1906 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1907 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1908 {
1909 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1910 cursor_index++;
1911 cursor_char_position = 0;
1912 }
1913 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001914
1915 int num_command_matches;
1916
1917 matches.Clear();
1918
1919 // Only max_return_elements == -1 is supported at present:
1920 assert (max_return_elements == -1);
Jim Ingham558ce122010-06-30 05:02:46 +00001921 bool word_complete;
Greg Clayton66111032010-06-23 01:19:29 +00001922 num_command_matches = HandleCompletionMatches (parsed_line,
1923 cursor_index,
1924 cursor_char_position,
1925 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001926 max_return_elements,
1927 word_complete,
Greg Clayton66111032010-06-23 01:19:29 +00001928 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001929
1930 if (num_command_matches <= 0)
1931 return num_command_matches;
1932
1933 if (num_args == 0)
1934 {
1935 // If we got an empty string, insert nothing.
1936 matches.InsertStringAtIndex(0, "");
1937 }
1938 else
1939 {
1940 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1941 // put an empty string in element 0.
1942 std::string command_partial_str;
1943 if (cursor_index >= 0)
Jim Ingham49e80a12010-10-22 18:47:16 +00001944 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1945 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001946
1947 std::string common_prefix;
1948 matches.LongestCommonPrefix (common_prefix);
1949 int partial_name_len = command_partial_str.size();
1950
1951 // If we matched a unique single command, add a space...
Jim Ingham558ce122010-06-30 05:02:46 +00001952 // Only do this if the completer told us this was a complete word, however...
1953 if (num_command_matches == 1 && word_complete)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001954 {
1955 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1956 if (quote_char != '\0')
1957 common_prefix.push_back(quote_char);
1958
1959 common_prefix.push_back(' ');
1960 }
1961 common_prefix.erase (0, partial_name_len);
1962 matches.InsertStringAtIndex(0, common_prefix.c_str());
1963 }
1964 return num_command_matches;
1965}
1966
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001967
1968CommandInterpreter::~CommandInterpreter ()
1969{
1970}
1971
1972const char *
1973CommandInterpreter::GetPrompt ()
1974{
Caroline Ticedaccaa92010-09-20 20:44:43 +00001975 return m_debugger.GetPrompt();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001976}
1977
1978void
1979CommandInterpreter::SetPrompt (const char *new_prompt)
1980{
Caroline Ticedaccaa92010-09-20 20:44:43 +00001981 m_debugger.SetPrompt (new_prompt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001982}
1983
Jim Ingham97a6dc72010-10-04 19:49:29 +00001984size_t
Greg Clayton51b1e2d2011-02-09 01:08:52 +00001985CommandInterpreter::GetConfirmationInputReaderCallback
1986(
1987 void *baton,
1988 InputReader &reader,
1989 lldb::InputReaderAction action,
1990 const char *bytes,
1991 size_t bytes_len
1992)
Jim Ingham97a6dc72010-10-04 19:49:29 +00001993{
Greg Clayton51b1e2d2011-02-09 01:08:52 +00001994 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham97a6dc72010-10-04 19:49:29 +00001995 bool *response_ptr = (bool *) baton;
1996
1997 switch (action)
1998 {
1999 case eInputReaderActivate:
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002000 if (out_file.IsValid())
Jim Ingham97a6dc72010-10-04 19:49:29 +00002001 {
2002 if (reader.GetPrompt())
Caroline Tice31f7d462011-02-02 01:17:56 +00002003 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002004 out_file.Printf ("%s", reader.GetPrompt());
2005 out_file.Flush ();
Caroline Tice31f7d462011-02-02 01:17:56 +00002006 }
Jim Ingham97a6dc72010-10-04 19:49:29 +00002007 }
2008 break;
2009
2010 case eInputReaderDeactivate:
2011 break;
2012
2013 case eInputReaderReactivate:
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002014 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice31f7d462011-02-02 01:17:56 +00002015 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002016 out_file.Printf ("%s", reader.GetPrompt());
2017 out_file.Flush ();
Caroline Tice31f7d462011-02-02 01:17:56 +00002018 }
Jim Ingham97a6dc72010-10-04 19:49:29 +00002019 break;
Caroline Tice969ed3d2011-05-02 20:41:46 +00002020
2021 case eInputReaderAsynchronousOutputWritten:
2022 break;
2023
Jim Ingham97a6dc72010-10-04 19:49:29 +00002024 case eInputReaderGotToken:
2025 if (bytes_len == 0)
2026 {
2027 reader.SetIsDone(true);
2028 }
Jim Inghamc8b47582011-11-14 20:02:01 +00002029 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham97a6dc72010-10-04 19:49:29 +00002030 {
2031 *response_ptr = true;
2032 reader.SetIsDone(true);
2033 }
Jim Inghamc8b47582011-11-14 20:02:01 +00002034 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham97a6dc72010-10-04 19:49:29 +00002035 {
2036 *response_ptr = false;
2037 reader.SetIsDone(true);
2038 }
2039 else
2040 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002041 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham97a6dc72010-10-04 19:49:29 +00002042 {
Jim Ingham78d61482011-11-17 01:22:00 +00002043 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002044 out_file.Flush ();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002045 }
2046 }
2047 break;
2048
Caroline Ticeefed6132010-11-19 20:47:54 +00002049 case eInputReaderInterrupt:
2050 case eInputReaderEndOfFile:
2051 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
2052 reader.SetIsDone (true);
2053 break;
2054
Jim Ingham97a6dc72010-10-04 19:49:29 +00002055 case eInputReaderDone:
2056 break;
2057 }
2058
2059 return bytes_len;
2060
2061}
2062
2063bool
2064CommandInterpreter::Confirm (const char *message, bool default_answer)
2065{
Jim Ingham3bcdb292010-10-04 22:44:14 +00002066 // Check AutoConfirm first:
2067 if (m_debugger.GetAutoConfirm())
2068 return default_answer;
2069
Jim Ingham97a6dc72010-10-04 19:49:29 +00002070 InputReaderSP reader_sp (new InputReader(GetDebugger()));
2071 bool response = default_answer;
2072 if (reader_sp)
2073 {
2074 std::string prompt(message);
2075 prompt.append(": [");
2076 if (default_answer)
2077 prompt.append ("Y/n] ");
2078 else
2079 prompt.append ("y/N] ");
2080
2081 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
2082 &response, // baton
2083 eInputReaderGranularityLine, // token size, to pass to callback function
2084 NULL, // end token
2085 prompt.c_str(), // prompt
2086 true)); // echo input
2087 if (err.Success())
2088 {
2089 GetDebugger().PushInputReader (reader_sp);
2090 }
2091 reader_sp->WaitOnReaderIsDone();
2092 }
2093 return response;
2094}
2095
2096
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002097void
2098CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
2099{
Jim Ingham279a6c22010-07-06 22:46:59 +00002100 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002101
Sean Callanan9a028512012-08-09 00:50:26 +00002102 if (cmd_obj_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002103 {
2104 CommandObject *cmd_obj = cmd_obj_sp.get();
2105 if (cmd_obj->IsCrossRefObject ())
2106 cmd_obj->AddObject (object_type);
2107 }
2108}
2109
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002110OptionArgVectorSP
2111CommandInterpreter::GetAliasOptions (const char *alias_name)
2112{
2113 OptionArgMap::iterator pos;
2114 OptionArgVectorSP ret_val;
2115
2116 std::string alias (alias_name);
2117
2118 if (HasAliasOptions())
2119 {
2120 pos = m_alias_options.find (alias);
2121 if (pos != m_alias_options.end())
2122 ret_val = pos->second;
2123 }
2124
2125 return ret_val;
2126}
2127
2128void
2129CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2130{
2131 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2132 if (pos != m_alias_options.end())
2133 {
2134 m_alias_options.erase (pos);
2135 }
2136}
2137
2138void
2139CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2140{
2141 m_alias_options[alias_name] = option_arg_vector_sp;
2142}
2143
2144bool
2145CommandInterpreter::HasCommands ()
2146{
2147 return (!m_command_dict.empty());
2148}
2149
2150bool
2151CommandInterpreter::HasAliases ()
2152{
2153 return (!m_alias_dict.empty());
2154}
2155
2156bool
2157CommandInterpreter::HasUserCommands ()
2158{
2159 return (!m_user_dict.empty());
2160}
2161
2162bool
2163CommandInterpreter::HasAliasOptions ()
2164{
2165 return (!m_alias_options.empty());
2166}
2167
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002168void
Caroline Tice4ab31c92010-10-12 21:57:09 +00002169CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2170 const char *alias_name,
2171 Args &cmd_args,
Caroline Ticed9d63362010-12-07 19:58:26 +00002172 std::string &raw_input_string,
Caroline Tice4ab31c92010-10-12 21:57:09 +00002173 CommandReturnObject &result)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002174{
2175 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Ticed9d63362010-12-07 19:58:26 +00002176
2177 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002178
Caroline Ticed9d63362010-12-07 19:58:26 +00002179 // Make sure that the alias name is the 0th element in cmd_args
2180 std::string alias_name_str = alias_name;
2181 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2182 cmd_args.Unshift (alias_name);
2183
2184 Args new_args (alias_cmd_obj->GetCommandName());
2185 if (new_args.GetArgumentCount() == 2)
2186 new_args.Shift();
2187
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002188 if (option_arg_vector_sp.get())
2189 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002190 if (wants_raw_input)
2191 {
2192 // We have a command that both has command options and takes raw input. Make *sure* it has a
2193 // " -- " in the right place in the raw_input_string.
2194 size_t pos = raw_input_string.find(" -- ");
2195 if (pos == std::string::npos)
2196 {
2197 // None found; assume it goes at the beginning of the raw input string
2198 raw_input_string.insert (0, " -- ");
2199 }
2200 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002201
2202 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2203 int old_size = cmd_args.GetArgumentCount();
Caroline Tice4ab31c92010-10-12 21:57:09 +00002204 std::vector<bool> used (old_size + 1, false);
2205
2206 used[0] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002207
2208 for (int i = 0; i < option_arg_vector->size(); ++i)
2209 {
2210 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Ticed9d63362010-12-07 19:58:26 +00002211 OptionArgValue value_pair = option_pair.second;
2212 int value_type = value_pair.first;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002213 std::string option = option_pair.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00002214 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002215 if (option.compare ("<argument>") == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002216 {
2217 if (!wants_raw_input
2218 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2219 new_args.AppendArgument (value.c_str());
2220 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002221 else
2222 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002223 if (value_type != optional_argument)
2224 new_args.AppendArgument (option.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002225 if (value.compare ("<no-argument>") != 0)
2226 {
2227 int index = GetOptionArgumentPosition (value.c_str());
2228 if (index == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002229 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002230 // value was NOT a positional argument; must be a real value
Caroline Ticed9d63362010-12-07 19:58:26 +00002231 if (value_type != optional_argument)
2232 new_args.AppendArgument (value.c_str());
2233 else
2234 {
2235 char buffer[255];
2236 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2237 new_args.AppendArgument (buffer);
2238 }
2239
2240 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002241 else if (index >= cmd_args.GetArgumentCount())
2242 {
2243 result.AppendErrorWithFormat
2244 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2245 index);
2246 result.SetStatus (eReturnStatusFailed);
2247 return;
2248 }
2249 else
2250 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002251 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2252 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2253 if (strpos != std::string::npos)
2254 {
2255 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2256 }
2257
2258 if (value_type != optional_argument)
2259 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2260 else
2261 {
2262 char buffer[255];
2263 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2264 cmd_args.GetArgumentAtIndex (index));
2265 new_args.AppendArgument (buffer);
2266 }
Caroline Tice4ab31c92010-10-12 21:57:09 +00002267 used[index] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002268 }
2269 }
2270 }
2271 }
2272
2273 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2274 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002275 if (!used[j] && !wants_raw_input)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002276 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2277 }
2278
2279 cmd_args.Clear();
2280 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2281 }
2282 else
2283 {
2284 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Ticed9d63362010-12-07 19:58:26 +00002285 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2286 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2287 // input string.
2288 if (wants_raw_input)
2289 {
2290 cmd_args.Clear();
2291 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2292 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002293 return;
2294 }
2295
2296 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2297 return;
2298}
2299
2300
2301int
2302CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2303{
2304 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2305 // of zero.
2306
2307 char *cptr = (char *) in_string;
2308
2309 // Does it start with '%'
2310 if (cptr[0] == '%')
2311 {
2312 ++cptr;
2313
2314 // Is the rest of it entirely digits?
2315 if (isdigit (cptr[0]))
2316 {
2317 const char *start = cptr;
2318 while (isdigit (cptr[0]))
2319 ++cptr;
2320
2321 // We've gotten to the end of the digits; are we at the end of the string?
2322 if (cptr[0] == '\0')
2323 position = atoi (start);
2324 }
2325 }
2326
2327 return position;
2328}
2329
2330void
2331CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2332{
Jim Ingham16e0c682011-08-12 23:34:31 +00002333 FileSpec init_file;
Greg Clayton14a35512011-09-11 00:01:44 +00002334 if (in_cwd)
Jim Ingham16e0c682011-08-12 23:34:31 +00002335 {
Greg Clayton14a35512011-09-11 00:01:44 +00002336 // In the current working directory we don't load any program specific
2337 // .lldbinit files, we only look for a "./.lldbinit" file.
2338 if (m_skip_lldbinit_files)
2339 return;
2340
2341 init_file.SetFile ("./.lldbinit", true);
Jim Ingham16e0c682011-08-12 23:34:31 +00002342 }
Greg Clayton14a35512011-09-11 00:01:44 +00002343 else
Jim Ingham16e0c682011-08-12 23:34:31 +00002344 {
Greg Clayton14a35512011-09-11 00:01:44 +00002345 // If we aren't looking in the current working directory we are looking
2346 // in the home directory. We will first see if there is an application
2347 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2348 // "-" and the name of the program. If this file doesn't exist, we fall
2349 // back to just the "~/.lldbinit" file. We also obey any requests to not
2350 // load the init files.
2351 const char *init_file_path = "~/.lldbinit";
2352
2353 if (m_skip_app_init_files == false)
2354 {
2355 FileSpec program_file_spec (Host::GetProgramFileSpec());
2356 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham16e0c682011-08-12 23:34:31 +00002357
Greg Clayton14a35512011-09-11 00:01:44 +00002358 if (program_name)
2359 {
2360 char program_init_file_name[PATH_MAX];
2361 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2362 init_file.SetFile (program_init_file_name, true);
2363 if (!init_file.Exists())
2364 init_file.Clear();
2365 }
2366 }
2367
2368 if (!init_file && !m_skip_lldbinit_files)
2369 init_file.SetFile (init_file_path, true);
2370 }
2371
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002372 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2373 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2374
2375 if (init_file.Exists())
2376 {
Jim Inghame16c50a2011-02-18 00:54:25 +00002377 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2378 bool stop_on_continue = true;
2379 bool stop_on_error = false;
2380 bool echo_commands = false;
2381 bool print_results = false;
2382
Enrico Granata5f5ab602012-05-31 01:09:06 +00002383 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002384 }
2385 else
2386 {
2387 // nothing to be done if the file doesn't exist
2388 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2389 }
2390}
2391
Greg Clayton8b82f082011-04-12 05:54:46 +00002392PlatformSP
2393CommandInterpreter::GetPlatform (bool prefer_target_platform)
2394{
2395 PlatformSP platform_sp;
Greg Claytonc14ee322011-09-22 04:58:26 +00002396 if (prefer_target_platform)
2397 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002398 ExecutionContext exe_ctx(GetExecutionContext());
2399 Target *target = exe_ctx.GetTargetPtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002400 if (target)
2401 platform_sp = target->GetPlatform();
2402 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002403
2404 if (!platform_sp)
2405 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2406 return platform_sp;
2407}
2408
Jim Inghame16c50a2011-02-18 00:54:25 +00002409void
Jim Inghambad87fe2011-03-11 01:51:49 +00002410CommandInterpreter::HandleCommands (const StringList &commands,
Jim Inghame16c50a2011-02-18 00:54:25 +00002411 ExecutionContext *override_context,
2412 bool stop_on_continue,
2413 bool stop_on_error,
2414 bool echo_commands,
2415 bool print_results,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002416 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002417 CommandReturnObject &result)
2418{
2419 size_t num_lines = commands.GetSize();
Jim Inghame16c50a2011-02-18 00:54:25 +00002420
2421 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2422 // Make sure you reset this value anywhere you return from the function.
2423
2424 bool old_async_execution = m_debugger.GetAsyncExecution();
2425
2426 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2427 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2428
2429 if (override_context != NULL)
Greg Clayton8b82f082011-04-12 05:54:46 +00002430 UpdateExecutionContext (override_context);
Jim Inghame16c50a2011-02-18 00:54:25 +00002431
2432 if (!stop_on_continue)
2433 {
2434 m_debugger.SetAsyncExecution (false);
2435 }
2436
2437 for (int idx = 0; idx < num_lines; idx++)
2438 {
2439 const char *cmd = commands.GetStringAtIndex(idx);
2440 if (cmd[0] == '\0')
2441 continue;
2442
Jim Inghame16c50a2011-02-18 00:54:25 +00002443 if (echo_commands)
2444 {
2445 result.AppendMessageWithFormat ("%s %s\n",
2446 GetPrompt(),
2447 cmd);
2448 }
2449
Greg Clayton9d0402b2011-02-20 02:15:07 +00002450 CommandReturnObject tmp_result;
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002451 // If override_context is not NULL, pass no_context_switching = true for
2452 // HandleCommand() since we updated our context already.
Enrico Granata5f5ab602012-05-31 01:09:06 +00002453 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002454 NULL, /* override_context */
2455 true, /* repeat_on_empty_command */
2456 override_context != NULL /* no_context_switching */);
Jim Inghame16c50a2011-02-18 00:54:25 +00002457
2458 if (print_results)
2459 {
2460 if (tmp_result.Succeeded())
Jim Ingham85e8b812011-02-19 02:53:09 +00002461 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Inghame16c50a2011-02-18 00:54:25 +00002462 }
2463
2464 if (!success || !tmp_result.Succeeded())
2465 {
Jim Inghama5038812012-04-24 02:25:07 +00002466 const char *error_msg = tmp_result.GetErrorData();
2467 if (error_msg == NULL || error_msg[0] == '\0')
2468 error_msg = "<unknown error>.\n";
Jim Inghame16c50a2011-02-18 00:54:25 +00002469 if (stop_on_error)
2470 {
Jim Inghama5038812012-04-24 02:25:07 +00002471 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2472 idx, cmd, error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002473 result.SetStatus (eReturnStatusFailed);
2474 m_debugger.SetAsyncExecution (old_async_execution);
2475 return;
2476 }
2477 else if (print_results)
2478 {
Jim Inghama5038812012-04-24 02:25:07 +00002479 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Inghame16c50a2011-02-18 00:54:25 +00002480 idx + 1,
2481 cmd,
Jim Inghama5038812012-04-24 02:25:07 +00002482 error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002483 }
2484 }
2485
Caroline Tice969ed3d2011-05-02 20:41:46 +00002486 if (result.GetImmediateOutputStream())
2487 result.GetImmediateOutputStream()->Flush();
2488
2489 if (result.GetImmediateErrorStream())
2490 result.GetImmediateErrorStream()->Flush();
2491
Jim Inghame16c50a2011-02-18 00:54:25 +00002492 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2493 // could be running (for instance in Breakpoint Commands.
2494 // So we check the return value to see if it is has running in it.
2495 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2496 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2497 {
2498 if (stop_on_continue)
2499 {
2500 // If we caused the target to proceed, and we're going to stop in that case, set the
2501 // status in our real result before returning. This is an error if the continue was not the
2502 // last command in the set of commands to be run.
2503 if (idx != num_lines - 1)
2504 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2505 idx + 1, cmd);
2506 else
2507 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2508
2509 result.SetStatus(tmp_result.GetStatus());
2510 m_debugger.SetAsyncExecution (old_async_execution);
2511
2512 return;
2513 }
2514 }
2515
2516 }
2517
2518 result.SetStatus (eReturnStatusSuccessFinishResult);
2519 m_debugger.SetAsyncExecution (old_async_execution);
2520
2521 return;
2522}
2523
2524void
2525CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2526 ExecutionContext *context,
2527 bool stop_on_continue,
2528 bool stop_on_error,
2529 bool echo_command,
2530 bool print_result,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002531 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002532 CommandReturnObject &result)
2533{
2534 if (cmd_file.Exists())
2535 {
2536 bool success;
2537 StringList commands;
2538 success = commands.ReadFileLines(cmd_file);
2539 if (!success)
2540 {
2541 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2542 result.SetStatus (eReturnStatusFailed);
2543 return;
2544 }
Enrico Granata5f5ab602012-05-31 01:09:06 +00002545 m_command_source_depth++;
2546 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2547 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002548 }
2549 else
2550 {
2551 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2552 cmd_file.GetFilename().AsCString());
2553 result.SetStatus (eReturnStatusFailed);
2554 return;
2555 }
2556}
2557
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002558ScriptInterpreter *
Enrico Granatab5887262012-10-29 21:18:03 +00002559CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002560{
Enrico Granatab5887262012-10-29 21:18:03 +00002561 if (m_script_interpreter_ap.get() != NULL)
2562 return m_script_interpreter_ap.get();
2563
2564 if (!can_create)
2565 return NULL;
2566
Enrico Granataa29bdad2012-07-10 18:23:48 +00002567 // <rdar://problem/11751427>
2568 // we need to protect the initialization of the script interpreter
2569 // otherwise we could end up with two threads both trying to create
2570 // their instance of it, and for some languages (e.g. Python)
2571 // this is a bulletproof recipe for disaster!
2572 // this needs to be a function-level static because multiple Debugger instances living in the same process
2573 // still need to be isolated and not try to initialize Python concurrently
Enrico Granata8b95df22012-07-10 19:04:14 +00002574 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2575 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granataa29bdad2012-07-10 18:23:48 +00002576
Enrico Granatab5887262012-10-29 21:18:03 +00002577 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
2578 if (log)
2579 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton66111032010-06-23 01:19:29 +00002580
Caroline Tice2f88aad2011-01-14 00:29:16 +00002581 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2582 switch (script_lang)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002583 {
Greg Claytondce502e2011-11-04 03:34:56 +00002584 case eScriptLanguagePython:
2585#ifndef LLDB_DISABLE_PYTHON
2586 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2587 break;
2588#else
2589 // Fall through to the None case when python is disabled
2590#endif
Caroline Tice2f88aad2011-01-14 00:29:16 +00002591 case eScriptLanguageNone:
2592 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2593 break;
Caroline Tice2f88aad2011-01-14 00:29:16 +00002594 };
2595
2596 return m_script_interpreter_ap.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002597}
2598
2599
2600
2601bool
2602CommandInterpreter::GetSynchronous ()
2603{
2604 return m_synchronous_execution;
2605}
2606
2607void
2608CommandInterpreter::SetSynchronous (bool value)
2609{
Johnny Chenc066ab42010-10-14 01:22:03 +00002610 m_synchronous_execution = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002611}
2612
2613void
2614CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2615 const char *word_text,
2616 const char *separator,
2617 const char *help_text,
2618 uint32_t max_word_len)
2619{
Greg Claytona7015092010-09-18 01:14:36 +00002620 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2621
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002622 int indent_size = max_word_len + strlen (separator) + 2;
2623
2624 strm.IndentMore (indent_size);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002625
2626 StreamString text_strm;
2627 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2628
2629 size_t len = text_strm.GetSize();
2630 const char *text = text_strm.GetData();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002631 if (text[len - 1] == '\n')
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002632 {
2633 text_strm.EOL();
2634 len = text_strm.GetSize();
2635 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002636
2637 if (len < max_columns)
2638 {
2639 // Output it as a single line.
2640 strm.Printf ("%s", text);
2641 }
2642 else
2643 {
2644 // We need to break it up into multiple lines.
2645 bool first_line = true;
2646 int text_width;
2647 int start = 0;
2648 int end = start;
2649 int final_end = strlen (text);
2650 int sub_len;
2651
2652 while (end < final_end)
2653 {
2654 if (first_line)
2655 text_width = max_columns - 1;
2656 else
2657 text_width = max_columns - indent_size - 1;
2658
2659 // Don't start the 'text' on a space, since we're already outputting the indentation.
2660 if (!first_line)
2661 {
2662 while ((start < final_end) && (text[start] == ' '))
2663 start++;
2664 }
2665
2666 end = start + text_width;
2667 if (end > final_end)
2668 end = final_end;
2669 else
2670 {
2671 // If we're not at the end of the text, make sure we break the line on white space.
2672 while (end > start
2673 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2674 end--;
Greg Clayton67cc0632012-08-22 17:17:09 +00002675 assert (end > 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002676 }
2677
2678 sub_len = end - start;
2679 if (start != 0)
2680 strm.EOL();
2681 if (!first_line)
2682 strm.Indent();
2683 else
2684 first_line = false;
2685 assert (start <= final_end);
2686 assert (start + sub_len <= final_end);
2687 if (sub_len > 0)
2688 strm.Write (text + start, sub_len);
2689 start = end + 1;
2690 }
2691 }
2692 strm.EOL();
2693 strm.IndentLess(indent_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002694}
2695
2696void
Enrico Granata82a7d982011-07-07 00:38:40 +00002697CommandInterpreter::OutputHelpText (Stream &strm,
2698 const char *word_text,
2699 const char *separator,
2700 const char *help_text,
2701 uint32_t max_word_len)
2702{
2703 int indent_size = max_word_len + strlen (separator) + 2;
2704
2705 strm.IndentMore (indent_size);
2706
2707 StreamString text_strm;
2708 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2709
2710 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata82a7d982011-07-07 00:38:40 +00002711
2712 size_t len = text_strm.GetSize();
2713 const char *text = text_strm.GetData();
2714
2715 uint32_t chars_left = max_columns;
2716
2717 for (uint32_t i = 0; i < len; i++)
2718 {
2719 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2720 {
Enrico Granata82a7d982011-07-07 00:38:40 +00002721 chars_left = max_columns - indent_size;
2722 strm.EOL();
2723 strm.Indent();
2724 }
2725 else
2726 {
2727 strm.PutChar(text[i]);
2728 chars_left--;
2729 }
2730
2731 }
2732
2733 strm.EOL();
2734 strm.IndentLess(indent_size);
2735}
2736
2737void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002738CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2739 StringList &commands_help)
2740{
2741 CommandObject::CommandMap::const_iterator pos;
2742
2743 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2744 {
2745 const char *command_name = pos->first.c_str();
2746 CommandObject *cmd_obj = pos->second.get();
2747
Greg Claytona7015092010-09-18 01:14:36 +00002748 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002749 {
2750 commands_found.AppendString (command_name);
2751 commands_help.AppendString (cmd_obj->GetHelp());
2752 }
2753
2754 if (cmd_obj->IsMultiwordObject())
Greg Clayton998255b2012-10-13 02:07:45 +00002755 cmd_obj->AproposAllSubCommands (command_name,
2756 search_word,
2757 commands_found,
2758 commands_help);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002759
2760 }
2761}
Greg Clayton8b82f082011-04-12 05:54:46 +00002762
2763
2764void
2765CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2766{
Greg Clayton8b82f082011-04-12 05:54:46 +00002767 if (override_context != NULL)
2768 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002769 m_exe_ctx_ref = *override_context;
Greg Clayton8b82f082011-04-12 05:54:46 +00002770 }
2771 else
2772 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002773 const bool adopt_selected = true;
2774 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Clayton8b82f082011-04-12 05:54:46 +00002775 }
2776}
2777
Jim Inghama5a97eb2011-07-12 03:12:18 +00002778void
2779CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2780{
2781 DumpHistory (stream, 0, count - 1);
2782}
2783
2784void
2785CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2786{
Greg Clayton5521f992011-10-28 21:38:01 +00002787 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2788 for (size_t i = start; i < last_idx; i++)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002789 {
2790 if (!m_command_history[i].empty())
2791 {
2792 stream.Indent();
Greg Clayton5521f992011-10-28 21:38:01 +00002793 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Inghama5a97eb2011-07-12 03:12:18 +00002794 }
2795 }
2796}
2797
2798const char *
2799CommandInterpreter::FindHistoryString (const char *input_str) const
2800{
2801 if (input_str[0] != m_repeat_char)
2802 return NULL;
2803 if (input_str[1] == '-')
2804 {
2805 bool success;
2806 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2807 if (!success)
2808 return NULL;
2809 if (idx > m_command_history.size())
2810 return NULL;
2811 idx = m_command_history.size() - idx;
2812 return m_command_history[idx].c_str();
2813
2814 }
2815 else if (input_str[1] == m_repeat_char)
2816 {
2817 if (m_command_history.empty())
2818 return NULL;
2819 else
2820 return m_command_history.back().c_str();
2821 }
2822 else
2823 {
2824 bool success;
2825 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2826 if (!success)
2827 return NULL;
2828 if (idx >= m_command_history.size())
2829 return NULL;
2830 return m_command_history[idx].c_str();
2831 }
2832}