blob: f248fdf1d8899408030d1715b8361e172ea6a640 [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)
Jim Ingham184e9812013-01-15 02:47:48 +00001323 .SetIgnoreBreakpoints(true)
Enrico Granatad4439aa2012-09-05 20:41:26 +00001324 .SetKeepInMemory(false)
Jim Ingham35e1bda2012-10-16 21:41:58 +00001325 .SetRunOthers(true)
1326 .SetTimeoutUsec(0);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001327
Greg Clayton5a314712011-10-14 07:41:33 +00001328 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad4439aa2012-09-05 20:41:26 +00001329 exe_ctx.GetFramePtr(),
Enrico Granata3372f582012-07-16 23:10:35 +00001330 expr_result_valobj_sp,
Enrico Granatad4439aa2012-09-05 20:41:26 +00001331 options);
1332
Greg Clayton5a314712011-10-14 07:41:33 +00001333 if (expr_result == eExecutionCompleted)
1334 {
1335 Scalar scalar;
1336 if (expr_result_valobj_sp->ResolveValue (scalar))
1337 {
1338 command.erase (start_backtick, end_backtick - start_backtick + 1);
1339 StreamString value_strm;
1340 const bool show_type = false;
1341 scalar.GetValue (&value_strm, show_type);
1342 size_t value_string_size = value_strm.GetSize();
1343 if (value_string_size)
1344 {
1345 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1346 pos = start_backtick + value_string_size;
1347 continue;
1348 }
1349 else
1350 {
1351 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1352 }
1353 }
1354 else
1355 {
1356 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1357 }
1358 }
1359 else
1360 {
1361 if (expr_result_valobj_sp)
1362 error = expr_result_valobj_sp->GetError();
1363 if (error.Success())
1364 {
1365
1366 switch (expr_result)
1367 {
1368 case eExecutionSetupError:
1369 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1370 break;
1371 case eExecutionCompleted:
1372 break;
1373 case eExecutionDiscarded:
1374 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1375 break;
1376 case eExecutionInterrupted:
1377 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1378 break;
Jim Ingham184e9812013-01-15 02:47:48 +00001379 case eExecutionHitBreakpoint:
1380 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1381 break;
Greg Clayton5a314712011-10-14 07:41:33 +00001382 case eExecutionTimedOut:
1383 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1384 break;
1385 }
1386 }
1387 }
1388 }
1389 }
1390 if (error.Fail())
1391 break;
1392 }
1393 }
1394 return error;
1395}
1396
1397
Caroline Tice844d2302010-12-09 22:52:49 +00001398bool
1399CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata5f5ab602012-05-31 01:09:06 +00001400 LazyBool lazy_add_to_history,
Caroline Tice844d2302010-12-09 22:52:49 +00001401 CommandReturnObject &result,
Jim Inghame16c50a2011-02-18 00:54:25 +00001402 ExecutionContext *override_context,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001403 bool repeat_on_empty_command,
1404 bool no_context_switching)
Jim Inghame16c50a2011-02-18 00:54:25 +00001405
Caroline Tice844d2302010-12-09 22:52:49 +00001406{
Jim Inghame16c50a2011-02-18 00:54:25 +00001407
Caroline Tice844d2302010-12-09 22:52:49 +00001408 bool done = false;
1409 CommandObject *cmd_obj = NULL;
Caroline Tice844d2302010-12-09 22:52:49 +00001410 bool wants_raw_input = false;
1411 std::string command_string (command_line);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001412 std::string original_command_string (command_line);
Caroline Tice844d2302010-12-09 22:52:49 +00001413
1414 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001415 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1416
1417 // Make a scoped cleanup object that will clear the crash description string
1418 // on exit of this function.
Enrico Granataf9fa6ee2011-07-12 00:18:11 +00001419 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001420
Caroline Tice844d2302010-12-09 22:52:49 +00001421 if (log)
1422 log->Printf ("Processing command: %s", command_line);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001423
Jim Ingham30244832010-11-04 23:08:45 +00001424 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1425
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001426 if (!no_context_switching)
1427 UpdateExecutionContext (override_context);
Enrico Granata5f5ab602012-05-31 01:09:06 +00001428
1429 // <rdar://problem/11328896>
1430 bool add_to_history;
1431 if (lazy_add_to_history == eLazyBoolCalculate)
1432 add_to_history = (m_command_source_depth == 0);
1433 else
1434 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1435
Jim Inghame16c50a2011-02-18 00:54:25 +00001436 bool empty_command = false;
1437 bool comment_command = false;
1438 if (command_string.empty())
1439 empty_command = true;
1440 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001441 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001442 const char *k_space_characters = "\t\n\v\f\r ";
1443
1444 size_t non_space = command_string.find_first_not_of (k_space_characters);
1445 // Check for empty line or comment line (lines whose first
1446 // non-space character is the comment character for this interpreter)
1447 if (non_space == std::string::npos)
1448 empty_command = true;
1449 else if (command_string[non_space] == m_comment_char)
1450 comment_command = true;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001451 else if (command_string[non_space] == m_repeat_char)
1452 {
1453 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1454 if (history_string == NULL)
1455 {
1456 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1457 result.SetStatus(eReturnStatusFailed);
1458 return false;
1459 }
1460 add_to_history = false;
1461 command_string = history_string;
1462 original_command_string = history_string;
1463 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001464 }
1465
1466 if (empty_command)
1467 {
1468 if (repeat_on_empty_command)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001469 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001470 if (m_command_history.empty())
1471 {
1472 result.AppendError ("empty command");
1473 result.SetStatus(eReturnStatusFailed);
1474 return false;
1475 }
1476 else
1477 {
1478 command_line = m_repeat_command.c_str();
1479 command_string = command_line;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001480 original_command_string = command_line;
Jim Inghame16c50a2011-02-18 00:54:25 +00001481 if (m_repeat_command.empty())
1482 {
1483 result.AppendErrorWithFormat("No auto repeat.\n");
1484 result.SetStatus (eReturnStatusFailed);
1485 return false;
1486 }
1487 }
1488 add_to_history = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001489 }
1490 else
1491 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001492 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1493 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001494 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001495 }
1496 else if (comment_command)
1497 {
1498 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1499 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001500 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001501
Greg Clayton5a314712011-10-14 07:41:33 +00001502
1503 Error error (PreprocessCommand (command_string));
1504
1505 if (error.Fail())
1506 {
1507 result.AppendError (error.AsCString());
1508 result.SetStatus(eReturnStatusFailed);
1509 return false;
1510 }
Caroline Tice844d2302010-12-09 22:52:49 +00001511 // Phase 1.
1512
1513 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1514 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1515 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1516 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1517 // 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 +00001518 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Tice844d2302010-12-09 22:52:49 +00001519 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Ticed9d63362010-12-07 19:58:26 +00001520
Caroline Tice844d2302010-12-09 22:52:49 +00001521 StreamString revised_command_line;
Caroline Tice01274c02010-12-11 08:16:56 +00001522 size_t actual_cmd_name_len = 0;
Greg Clayton5521f992011-10-28 21:38:01 +00001523 std::string next_word;
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001524 StringList matches;
Caroline Tice844d2302010-12-09 22:52:49 +00001525 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001526 {
Caroline Tice2b5e8502011-05-11 16:07:06 +00001527 char quote_char = '\0';
Greg Clayton5521f992011-10-28 21:38:01 +00001528 std::string suffix;
1529 ExtractCommand (command_string, next_word, suffix, quote_char);
1530 if (cmd_obj == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001531 {
Greg Clayton5521f992011-10-28 21:38:01 +00001532 if (AliasExists (next_word.c_str()))
Caroline Tice472362e2010-12-14 18:51:39 +00001533 {
Greg Clayton5521f992011-10-28 21:38:01 +00001534 std::string alias_result;
1535 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1536 revised_command_line.Printf ("%s", alias_result.c_str());
1537 if (cmd_obj)
1538 {
1539 wants_raw_input = cmd_obj->WantsRawCommandString ();
1540 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1541 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001542 }
1543 else
1544 {
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001545 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton5521f992011-10-28 21:38:01 +00001546 if (cmd_obj)
1547 {
1548 actual_cmd_name_len += next_word.length();
1549 revised_command_line.Printf ("%s", next_word.c_str());
1550 wants_raw_input = cmd_obj->WantsRawCommandString ();
1551 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001552 else
Greg Clayton5521f992011-10-28 21:38:01 +00001553 {
1554 revised_command_line.Printf ("%s", next_word.c_str());
1555 }
Caroline Tice844d2302010-12-09 22:52:49 +00001556 }
1557 }
1558 else
1559 {
Greg Clayton5521f992011-10-28 21:38:01 +00001560 if (cmd_obj->IsMultiwordObject ())
1561 {
Greg Clayton998255b2012-10-13 02:07:45 +00001562 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
Greg Clayton5521f992011-10-28 21:38:01 +00001563 if (sub_cmd_obj)
1564 {
1565 actual_cmd_name_len += next_word.length() + 1;
1566 revised_command_line.Printf (" %s", next_word.c_str());
1567 cmd_obj = sub_cmd_obj;
1568 wants_raw_input = cmd_obj->WantsRawCommandString ();
1569 }
1570 else
1571 {
1572 if (quote_char)
1573 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1574 else
1575 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1576 done = true;
1577 }
1578 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001579 else
Greg Clayton5521f992011-10-28 21:38:01 +00001580 {
1581 if (quote_char)
1582 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1583 else
1584 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1585 done = true;
1586 }
Caroline Tice844d2302010-12-09 22:52:49 +00001587 }
1588
1589 if (cmd_obj == NULL)
1590 {
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001591 uint32_t num_matches = matches.GetSize();
1592 if (matches.GetSize() > 1) {
1593 std::string error_msg;
1594 error_msg.assign ("Ambiguous command '");
1595 error_msg.append(next_word.c_str());
1596 error_msg.append ("'.");
1597
1598 error_msg.append (" Possible matches:");
1599
1600 for (uint32_t i = 0; i < num_matches; ++i) {
1601 error_msg.append ("\n\t");
1602 error_msg.append (matches.GetStringAtIndex(i));
1603 }
1604 error_msg.append ("\n");
1605 result.AppendRawError (error_msg.c_str(), error_msg.size());
1606 } else {
1607 // We didn't have only one match, otherwise we wouldn't get here.
1608 assert(num_matches == 0);
1609 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1610 }
Caroline Tice844d2302010-12-09 22:52:49 +00001611 result.SetStatus (eReturnStatusFailed);
1612 return false;
1613 }
1614
Greg Clayton5521f992011-10-28 21:38:01 +00001615 if (cmd_obj->IsMultiwordObject ())
1616 {
1617 if (!suffix.empty())
1618 {
1619
1620 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1621 next_word.c_str(),
1622 suffix.c_str());
1623 result.SetStatus (eReturnStatusFailed);
1624 return false;
1625 }
1626 }
1627 else
1628 {
1629 // If we found a normal command, we are done
1630 done = true;
1631 if (!suffix.empty())
1632 {
1633 switch (suffix[0])
1634 {
1635 case '/':
1636 // GDB format suffixes
Greg Clayton52ec56c2011-10-29 00:57:28 +00001637 {
1638 Options *command_options = cmd_obj->GetOptions();
1639 if (command_options && command_options->SupportsLongOption("gdb-format"))
1640 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001641 std::string gdb_format_option ("--gdb-format=");
1642 gdb_format_option += (suffix.c_str() + 1);
1643
1644 bool inserted = false;
1645 std::string &cmd = revised_command_line.GetString();
1646 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1647 if (arg_terminator_idx != std::string::npos)
1648 {
1649 // Insert the gdb format option before the "--" that terminates options
1650 gdb_format_option.append(1,' ');
1651 cmd.insert(arg_terminator_idx, gdb_format_option);
1652 inserted = true;
1653 }
1654
1655 if (!inserted)
1656 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1657
1658 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1659 revised_command_line.PutCString (" --");
Greg Clayton52ec56c2011-10-29 00:57:28 +00001660 }
1661 else
1662 {
1663 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1664 cmd_obj->GetCommandName());
1665 result.SetStatus (eReturnStatusFailed);
1666 return false;
1667 }
1668 }
Greg Clayton5521f992011-10-28 21:38:01 +00001669 break;
Johnny Chen8e9383d2011-10-31 22:22:06 +00001670
1671 default:
1672 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1673 suffix.c_str());
1674 result.SetStatus (eReturnStatusFailed);
1675 return false;
1676
Greg Clayton5521f992011-10-28 21:38:01 +00001677 }
1678 }
1679 }
Caroline Tice844d2302010-12-09 22:52:49 +00001680 if (command_string.length() == 0)
1681 done = true;
1682
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001683 }
Caroline Tice844d2302010-12-09 22:52:49 +00001684
Greg Clayton5521f992011-10-28 21:38:01 +00001685 if (!command_string.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001686 revised_command_line.Printf (" %s", command_string.c_str());
1687
1688 // End of Phase 1.
1689 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1690 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1691 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1692 // wants_raw_input specifies whether the Execute method expects raw input or not.
1693
1694
1695 if (log)
1696 {
1697 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1698 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1699 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1700 }
1701
1702 // Phase 2.
1703 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1704 // CommandObject, with the appropriate arguments.
1705
1706 if (cmd_obj != NULL)
1707 {
1708 if (add_to_history)
1709 {
1710 Args command_args (revised_command_line.GetData());
1711 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1712 if (repeat_command != NULL)
1713 m_repeat_command.assign(repeat_command);
1714 else
Jim Inghama5a97eb2011-07-12 03:12:18 +00001715 m_repeat_command.assign(original_command_string.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001716
Jim Inghama5a97eb2011-07-12 03:12:18 +00001717 // Don't keep pushing the same command onto the history...
Greg Clayton5521f992011-10-28 21:38:01 +00001718 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001719 m_command_history.push_back (original_command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001720 }
1721
1722 command_string = revised_command_line.GetData();
1723 std::string command_name (cmd_obj->GetCommandName());
Caroline Tice01274c02010-12-11 08:16:56 +00001724 std::string remainder;
1725 if (actual_cmd_name_len < command_string.length())
1726 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1727 // than cmd_obj->GetCommandName(), because name completion
1728 // allows users to enter short versions of the names,
1729 // e.g. 'br s' for 'breakpoint set'.
Caroline Tice844d2302010-12-09 22:52:49 +00001730
1731 // Remove any initial spaces
1732 std::string white_space (" \t\v");
1733 size_t pos = remainder.find_first_not_of (white_space);
1734 if (pos != 0 && pos != std::string::npos)
Greg Claytona3482592011-04-22 20:58:45 +00001735 remainder.erase(0, pos);
Caroline Tice844d2302010-12-09 22:52:49 +00001736
1737 if (log)
Jason Molendabfb36ff2011-08-25 00:20:04 +00001738 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001739
Jim Ingham5a988412012-06-08 21:56:10 +00001740 cmd_obj->Execute (remainder.c_str(), result);
Caroline Tice844d2302010-12-09 22:52:49 +00001741 }
1742 else
1743 {
1744 // We didn't find the first command object, so complete the first argument.
1745 Args command_args (revised_command_line.GetData());
1746 StringList matches;
1747 int num_matches;
1748 int cursor_index = 0;
1749 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1750 bool word_complete;
1751 num_matches = HandleCompletionMatches (command_args,
1752 cursor_index,
1753 cursor_char_position,
1754 0,
1755 -1,
1756 word_complete,
1757 matches);
1758
1759 if (num_matches > 0)
1760 {
1761 std::string error_msg;
1762 error_msg.assign ("ambiguous command '");
1763 error_msg.append(command_args.GetArgumentAtIndex(0));
1764 error_msg.append ("'.");
1765
1766 error_msg.append (" Possible completions:");
1767 for (int i = 0; i < num_matches; i++)
1768 {
1769 error_msg.append ("\n\t");
1770 error_msg.append (matches.GetStringAtIndex (i));
1771 }
1772 error_msg.append ("\n");
1773 result.AppendRawError (error_msg.c_str(), error_msg.size());
1774 }
1775 else
1776 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1777
1778 result.SetStatus (eReturnStatusFailed);
1779 }
1780
Jason Molendabfb36ff2011-08-25 00:20:04 +00001781 if (log)
1782 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1783
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001784 return result.Succeeded();
1785}
1786
1787int
1788CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1789 int &cursor_index,
1790 int &cursor_char_position,
1791 int match_start_point,
1792 int max_return_elements,
Jim Ingham558ce122010-06-30 05:02:46 +00001793 bool &word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001794 StringList &matches)
1795{
1796 int num_command_matches = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001797 bool look_for_subcommand = false;
Jim Ingham558ce122010-06-30 05:02:46 +00001798
1799 // For any of the command completions a unique match will be a complete word.
1800 word_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001801
1802 if (cursor_index == -1)
1803 {
1804 // We got nothing on the command line, so return the list of commands
Jim Ingham279a6c22010-07-06 22:46:59 +00001805 bool include_aliases = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001806 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1807 }
1808 else if (cursor_index == 0)
1809 {
1810 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Ingham279a6c22010-07-06 22:46:59 +00001811 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001812 num_command_matches = matches.GetSize();
1813
1814 if (num_command_matches == 1
1815 && cmd_obj && cmd_obj->IsMultiwordObject()
1816 && matches.GetStringAtIndex(0) != NULL
1817 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1818 {
1819 look_for_subcommand = true;
1820 num_command_matches = 0;
1821 matches.DeleteStringAtIndex(0);
1822 parsed_line.AppendArgument ("");
1823 cursor_index++;
1824 cursor_char_position = 0;
1825 }
1826 }
1827
1828 if (cursor_index > 0 || look_for_subcommand)
1829 {
1830 // We are completing further on into a commands arguments, so find the command and tell it
1831 // to complete the command.
1832 // First see if there is a matching initial command:
Jim Ingham279a6c22010-07-06 22:46:59 +00001833 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001834 if (command_object == NULL)
1835 {
1836 return 0;
1837 }
1838 else
1839 {
1840 parsed_line.Shift();
1841 cursor_index--;
Greg Claytona7015092010-09-18 01:14:36 +00001842 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton66111032010-06-23 01:19:29 +00001843 cursor_index,
1844 cursor_char_position,
1845 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001846 max_return_elements,
1847 word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001848 matches);
1849 }
1850 }
1851
1852 return num_command_matches;
1853
1854}
1855
1856int
1857CommandInterpreter::HandleCompletion (const char *current_line,
1858 const char *cursor,
1859 const char *last_char,
1860 int match_start_point,
1861 int max_return_elements,
1862 StringList &matches)
1863{
1864 // We parse the argument up to the cursor, so the last argument in parsed_line is
1865 // the one containing the cursor, and the cursor is after the last character.
1866
1867 Args parsed_line(current_line, last_char - current_line);
1868 Args partial_parsed_line(current_line, cursor - current_line);
1869
Jim Inghama5a97eb2011-07-12 03:12:18 +00001870 // Don't complete comments, and if the line we are completing is just the history repeat character,
1871 // substitute the appropriate history line.
1872 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1873 if (first_arg)
1874 {
1875 if (first_arg[0] == m_comment_char)
1876 return 0;
1877 else if (first_arg[0] == m_repeat_char)
1878 {
1879 const char *history_string = FindHistoryString (first_arg);
1880 if (history_string != NULL)
1881 {
1882 matches.Clear();
1883 matches.InsertStringAtIndex(0, history_string);
1884 return -2;
1885 }
1886 else
1887 return 0;
1888
1889 }
1890 }
1891
1892
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001893 int num_args = partial_parsed_line.GetArgumentCount();
1894 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1895 int cursor_char_position;
1896
1897 if (cursor_index == -1)
1898 cursor_char_position = 0;
1899 else
1900 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamfe0c4252010-12-14 19:56:01 +00001901
1902 if (cursor > current_line && cursor[-1] == ' ')
1903 {
1904 // We are just after a space. If we are in an argument, then we will continue
1905 // parsing, but if we are between arguments, then we have to complete whatever the next
1906 // element would be.
1907 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1908 // protected by a quote) then the space will also be in the parsed argument...
1909
1910 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1911 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1912 {
1913 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1914 cursor_index++;
1915 cursor_char_position = 0;
1916 }
1917 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001918
1919 int num_command_matches;
1920
1921 matches.Clear();
1922
1923 // Only max_return_elements == -1 is supported at present:
1924 assert (max_return_elements == -1);
Jim Ingham558ce122010-06-30 05:02:46 +00001925 bool word_complete;
Greg Clayton66111032010-06-23 01:19:29 +00001926 num_command_matches = HandleCompletionMatches (parsed_line,
1927 cursor_index,
1928 cursor_char_position,
1929 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001930 max_return_elements,
1931 word_complete,
Greg Clayton66111032010-06-23 01:19:29 +00001932 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001933
1934 if (num_command_matches <= 0)
1935 return num_command_matches;
1936
1937 if (num_args == 0)
1938 {
1939 // If we got an empty string, insert nothing.
1940 matches.InsertStringAtIndex(0, "");
1941 }
1942 else
1943 {
1944 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1945 // put an empty string in element 0.
1946 std::string command_partial_str;
1947 if (cursor_index >= 0)
Jim Ingham49e80a12010-10-22 18:47:16 +00001948 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1949 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001950
1951 std::string common_prefix;
1952 matches.LongestCommonPrefix (common_prefix);
1953 int partial_name_len = command_partial_str.size();
1954
1955 // If we matched a unique single command, add a space...
Jim Ingham558ce122010-06-30 05:02:46 +00001956 // Only do this if the completer told us this was a complete word, however...
1957 if (num_command_matches == 1 && word_complete)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001958 {
1959 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1960 if (quote_char != '\0')
1961 common_prefix.push_back(quote_char);
1962
1963 common_prefix.push_back(' ');
1964 }
1965 common_prefix.erase (0, partial_name_len);
1966 matches.InsertStringAtIndex(0, common_prefix.c_str());
1967 }
1968 return num_command_matches;
1969}
1970
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001971
1972CommandInterpreter::~CommandInterpreter ()
1973{
1974}
1975
1976const char *
1977CommandInterpreter::GetPrompt ()
1978{
Caroline Ticedaccaa92010-09-20 20:44:43 +00001979 return m_debugger.GetPrompt();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001980}
1981
1982void
1983CommandInterpreter::SetPrompt (const char *new_prompt)
1984{
Caroline Ticedaccaa92010-09-20 20:44:43 +00001985 m_debugger.SetPrompt (new_prompt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001986}
1987
Jim Ingham97a6dc72010-10-04 19:49:29 +00001988size_t
Greg Clayton51b1e2d2011-02-09 01:08:52 +00001989CommandInterpreter::GetConfirmationInputReaderCallback
1990(
1991 void *baton,
1992 InputReader &reader,
1993 lldb::InputReaderAction action,
1994 const char *bytes,
1995 size_t bytes_len
1996)
Jim Ingham97a6dc72010-10-04 19:49:29 +00001997{
Greg Clayton51b1e2d2011-02-09 01:08:52 +00001998 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham97a6dc72010-10-04 19:49:29 +00001999 bool *response_ptr = (bool *) baton;
2000
2001 switch (action)
2002 {
2003 case eInputReaderActivate:
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002004 if (out_file.IsValid())
Jim Ingham97a6dc72010-10-04 19:49:29 +00002005 {
2006 if (reader.GetPrompt())
Caroline Tice31f7d462011-02-02 01:17:56 +00002007 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002008 out_file.Printf ("%s", reader.GetPrompt());
2009 out_file.Flush ();
Caroline Tice31f7d462011-02-02 01:17:56 +00002010 }
Jim Ingham97a6dc72010-10-04 19:49:29 +00002011 }
2012 break;
2013
2014 case eInputReaderDeactivate:
2015 break;
2016
2017 case eInputReaderReactivate:
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002018 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice31f7d462011-02-02 01:17:56 +00002019 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002020 out_file.Printf ("%s", reader.GetPrompt());
2021 out_file.Flush ();
Caroline Tice31f7d462011-02-02 01:17:56 +00002022 }
Jim Ingham97a6dc72010-10-04 19:49:29 +00002023 break;
Caroline Tice969ed3d2011-05-02 20:41:46 +00002024
2025 case eInputReaderAsynchronousOutputWritten:
2026 break;
2027
Jim Ingham97a6dc72010-10-04 19:49:29 +00002028 case eInputReaderGotToken:
2029 if (bytes_len == 0)
2030 {
2031 reader.SetIsDone(true);
2032 }
Jim Inghamc8b47582011-11-14 20:02:01 +00002033 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham97a6dc72010-10-04 19:49:29 +00002034 {
2035 *response_ptr = true;
2036 reader.SetIsDone(true);
2037 }
Jim Inghamc8b47582011-11-14 20:02:01 +00002038 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham97a6dc72010-10-04 19:49:29 +00002039 {
2040 *response_ptr = false;
2041 reader.SetIsDone(true);
2042 }
2043 else
2044 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002045 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham97a6dc72010-10-04 19:49:29 +00002046 {
Jim Ingham78d61482011-11-17 01:22:00 +00002047 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002048 out_file.Flush ();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002049 }
2050 }
2051 break;
2052
Caroline Ticeefed6132010-11-19 20:47:54 +00002053 case eInputReaderInterrupt:
2054 case eInputReaderEndOfFile:
2055 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
2056 reader.SetIsDone (true);
2057 break;
2058
Jim Ingham97a6dc72010-10-04 19:49:29 +00002059 case eInputReaderDone:
2060 break;
2061 }
2062
2063 return bytes_len;
2064
2065}
2066
2067bool
2068CommandInterpreter::Confirm (const char *message, bool default_answer)
2069{
Jim Ingham3bcdb292010-10-04 22:44:14 +00002070 // Check AutoConfirm first:
2071 if (m_debugger.GetAutoConfirm())
2072 return default_answer;
2073
Jim Ingham97a6dc72010-10-04 19:49:29 +00002074 InputReaderSP reader_sp (new InputReader(GetDebugger()));
2075 bool response = default_answer;
2076 if (reader_sp)
2077 {
2078 std::string prompt(message);
2079 prompt.append(": [");
2080 if (default_answer)
2081 prompt.append ("Y/n] ");
2082 else
2083 prompt.append ("y/N] ");
2084
2085 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
2086 &response, // baton
2087 eInputReaderGranularityLine, // token size, to pass to callback function
2088 NULL, // end token
2089 prompt.c_str(), // prompt
2090 true)); // echo input
2091 if (err.Success())
2092 {
2093 GetDebugger().PushInputReader (reader_sp);
2094 }
2095 reader_sp->WaitOnReaderIsDone();
2096 }
2097 return response;
2098}
2099
2100
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002101void
2102CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
2103{
Jim Ingham279a6c22010-07-06 22:46:59 +00002104 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002105
Sean Callanan9a028512012-08-09 00:50:26 +00002106 if (cmd_obj_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002107 {
2108 CommandObject *cmd_obj = cmd_obj_sp.get();
2109 if (cmd_obj->IsCrossRefObject ())
2110 cmd_obj->AddObject (object_type);
2111 }
2112}
2113
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002114OptionArgVectorSP
2115CommandInterpreter::GetAliasOptions (const char *alias_name)
2116{
2117 OptionArgMap::iterator pos;
2118 OptionArgVectorSP ret_val;
2119
2120 std::string alias (alias_name);
2121
2122 if (HasAliasOptions())
2123 {
2124 pos = m_alias_options.find (alias);
2125 if (pos != m_alias_options.end())
2126 ret_val = pos->second;
2127 }
2128
2129 return ret_val;
2130}
2131
2132void
2133CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2134{
2135 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2136 if (pos != m_alias_options.end())
2137 {
2138 m_alias_options.erase (pos);
2139 }
2140}
2141
2142void
2143CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2144{
2145 m_alias_options[alias_name] = option_arg_vector_sp;
2146}
2147
2148bool
2149CommandInterpreter::HasCommands ()
2150{
2151 return (!m_command_dict.empty());
2152}
2153
2154bool
2155CommandInterpreter::HasAliases ()
2156{
2157 return (!m_alias_dict.empty());
2158}
2159
2160bool
2161CommandInterpreter::HasUserCommands ()
2162{
2163 return (!m_user_dict.empty());
2164}
2165
2166bool
2167CommandInterpreter::HasAliasOptions ()
2168{
2169 return (!m_alias_options.empty());
2170}
2171
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002172void
Caroline Tice4ab31c92010-10-12 21:57:09 +00002173CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2174 const char *alias_name,
2175 Args &cmd_args,
Caroline Ticed9d63362010-12-07 19:58:26 +00002176 std::string &raw_input_string,
Caroline Tice4ab31c92010-10-12 21:57:09 +00002177 CommandReturnObject &result)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002178{
2179 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Ticed9d63362010-12-07 19:58:26 +00002180
2181 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002182
Caroline Ticed9d63362010-12-07 19:58:26 +00002183 // Make sure that the alias name is the 0th element in cmd_args
2184 std::string alias_name_str = alias_name;
2185 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2186 cmd_args.Unshift (alias_name);
2187
2188 Args new_args (alias_cmd_obj->GetCommandName());
2189 if (new_args.GetArgumentCount() == 2)
2190 new_args.Shift();
2191
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002192 if (option_arg_vector_sp.get())
2193 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002194 if (wants_raw_input)
2195 {
2196 // We have a command that both has command options and takes raw input. Make *sure* it has a
2197 // " -- " in the right place in the raw_input_string.
2198 size_t pos = raw_input_string.find(" -- ");
2199 if (pos == std::string::npos)
2200 {
2201 // None found; assume it goes at the beginning of the raw input string
2202 raw_input_string.insert (0, " -- ");
2203 }
2204 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002205
2206 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2207 int old_size = cmd_args.GetArgumentCount();
Caroline Tice4ab31c92010-10-12 21:57:09 +00002208 std::vector<bool> used (old_size + 1, false);
2209
2210 used[0] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002211
2212 for (int i = 0; i < option_arg_vector->size(); ++i)
2213 {
2214 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Ticed9d63362010-12-07 19:58:26 +00002215 OptionArgValue value_pair = option_pair.second;
2216 int value_type = value_pair.first;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002217 std::string option = option_pair.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00002218 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002219 if (option.compare ("<argument>") == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002220 {
2221 if (!wants_raw_input
2222 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2223 new_args.AppendArgument (value.c_str());
2224 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002225 else
2226 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002227 if (value_type != optional_argument)
2228 new_args.AppendArgument (option.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002229 if (value.compare ("<no-argument>") != 0)
2230 {
2231 int index = GetOptionArgumentPosition (value.c_str());
2232 if (index == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002233 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002234 // value was NOT a positional argument; must be a real value
Caroline Ticed9d63362010-12-07 19:58:26 +00002235 if (value_type != optional_argument)
2236 new_args.AppendArgument (value.c_str());
2237 else
2238 {
2239 char buffer[255];
2240 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2241 new_args.AppendArgument (buffer);
2242 }
2243
2244 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002245 else if (index >= cmd_args.GetArgumentCount())
2246 {
2247 result.AppendErrorWithFormat
2248 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2249 index);
2250 result.SetStatus (eReturnStatusFailed);
2251 return;
2252 }
2253 else
2254 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002255 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2256 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2257 if (strpos != std::string::npos)
2258 {
2259 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2260 }
2261
2262 if (value_type != optional_argument)
2263 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2264 else
2265 {
2266 char buffer[255];
2267 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2268 cmd_args.GetArgumentAtIndex (index));
2269 new_args.AppendArgument (buffer);
2270 }
Caroline Tice4ab31c92010-10-12 21:57:09 +00002271 used[index] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002272 }
2273 }
2274 }
2275 }
2276
2277 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2278 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002279 if (!used[j] && !wants_raw_input)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002280 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2281 }
2282
2283 cmd_args.Clear();
2284 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2285 }
2286 else
2287 {
2288 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Ticed9d63362010-12-07 19:58:26 +00002289 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2290 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2291 // input string.
2292 if (wants_raw_input)
2293 {
2294 cmd_args.Clear();
2295 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2296 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002297 return;
2298 }
2299
2300 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2301 return;
2302}
2303
2304
2305int
2306CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2307{
2308 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2309 // of zero.
2310
2311 char *cptr = (char *) in_string;
2312
2313 // Does it start with '%'
2314 if (cptr[0] == '%')
2315 {
2316 ++cptr;
2317
2318 // Is the rest of it entirely digits?
2319 if (isdigit (cptr[0]))
2320 {
2321 const char *start = cptr;
2322 while (isdigit (cptr[0]))
2323 ++cptr;
2324
2325 // We've gotten to the end of the digits; are we at the end of the string?
2326 if (cptr[0] == '\0')
2327 position = atoi (start);
2328 }
2329 }
2330
2331 return position;
2332}
2333
2334void
2335CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2336{
Jim Ingham16e0c682011-08-12 23:34:31 +00002337 FileSpec init_file;
Greg Clayton14a35512011-09-11 00:01:44 +00002338 if (in_cwd)
Jim Ingham16e0c682011-08-12 23:34:31 +00002339 {
Greg Clayton14a35512011-09-11 00:01:44 +00002340 // In the current working directory we don't load any program specific
2341 // .lldbinit files, we only look for a "./.lldbinit" file.
2342 if (m_skip_lldbinit_files)
2343 return;
2344
2345 init_file.SetFile ("./.lldbinit", true);
Jim Ingham16e0c682011-08-12 23:34:31 +00002346 }
Greg Clayton14a35512011-09-11 00:01:44 +00002347 else
Jim Ingham16e0c682011-08-12 23:34:31 +00002348 {
Greg Clayton14a35512011-09-11 00:01:44 +00002349 // If we aren't looking in the current working directory we are looking
2350 // in the home directory. We will first see if there is an application
2351 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2352 // "-" and the name of the program. If this file doesn't exist, we fall
2353 // back to just the "~/.lldbinit" file. We also obey any requests to not
2354 // load the init files.
2355 const char *init_file_path = "~/.lldbinit";
2356
2357 if (m_skip_app_init_files == false)
2358 {
2359 FileSpec program_file_spec (Host::GetProgramFileSpec());
2360 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham16e0c682011-08-12 23:34:31 +00002361
Greg Clayton14a35512011-09-11 00:01:44 +00002362 if (program_name)
2363 {
2364 char program_init_file_name[PATH_MAX];
2365 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2366 init_file.SetFile (program_init_file_name, true);
2367 if (!init_file.Exists())
2368 init_file.Clear();
2369 }
2370 }
2371
2372 if (!init_file && !m_skip_lldbinit_files)
2373 init_file.SetFile (init_file_path, true);
2374 }
2375
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002376 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2377 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2378
2379 if (init_file.Exists())
2380 {
Jim Inghame16c50a2011-02-18 00:54:25 +00002381 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2382 bool stop_on_continue = true;
2383 bool stop_on_error = false;
2384 bool echo_commands = false;
2385 bool print_results = false;
2386
Enrico Granata5f5ab602012-05-31 01:09:06 +00002387 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002388 }
2389 else
2390 {
2391 // nothing to be done if the file doesn't exist
2392 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2393 }
2394}
2395
Greg Clayton8b82f082011-04-12 05:54:46 +00002396PlatformSP
2397CommandInterpreter::GetPlatform (bool prefer_target_platform)
2398{
2399 PlatformSP platform_sp;
Greg Claytonc14ee322011-09-22 04:58:26 +00002400 if (prefer_target_platform)
2401 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002402 ExecutionContext exe_ctx(GetExecutionContext());
2403 Target *target = exe_ctx.GetTargetPtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002404 if (target)
2405 platform_sp = target->GetPlatform();
2406 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002407
2408 if (!platform_sp)
2409 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2410 return platform_sp;
2411}
2412
Jim Inghame16c50a2011-02-18 00:54:25 +00002413void
Jim Inghambad87fe2011-03-11 01:51:49 +00002414CommandInterpreter::HandleCommands (const StringList &commands,
Jim Inghame16c50a2011-02-18 00:54:25 +00002415 ExecutionContext *override_context,
2416 bool stop_on_continue,
2417 bool stop_on_error,
2418 bool echo_commands,
2419 bool print_results,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002420 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002421 CommandReturnObject &result)
2422{
2423 size_t num_lines = commands.GetSize();
Jim Inghame16c50a2011-02-18 00:54:25 +00002424
2425 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2426 // Make sure you reset this value anywhere you return from the function.
2427
2428 bool old_async_execution = m_debugger.GetAsyncExecution();
2429
2430 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2431 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2432
2433 if (override_context != NULL)
Greg Clayton8b82f082011-04-12 05:54:46 +00002434 UpdateExecutionContext (override_context);
Jim Inghame16c50a2011-02-18 00:54:25 +00002435
2436 if (!stop_on_continue)
2437 {
2438 m_debugger.SetAsyncExecution (false);
2439 }
2440
2441 for (int idx = 0; idx < num_lines; idx++)
2442 {
2443 const char *cmd = commands.GetStringAtIndex(idx);
2444 if (cmd[0] == '\0')
2445 continue;
2446
Jim Inghame16c50a2011-02-18 00:54:25 +00002447 if (echo_commands)
2448 {
2449 result.AppendMessageWithFormat ("%s %s\n",
2450 GetPrompt(),
2451 cmd);
2452 }
2453
Greg Clayton9d0402b2011-02-20 02:15:07 +00002454 CommandReturnObject tmp_result;
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002455 // If override_context is not NULL, pass no_context_switching = true for
2456 // HandleCommand() since we updated our context already.
Enrico Granata5f5ab602012-05-31 01:09:06 +00002457 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002458 NULL, /* override_context */
2459 true, /* repeat_on_empty_command */
2460 override_context != NULL /* no_context_switching */);
Jim Inghame16c50a2011-02-18 00:54:25 +00002461
2462 if (print_results)
2463 {
2464 if (tmp_result.Succeeded())
Jim Ingham85e8b812011-02-19 02:53:09 +00002465 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Inghame16c50a2011-02-18 00:54:25 +00002466 }
2467
2468 if (!success || !tmp_result.Succeeded())
2469 {
Jim Inghama5038812012-04-24 02:25:07 +00002470 const char *error_msg = tmp_result.GetErrorData();
2471 if (error_msg == NULL || error_msg[0] == '\0')
2472 error_msg = "<unknown error>.\n";
Jim Inghame16c50a2011-02-18 00:54:25 +00002473 if (stop_on_error)
2474 {
Jim Inghama5038812012-04-24 02:25:07 +00002475 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2476 idx, cmd, error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002477 result.SetStatus (eReturnStatusFailed);
2478 m_debugger.SetAsyncExecution (old_async_execution);
2479 return;
2480 }
2481 else if (print_results)
2482 {
Jim Inghama5038812012-04-24 02:25:07 +00002483 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Inghame16c50a2011-02-18 00:54:25 +00002484 idx + 1,
2485 cmd,
Jim Inghama5038812012-04-24 02:25:07 +00002486 error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002487 }
2488 }
2489
Caroline Tice969ed3d2011-05-02 20:41:46 +00002490 if (result.GetImmediateOutputStream())
2491 result.GetImmediateOutputStream()->Flush();
2492
2493 if (result.GetImmediateErrorStream())
2494 result.GetImmediateErrorStream()->Flush();
2495
Jim Inghame16c50a2011-02-18 00:54:25 +00002496 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2497 // could be running (for instance in Breakpoint Commands.
2498 // So we check the return value to see if it is has running in it.
2499 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2500 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2501 {
2502 if (stop_on_continue)
2503 {
2504 // If we caused the target to proceed, and we're going to stop in that case, set the
2505 // status in our real result before returning. This is an error if the continue was not the
2506 // last command in the set of commands to be run.
2507 if (idx != num_lines - 1)
2508 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2509 idx + 1, cmd);
2510 else
2511 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2512
2513 result.SetStatus(tmp_result.GetStatus());
2514 m_debugger.SetAsyncExecution (old_async_execution);
2515
2516 return;
2517 }
2518 }
2519
2520 }
2521
2522 result.SetStatus (eReturnStatusSuccessFinishResult);
2523 m_debugger.SetAsyncExecution (old_async_execution);
2524
2525 return;
2526}
2527
2528void
2529CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2530 ExecutionContext *context,
2531 bool stop_on_continue,
2532 bool stop_on_error,
2533 bool echo_command,
2534 bool print_result,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002535 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002536 CommandReturnObject &result)
2537{
2538 if (cmd_file.Exists())
2539 {
2540 bool success;
2541 StringList commands;
2542 success = commands.ReadFileLines(cmd_file);
2543 if (!success)
2544 {
2545 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2546 result.SetStatus (eReturnStatusFailed);
2547 return;
2548 }
Enrico Granata5f5ab602012-05-31 01:09:06 +00002549 m_command_source_depth++;
2550 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2551 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002552 }
2553 else
2554 {
2555 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2556 cmd_file.GetFilename().AsCString());
2557 result.SetStatus (eReturnStatusFailed);
2558 return;
2559 }
2560}
2561
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002562ScriptInterpreter *
Enrico Granatab5887262012-10-29 21:18:03 +00002563CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002564{
Enrico Granatab5887262012-10-29 21:18:03 +00002565 if (m_script_interpreter_ap.get() != NULL)
2566 return m_script_interpreter_ap.get();
2567
2568 if (!can_create)
2569 return NULL;
2570
Enrico Granataa29bdad2012-07-10 18:23:48 +00002571 // <rdar://problem/11751427>
2572 // we need to protect the initialization of the script interpreter
2573 // otherwise we could end up with two threads both trying to create
2574 // their instance of it, and for some languages (e.g. Python)
2575 // this is a bulletproof recipe for disaster!
2576 // this needs to be a function-level static because multiple Debugger instances living in the same process
2577 // still need to be isolated and not try to initialize Python concurrently
Enrico Granata8b95df22012-07-10 19:04:14 +00002578 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2579 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granataa29bdad2012-07-10 18:23:48 +00002580
Enrico Granatab5887262012-10-29 21:18:03 +00002581 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
2582 if (log)
2583 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton66111032010-06-23 01:19:29 +00002584
Caroline Tice2f88aad2011-01-14 00:29:16 +00002585 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2586 switch (script_lang)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002587 {
Greg Claytondce502e2011-11-04 03:34:56 +00002588 case eScriptLanguagePython:
2589#ifndef LLDB_DISABLE_PYTHON
2590 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2591 break;
2592#else
2593 // Fall through to the None case when python is disabled
2594#endif
Caroline Tice2f88aad2011-01-14 00:29:16 +00002595 case eScriptLanguageNone:
2596 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2597 break;
Caroline Tice2f88aad2011-01-14 00:29:16 +00002598 };
2599
2600 return m_script_interpreter_ap.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002601}
2602
2603
2604
2605bool
2606CommandInterpreter::GetSynchronous ()
2607{
2608 return m_synchronous_execution;
2609}
2610
2611void
2612CommandInterpreter::SetSynchronous (bool value)
2613{
Johnny Chenc066ab42010-10-14 01:22:03 +00002614 m_synchronous_execution = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002615}
2616
2617void
2618CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2619 const char *word_text,
2620 const char *separator,
2621 const char *help_text,
2622 uint32_t max_word_len)
2623{
Greg Claytona7015092010-09-18 01:14:36 +00002624 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2625
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002626 int indent_size = max_word_len + strlen (separator) + 2;
2627
2628 strm.IndentMore (indent_size);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002629
2630 StreamString text_strm;
2631 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2632
2633 size_t len = text_strm.GetSize();
2634 const char *text = text_strm.GetData();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002635 if (text[len - 1] == '\n')
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002636 {
2637 text_strm.EOL();
2638 len = text_strm.GetSize();
2639 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002640
2641 if (len < max_columns)
2642 {
2643 // Output it as a single line.
2644 strm.Printf ("%s", text);
2645 }
2646 else
2647 {
2648 // We need to break it up into multiple lines.
2649 bool first_line = true;
2650 int text_width;
2651 int start = 0;
2652 int end = start;
2653 int final_end = strlen (text);
2654 int sub_len;
2655
2656 while (end < final_end)
2657 {
2658 if (first_line)
2659 text_width = max_columns - 1;
2660 else
2661 text_width = max_columns - indent_size - 1;
2662
2663 // Don't start the 'text' on a space, since we're already outputting the indentation.
2664 if (!first_line)
2665 {
2666 while ((start < final_end) && (text[start] == ' '))
2667 start++;
2668 }
2669
2670 end = start + text_width;
2671 if (end > final_end)
2672 end = final_end;
2673 else
2674 {
2675 // If we're not at the end of the text, make sure we break the line on white space.
2676 while (end > start
2677 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2678 end--;
Greg Clayton67cc0632012-08-22 17:17:09 +00002679 assert (end > 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002680 }
2681
2682 sub_len = end - start;
2683 if (start != 0)
2684 strm.EOL();
2685 if (!first_line)
2686 strm.Indent();
2687 else
2688 first_line = false;
2689 assert (start <= final_end);
2690 assert (start + sub_len <= final_end);
2691 if (sub_len > 0)
2692 strm.Write (text + start, sub_len);
2693 start = end + 1;
2694 }
2695 }
2696 strm.EOL();
2697 strm.IndentLess(indent_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002698}
2699
2700void
Enrico Granata82a7d982011-07-07 00:38:40 +00002701CommandInterpreter::OutputHelpText (Stream &strm,
2702 const char *word_text,
2703 const char *separator,
2704 const char *help_text,
2705 uint32_t max_word_len)
2706{
2707 int indent_size = max_word_len + strlen (separator) + 2;
2708
2709 strm.IndentMore (indent_size);
2710
2711 StreamString text_strm;
2712 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2713
2714 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata82a7d982011-07-07 00:38:40 +00002715
2716 size_t len = text_strm.GetSize();
2717 const char *text = text_strm.GetData();
2718
2719 uint32_t chars_left = max_columns;
2720
2721 for (uint32_t i = 0; i < len; i++)
2722 {
2723 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2724 {
Enrico Granata82a7d982011-07-07 00:38:40 +00002725 chars_left = max_columns - indent_size;
2726 strm.EOL();
2727 strm.Indent();
2728 }
2729 else
2730 {
2731 strm.PutChar(text[i]);
2732 chars_left--;
2733 }
2734
2735 }
2736
2737 strm.EOL();
2738 strm.IndentLess(indent_size);
2739}
2740
2741void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002742CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2743 StringList &commands_help)
2744{
2745 CommandObject::CommandMap::const_iterator pos;
2746
2747 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2748 {
2749 const char *command_name = pos->first.c_str();
2750 CommandObject *cmd_obj = pos->second.get();
2751
Greg Claytona7015092010-09-18 01:14:36 +00002752 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002753 {
2754 commands_found.AppendString (command_name);
2755 commands_help.AppendString (cmd_obj->GetHelp());
2756 }
2757
2758 if (cmd_obj->IsMultiwordObject())
Greg Clayton998255b2012-10-13 02:07:45 +00002759 cmd_obj->AproposAllSubCommands (command_name,
2760 search_word,
2761 commands_found,
2762 commands_help);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002763
2764 }
2765}
Greg Clayton8b82f082011-04-12 05:54:46 +00002766
2767
2768void
2769CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2770{
Greg Clayton8b82f082011-04-12 05:54:46 +00002771 if (override_context != NULL)
2772 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002773 m_exe_ctx_ref = *override_context;
Greg Clayton8b82f082011-04-12 05:54:46 +00002774 }
2775 else
2776 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002777 const bool adopt_selected = true;
2778 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Clayton8b82f082011-04-12 05:54:46 +00002779 }
2780}
2781
Jim Inghama5a97eb2011-07-12 03:12:18 +00002782void
2783CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2784{
2785 DumpHistory (stream, 0, count - 1);
2786}
2787
2788void
2789CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2790{
Greg Clayton5521f992011-10-28 21:38:01 +00002791 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2792 for (size_t i = start; i < last_idx; i++)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002793 {
2794 if (!m_command_history[i].empty())
2795 {
2796 stream.Indent();
Greg Clayton5521f992011-10-28 21:38:01 +00002797 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Inghama5a97eb2011-07-12 03:12:18 +00002798 }
2799 }
2800}
2801
2802const char *
2803CommandInterpreter::FindHistoryString (const char *input_str) const
2804{
2805 if (input_str[0] != m_repeat_char)
2806 return NULL;
2807 if (input_str[1] == '-')
2808 {
2809 bool success;
2810 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2811 if (!success)
2812 return NULL;
2813 if (idx > m_command_history.size())
2814 return NULL;
2815 idx = m_command_history.size() - idx;
2816 return m_command_history[idx].c_str();
2817
2818 }
2819 else if (input_str[1] == m_repeat_char)
2820 {
2821 if (m_command_history.empty())
2822 return NULL;
2823 else
2824 return m_command_history.back().c_str();
2825 }
2826 else
2827 {
2828 bool success;
2829 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2830 if (!success)
2831 return NULL;
2832 if (idx >= m_command_history.size())
2833 return NULL;
2834 return m_command_history[idx].c_str();
2835 }
2836}