blob: 56c8f8c0ad6a0868662a5bd29911ed88931cb97a [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#include <stdlib.h>
15
Greg Clayton4a33d312011-06-23 17:59:56 +000016#include "CommandObjectScript.h"
Peter Collingbourne08405b62011-06-23 20:37:26 +000017#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000018
Eli Friedman3afb70c2010-06-13 02:17:17 +000019#include "../Commands/CommandObjectApropos.h"
20#include "../Commands/CommandObjectArgs.h"
21#include "../Commands/CommandObjectBreakpoint.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000022#include "../Commands/CommandObjectDisassemble.h"
23#include "../Commands/CommandObjectExpression.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000024#include "../Commands/CommandObjectFrame.h"
Greg Clayton44d93782014-01-27 23:43:24 +000025#include "../Commands/CommandObjectGUI.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectHelp.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000027#include "../Commands/CommandObjectLog.h"
28#include "../Commands/CommandObjectMemory.h"
Greg Claytonded470d2011-03-19 01:12:21 +000029#include "../Commands/CommandObjectPlatform.h"
Enrico Granata21dfcd92012-09-28 23:57:51 +000030#include "../Commands/CommandObjectPlugin.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000031#include "../Commands/CommandObjectProcess.h"
32#include "../Commands/CommandObjectQuit.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectRegister.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectSettings.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSource.h"
Jim Inghamebc09c32010-07-07 03:36:20 +000036#include "../Commands/CommandObjectCommands.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000037#include "../Commands/CommandObjectSyntax.h"
38#include "../Commands/CommandObjectTarget.h"
39#include "../Commands/CommandObjectThread.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000040#include "../Commands/CommandObjectType.h"
Johnny Chen31c39da2010-12-23 20:21:44 +000041#include "../Commands/CommandObjectVersion.h"
Johnny Chenf04ee932011-09-22 18:04:58 +000042#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043
Greg Clayton7d2ef162013-03-29 17:03:23 +000044
Chris Lattner30fdc8d2010-06-08 16:52:24 +000045#include "lldb/Core/Debugger.h"
Enrico Granatab5887262012-10-29 21:18:03 +000046#include "lldb/Core/Log.h"
Greg Claytonf0066ad2014-05-02 00:45:31 +000047#include "lldb/Core/State.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048#include "lldb/Core/Stream.h"
Greg Clayton44d93782014-01-27 23:43:24 +000049#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000050#include "lldb/Core/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000051
Greg Clayton44d93782014-01-27 23:43:24 +000052#include "lldb/Host/Editline.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000053#include "lldb/Host/Host.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000054#include "lldb/Host/HostInfo.h"
Enrico Granatab5887262012-10-29 21:18:03 +000055
56#include "lldb/Interpreter/Args.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000057#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000058#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000059#include "lldb/Interpreter/CommandReturnObject.h"
Enrico Granatab5887262012-10-29 21:18:03 +000060#include "lldb/Interpreter/Options.h"
61#include "lldb/Interpreter/ScriptInterpreterNone.h"
62#include "lldb/Interpreter/ScriptInterpreterPython.h"
63
64
Chris Lattner30fdc8d2010-06-08 16:52:24 +000065#include "lldb/Target/Process.h"
66#include "lldb/Target/Thread.h"
67#include "lldb/Target/TargetList.h"
68
Enrico Granatab5887262012-10-29 21:18:03 +000069#include "lldb/Utility/CleanUp.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000070
Zachary Turnera21fee02014-08-21 21:49:24 +000071#include "llvm/ADT/SmallString.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000072#include "llvm/ADT/STLExtras.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000073#include "llvm/Support/Path.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000074
Chris Lattner30fdc8d2010-06-08 16:52:24 +000075using namespace lldb;
76using namespace lldb_private;
77
Greg Clayton754a9362012-08-23 00:22:02 +000078
79static PropertyDefinition
80g_properties[] =
81{
Ed Masted78c9572014-04-20 00:31:37 +000082 { "expand-regex-aliases", OptionValue::eTypeBoolean, true, false, nullptr, nullptr, "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." },
83 { "prompt-on-quit", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, LLDB will prompt you before quitting if there are any live processes being debugged. If false, LLDB will quit without asking in any case." },
84 { "stop-command-source-on-error", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, LLDB will stop running a 'command source' script upon encountering an error." },
85 { nullptr , OptionValue::eTypeInvalid, true, 0 , nullptr, nullptr, nullptr }
Greg Clayton754a9362012-08-23 00:22:02 +000086};
87
88enum
89{
Enrico Granatabcba2b22013-01-17 21:36:19 +000090 ePropertyExpandRegexAliases = 0,
Enrico Granata012d4fc2013-06-11 01:26:35 +000091 ePropertyPromptOnQuit = 1,
92 ePropertyStopCmdSourceOnError = 2
Greg Clayton754a9362012-08-23 00:22:02 +000093};
94
Jim Ingham4bddaeb2012-02-16 06:50:00 +000095ConstString &
96CommandInterpreter::GetStaticBroadcasterClass ()
97{
98 static ConstString class_name ("lldb.commandInterpreter");
99 return class_name;
100}
101
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000102CommandInterpreter::CommandInterpreter
103(
Greg Clayton66111032010-06-23 01:19:29 +0000104 Debugger &debugger,
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000105 ScriptLanguage script_language,
Greg Clayton66111032010-06-23 01:19:29 +0000106 bool synchronous_execution
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000107) :
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000108 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton754a9362012-08-23 00:22:02 +0000109 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton44d93782014-01-27 23:43:24 +0000110 IOHandlerDelegate (IOHandlerDelegate::Completion::LLDBCommand),
Greg Clayton66111032010-06-23 01:19:29 +0000111 m_debugger (debugger),
Greg Clayton6eee5aa2010-10-11 01:05:37 +0000112 m_synchronous_execution (synchronous_execution),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000113 m_skip_lldbinit_files (false),
Jim Ingham16e0c682011-08-12 23:34:31 +0000114 m_skip_app_init_files (false),
Jim Inghame16c50a2011-02-18 00:54:25 +0000115 m_script_interpreter_ap (),
Greg Clayton44d93782014-01-27 23:43:24 +0000116 m_command_io_handler_sp (),
Caroline Ticed61c10b2011-06-16 16:27:19 +0000117 m_comment_char ('#'),
Johnny Chen4ac1d9e2012-08-09 22:06:10 +0000118 m_batch_command_mode (false),
Enrico Granata5f5ab602012-05-31 01:09:06 +0000119 m_truncation_warning(eNoTruncation),
120 m_command_source_depth (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000121{
Greg Clayton67cc0632012-08-22 17:17:09 +0000122 debugger.SetScriptLanguage (script_language);
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000123 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
124 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton67cc0632012-08-22 17:17:09 +0000125 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000126 CheckInWithManager ();
Greg Clayton754a9362012-08-23 00:22:02 +0000127 m_collection_sp->Initialize (g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000128}
129
Greg Clayton754a9362012-08-23 00:22:02 +0000130bool
131CommandInterpreter::GetExpandRegexAliases () const
132{
133 const uint32_t idx = ePropertyExpandRegexAliases;
Ed Masted78c9572014-04-20 00:31:37 +0000134 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000135}
136
Enrico Granatabcba2b22013-01-17 21:36:19 +0000137bool
138CommandInterpreter::GetPromptOnQuit () const
139{
140 const uint32_t idx = ePropertyPromptOnQuit;
Ed Masted78c9572014-04-20 00:31:37 +0000141 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000142}
Greg Clayton754a9362012-08-23 00:22:02 +0000143
Enrico Granata012d4fc2013-06-11 01:26:35 +0000144bool
145CommandInterpreter::GetStopCmdSourceOnError () const
146{
147 const uint32_t idx = ePropertyStopCmdSourceOnError;
Ed Masted78c9572014-04-20 00:31:37 +0000148 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000149}
150
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000151void
152CommandInterpreter::Initialize ()
153{
154 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
155
156 CommandReturnObject result;
157
158 LoadCommandDictionary ();
159
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000160 // Set up some initial aliases.
Caroline Ticeca90c472011-05-06 21:37:15 +0000161 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
162 if (cmd_obj_sp)
163 {
164 AddAlias ("q", cmd_obj_sp);
165 AddAlias ("exit", cmd_obj_sp);
166 }
Sean Callanan247e62a2012-05-04 23:15:02 +0000167
Johnny Chen6d675242012-08-24 18:15:45 +0000168 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callanan247e62a2012-05-04 23:15:02 +0000169 if (cmd_obj_sp)
170 {
171 AddAlias ("attach", cmd_obj_sp);
172 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000173
Johnny Chen6d675242012-08-24 18:15:45 +0000174 cmd_obj_sp = GetCommandSPExact ("process detach",false);
175 if (cmd_obj_sp)
176 {
177 AddAlias ("detach", cmd_obj_sp);
178 }
179
Caroline Ticeca90c472011-05-06 21:37:15 +0000180 cmd_obj_sp = GetCommandSPExact ("process continue", false);
181 if (cmd_obj_sp)
182 {
183 AddAlias ("c", cmd_obj_sp);
184 AddAlias ("continue", cmd_obj_sp);
185 }
186
187 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
188 if (cmd_obj_sp)
189 AddAlias ("b", cmd_obj_sp);
190
Jim Inghamca36cd12012-10-05 19:16:31 +0000191 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
192 if (cmd_obj_sp)
193 AddAlias ("tbreak", cmd_obj_sp);
194
Caroline Ticeca90c472011-05-06 21:37:15 +0000195 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
196 if (cmd_obj_sp)
Jason Molendaf385f122011-10-22 00:47:41 +0000197 {
198 AddAlias ("stepi", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000199 AddAlias ("si", cmd_obj_sp);
Jason Molendaf385f122011-10-22 00:47:41 +0000200 }
201
202 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
203 if (cmd_obj_sp)
204 {
205 AddAlias ("nexti", cmd_obj_sp);
206 AddAlias ("ni", cmd_obj_sp);
207 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000208
209 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
210 if (cmd_obj_sp)
211 {
212 AddAlias ("s", cmd_obj_sp);
213 AddAlias ("step", cmd_obj_sp);
214 }
215
216 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
217 if (cmd_obj_sp)
218 {
219 AddAlias ("n", cmd_obj_sp);
220 AddAlias ("next", cmd_obj_sp);
221 }
222
223 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
224 if (cmd_obj_sp)
225 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000226 AddAlias ("finish", cmd_obj_sp);
227 }
228
Jim Ingham6d6d1072011-12-02 01:12:59 +0000229 cmd_obj_sp = GetCommandSPExact ("frame select", false);
230 if (cmd_obj_sp)
231 {
232 AddAlias ("f", cmd_obj_sp);
233 }
234
Jim Inghamca36cd12012-10-05 19:16:31 +0000235 cmd_obj_sp = GetCommandSPExact ("thread select", false);
236 if (cmd_obj_sp)
237 {
238 AddAlias ("t", cmd_obj_sp);
239 }
240
Richard Mittonf86248d2013-09-12 02:20:34 +0000241 cmd_obj_sp = GetCommandSPExact ("_regexp-jump",false);
242 if (cmd_obj_sp)
243 {
244 AddAlias ("j", cmd_obj_sp);
245 AddAlias ("jump", cmd_obj_sp);
246 }
247
Greg Clayton6bade322013-02-01 23:33:03 +0000248 cmd_obj_sp = GetCommandSPExact ("_regexp-list", false);
Caroline Ticeca90c472011-05-06 21:37:15 +0000249 if (cmd_obj_sp)
250 {
251 AddAlias ("l", cmd_obj_sp);
252 AddAlias ("list", cmd_obj_sp);
253 }
254
Greg Claytonef5651d2013-02-12 18:52:24 +0000255 cmd_obj_sp = GetCommandSPExact ("_regexp-env", false);
256 if (cmd_obj_sp)
257 {
258 AddAlias ("env", cmd_obj_sp);
259 }
260
Caroline Ticeca90c472011-05-06 21:37:15 +0000261 cmd_obj_sp = GetCommandSPExact ("memory read", false);
262 if (cmd_obj_sp)
263 AddAlias ("x", cmd_obj_sp);
264
265 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
266 if (cmd_obj_sp)
267 AddAlias ("up", cmd_obj_sp);
268
269 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
270 if (cmd_obj_sp)
271 AddAlias ("down", cmd_obj_sp);
272
Jason Molenda0c8e0062011-10-25 02:11:20 +0000273 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000274 if (cmd_obj_sp)
275 AddAlias ("display", cmd_obj_sp);
Jim Ingham7e18e422011-10-24 18:37:00 +0000276
277 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
278 if (cmd_obj_sp)
279 AddAlias ("dis", cmd_obj_sp);
280
281 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
282 if (cmd_obj_sp)
283 AddAlias ("di", cmd_obj_sp);
284
285
Jason Molendabc7748b2011-10-22 01:30:52 +0000286
Jason Molenda0c8e0062011-10-25 02:11:20 +0000287 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000288 if (cmd_obj_sp)
289 AddAlias ("undisplay", cmd_obj_sp);
290
Jim Ingham71bf2992012-10-10 16:51:31 +0000291 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
292 if (cmd_obj_sp)
293 AddAlias ("bt", cmd_obj_sp);
294
Caroline Ticeca90c472011-05-06 21:37:15 +0000295 cmd_obj_sp = GetCommandSPExact ("target create", false);
296 if (cmd_obj_sp)
297 AddAlias ("file", cmd_obj_sp);
298
299 cmd_obj_sp = GetCommandSPExact ("target modules", false);
300 if (cmd_obj_sp)
301 AddAlias ("image", cmd_obj_sp);
302
303
304 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghamffba2292011-03-22 02:29:32 +0000305
Caroline Ticeca90c472011-05-06 21:37:15 +0000306 cmd_obj_sp = GetCommandSPExact ("expression", false);
307 if (cmd_obj_sp)
Sean Callanan90e579f2013-04-17 17:23:58 +0000308 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000309 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
310 AddAlias ("p", cmd_obj_sp);
311 AddAlias ("print", cmd_obj_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000312 AddAlias ("call", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000313 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
314 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000315 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000316
317 alias_arguments_vector_sp.reset (new OptionArgVector);
Greg Clayton9e57dcd2013-05-15 01:03:08 +0000318 ProcessAliasOptionsArgs (cmd_obj_sp, "-O -- ", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000319 AddAlias ("po", cmd_obj_sp);
320 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
321 }
322
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000323 cmd_obj_sp = GetCommandSPExact ("process kill", false);
324 if (cmd_obj_sp)
Greg Claytone86fd742012-09-27 00:02:27 +0000325 {
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000326 AddAlias ("kill", cmd_obj_sp);
Greg Claytone86fd742012-09-27 00:02:27 +0000327 }
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000328
Caroline Ticeca90c472011-05-06 21:37:15 +0000329 cmd_obj_sp = GetCommandSPExact ("process launch", false);
330 if (cmd_obj_sp)
331 {
332 alias_arguments_vector_sp.reset (new OptionArgVector);
Todd Fiala013434e2014-07-09 01:29:05 +0000333#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Jason Molenda85da3122012-07-06 02:46:23 +0000334 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
335#else
Ed Maste7c566672013-09-05 21:38:45 +0000336 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=" LLDB_DEFAULT_SHELL " --", alias_arguments_vector_sp);
Jason Molenda85da3122012-07-06 02:46:23 +0000337#endif
Caroline Ticeca90c472011-05-06 21:37:15 +0000338 AddAlias ("r", cmd_obj_sp);
339 AddAlias ("run", cmd_obj_sp);
340 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
341 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
342 }
Greg Clayton843d62d2012-03-29 21:47:51 +0000343
344 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
345 if (cmd_obj_sp)
346 {
347 AddAlias ("add-dsym", cmd_obj_sp);
348 }
Sean Callananfc732752012-05-21 18:25:19 +0000349
350 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
351 if (cmd_obj_sp)
352 {
353 alias_arguments_vector_sp.reset (new OptionArgVector);
354 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
Jim Ingham06d282d2012-10-18 23:24:12 +0000355 AddAlias ("rbreak", cmd_obj_sp);
356 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
Sean Callananfc732752012-05-21 18:25:19 +0000357 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000358}
359
Greg Clayton0c4129f2014-04-25 00:35:14 +0000360void
361CommandInterpreter::Clear()
362{
363 m_command_io_handler_sp.reset();
Greg Claytoned6499f2014-04-25 23:55:12 +0000364
365 if (m_script_interpreter_ap)
366 m_script_interpreter_ap->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000367}
368
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000369const char *
370CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
371{
372 // This function has not yet been implemented.
373
374 // Look for any embedded script command
375 // If found,
376 // get interpreter object from the command dictionary,
377 // call execute_one_command on it,
378 // get the results as a string,
379 // substitute that string for current stuff.
380
381 return arg;
382}
383
384
385void
386CommandInterpreter::LoadCommandDictionary ()
387{
388 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
389
Caroline Ticedaccaa92010-09-20 20:44:43 +0000390 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000391
Greg Claytona7015092010-09-18 01:14:36 +0000392 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000393 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Johnny Chenb89982d2011-04-21 00:39:18 +0000394 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000395 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
396 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000397 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton44d93782014-01-27 23:43:24 +0000398 m_command_dict["gui"] = CommandObjectSP (new CommandObjectGUI (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000399 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000400 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
401 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonded470d2011-03-19 01:12:21 +0000402 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata21dfcd92012-09-28 23:57:51 +0000403 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000404 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000405 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000406 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000407 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000408 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Inghamebc09c32010-07-07 03:36:20 +0000409 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000410 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
411 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata223383e2011-08-16 23:24:13 +0000412 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen31c39da2010-12-23 20:21:44 +0000413 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chenf04ee932011-09-22 18:04:58 +0000414 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000415
Jim Inghamca36cd12012-10-05 19:16:31 +0000416 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
417 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
Greg Clayton722e8852013-02-08 02:54:24 +0000418 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
Greg Clayton1b3815c2013-01-30 00:18:29 +0000419 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000420 {"^(-.*)$", "breakpoint set %1"},
421 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
Greg Clayton722e8852013-02-08 02:54:24 +0000422 {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"},
Greg Clayton2d4b5122014-08-14 17:58:33 +0000423 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"}};
Jim Inghamca36cd12012-10-05 19:16:31 +0000424
Saleem Abdulrasool28606952014-06-27 05:17:41 +0000425 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000426
Greg Clayton7b0992d2013-04-18 22:45:39 +0000427 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytona7015092010-09-18 01:14:36 +0000428 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000429 "_regexp-break",
Johnny Chenb417dcd2012-08-23 00:32:22 +0000430 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000431 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
432 2,
433 CommandCompletions::eSymbolCompletion |
434 CommandCompletions::eSourceFileCompletion));
Jim Inghamca36cd12012-10-05 19:16:31 +0000435
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000436 if (break_regex_cmd_ap.get())
437 {
Jim Inghamca36cd12012-10-05 19:16:31 +0000438 bool success = true;
439 for (size_t i = 0; i < num_regexes; i++)
440 {
441 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
442 if (!success)
443 break;
444 }
445 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
446
447 if (success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000448 {
449 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
450 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
451 }
452 }
Jim Inghamffba2292011-03-22 02:29:32 +0000453
Greg Clayton7b0992d2013-04-18 22:45:39 +0000454 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamca36cd12012-10-05 19:16:31 +0000455 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
456 "_regexp-tbreak",
457 "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000458 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
459 2,
460 CommandCompletions::eSymbolCompletion |
461 CommandCompletions::eSourceFileCompletion));
Jim Inghamca36cd12012-10-05 19:16:31 +0000462
463 if (tbreak_regex_cmd_ap.get())
464 {
465 bool success = true;
466 for (size_t i = 0; i < num_regexes; i++)
467 {
468 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
469 char buffer[1024];
470 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
471 assert (num_printed < 1024);
472 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
473 if (!success)
474 break;
475 }
476 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
477
478 if (success)
479 {
480 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
481 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
482 }
483 }
484
Greg Clayton7b0992d2013-04-18 22:45:39 +0000485 std::unique_ptr<CommandObjectRegexCommand>
Johnny Chen6d675242012-08-24 18:15:45 +0000486 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
487 "_regexp-attach",
488 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000489 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]",
490 2));
Johnny Chen6d675242012-08-24 18:15:45 +0000491 if (attach_regex_cmd_ap.get())
492 {
Greg Clayton3cb4c7d2012-12-15 01:19:07 +0000493 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
494 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
495 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
496 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
Johnny Chen6d675242012-08-24 18:15:45 +0000497 {
498 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
499 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
500 }
501 }
502
Greg Clayton7b0992d2013-04-18 22:45:39 +0000503 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000504 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000505 "_regexp-down",
506 "Go down \"n\" frames in the stack (1 frame by default).",
507 "_regexp-down [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000508 if (down_regex_cmd_ap.get())
509 {
510 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
511 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
512 {
513 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
514 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
515 }
516 }
517
Greg Clayton7b0992d2013-04-18 22:45:39 +0000518 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000519 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000520 "_regexp-up",
521 "Go up \"n\" frames in the stack (1 frame by default).",
522 "_regexp-up [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000523 if (up_regex_cmd_ap.get())
524 {
525 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
526 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
527 {
528 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
529 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
530 }
531 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000532
Greg Clayton7b0992d2013-04-18 22:45:39 +0000533 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000534 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000535 "_regexp-display",
536 "Add an expression evaluation stop-hook.",
537 "_regexp-display expression", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000538 if (display_regex_cmd_ap.get())
539 {
540 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
541 {
542 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
543 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
544 }
545 }
546
Greg Clayton7b0992d2013-04-18 22:45:39 +0000547 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000548 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000549 "_regexp-undisplay",
550 "Remove an expression evaluation stop-hook.",
551 "_regexp-undisplay stop-hook-number", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000552 if (undisplay_regex_cmd_ap.get())
553 {
554 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
555 {
556 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
557 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
558 }
559 }
560
Greg Clayton7b0992d2013-04-18 22:45:39 +0000561 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000562 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000563 "gdb-remote",
564 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
565 "gdb-remote [<hostname>:]<portnum>", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000566 if (connect_gdb_remote_cmd_ap.get())
567 {
568 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
569 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
570 {
571 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
572 m_command_dict[command_sp->GetCommandName ()] = command_sp;
573 }
574 }
575
Greg Clayton7b0992d2013-04-18 22:45:39 +0000576 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000577 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
578 "kdp-remote",
Jason Molendaa7dcb332012-10-23 03:05:16 +0000579 "Connect to a remote KDP server. udp port 41139 is the default port number.",
580 "kdp-remote <hostname>[:<portnum>]", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000581 if (connect_kdp_remote_cmd_ap.get())
582 {
583 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molendac36b1842012-09-27 02:47:55 +0000584 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000585 {
586 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
587 m_command_dict[command_sp->GetCommandName ()] = command_sp;
588 }
589 }
590
Greg Clayton7b0992d2013-04-18 22:45:39 +0000591 std::unique_ptr<CommandObjectRegexCommand>
Jason Molenda4cddfed2012-10-05 05:29:32 +0000592 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jim Ingham71bf2992012-10-10 16:51:31 +0000593 "_regexp-bt",
Jason Molenda4cddfed2012-10-05 05:29:32 +0000594 "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.",
595 "bt [<digit>|all]", 2));
596 if (bt_regex_cmd_ap.get())
597 {
598 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
599 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
600 // so now "bt 3" is the preferred form, in line with gdb.
601 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
602 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
603 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
604 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
605 {
606 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
607 m_command_dict[command_sp->GetCommandName ()] = command_sp;
608 }
609 }
610
Greg Clayton7b0992d2013-04-18 22:45:39 +0000611 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton6bade322013-02-01 23:33:03 +0000612 list_regex_cmd_ap(new CommandObjectRegexCommand (*this,
613 "_regexp-list",
614 "Implements the GDB 'list' command in all of its forms except FILE:FUNCTION and maps them to the appropriate 'source list' commands.",
Ben Langmuiredb3b212013-09-26 20:00:01 +0000615 "_regexp-list [<line>]\n_regexp-list [<file>:<line>]\n_regexp-list [<file>:<line>]",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000616 2,
617 CommandCompletions::eSourceFileCompletion));
Greg Clayton6bade322013-02-01 23:33:03 +0000618 if (list_regex_cmd_ap.get())
619 {
620 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") &&
621 list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") &&
622 list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") &&
Greg Claytond9010962013-02-12 18:42:05 +0000623 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") &&
Greg Claytone4ca5152013-03-13 18:25:49 +0000624 list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") &&
Greg Clayton6bade322013-02-01 23:33:03 +0000625 list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") &&
626 list_regex_cmd_ap->AddRegexCommand("^$", "source list"))
627 {
628 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
629 m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp;
630 }
631 }
632
Greg Clayton7b0992d2013-04-18 22:45:39 +0000633 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytonef5651d2013-02-12 18:52:24 +0000634 env_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000635 "_regexp-env",
636 "Implements a shortcut to viewing and setting environment variables.",
637 "_regexp-env\n_regexp-env FOO=BAR", 2));
Greg Claytonef5651d2013-02-12 18:52:24 +0000638 if (env_regex_cmd_ap.get())
639 {
640 if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") &&
641 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1"))
642 {
643 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
644 m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp;
645 }
646 }
647
Richard Mittonf86248d2013-09-12 02:20:34 +0000648 std::unique_ptr<CommandObjectRegexCommand>
649 jump_regex_cmd_ap(new CommandObjectRegexCommand (*this,
650 "_regexp-jump",
651 "Sets the program counter to a new address.",
652 "_regexp-jump [<line>]\n"
653 "_regexp-jump [<+-lineoffset>]\n"
654 "_regexp-jump [<file>:<line>]\n"
655 "_regexp-jump [*<addr>]\n", 2));
656 if (jump_regex_cmd_ap.get())
657 {
658 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") &&
659 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") &&
660 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") &&
661 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1"))
662 {
663 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
664 m_command_dict[jump_regex_cmd_sp->GetCommandName ()] = jump_regex_cmd_sp;
665 }
666 }
667
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000668}
669
670int
671CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
672 StringList &matches)
673{
674 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
675
676 if (include_aliases)
677 {
678 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
679 }
680
681 return matches.GetSize();
682}
683
684CommandObjectSP
685CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
686{
687 CommandObject::CommandMap::iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +0000688 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000689
690 std::string cmd(cmd_cstr);
691
692 if (HasCommands())
693 {
694 pos = m_command_dict.find(cmd);
695 if (pos != m_command_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000696 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000697 }
698
699 if (include_aliases && HasAliases())
700 {
701 pos = m_alias_dict.find(cmd);
702 if (pos != m_alias_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000703 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000704 }
705
706 if (HasUserCommands())
707 {
708 pos = m_user_dict.find(cmd);
709 if (pos != m_user_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000710 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000711 }
712
Greg Claytonc7bece562013-01-25 18:06:21 +0000713 if (!exact && !command_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000714 {
Jim Ingham279a6c22010-07-06 22:46:59 +0000715 // We will only get into here if we didn't find any exact matches.
716
717 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
718
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000719 StringList local_matches;
Ed Masted78c9572014-04-20 00:31:37 +0000720 if (matches == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000721 matches = &local_matches;
722
Jim Ingham279a6c22010-07-06 22:46:59 +0000723 unsigned int num_cmd_matches = 0;
724 unsigned int num_alias_matches = 0;
725 unsigned int num_user_matches = 0;
726
727 // Look through the command dictionaries one by one, and if we get only one match from any of
728 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
729
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000730 if (HasCommands())
731 {
732 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
733 }
734
735 if (num_cmd_matches == 1)
736 {
737 cmd.assign(matches->GetStringAtIndex(0));
738 pos = m_command_dict.find(cmd);
739 if (pos != m_command_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000740 real_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000741 }
742
Jim Ingham490ac552010-06-24 20:28:42 +0000743 if (include_aliases && HasAliases())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000744 {
745 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
746
747 }
748
Jim Ingham279a6c22010-07-06 22:46:59 +0000749 if (num_alias_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000750 {
751 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
752 pos = m_alias_dict.find(cmd);
753 if (pos != m_alias_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000754 alias_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000755 }
756
Jim Ingham490ac552010-06-24 20:28:42 +0000757 if (HasUserCommands())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000758 {
759 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
760 }
761
Jim Ingham279a6c22010-07-06 22:46:59 +0000762 if (num_user_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000763 {
764 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
765
766 pos = m_user_dict.find (cmd);
767 if (pos != m_user_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000768 user_match_sp = pos->second;
769 }
770
771 // If we got exactly one match, return that, otherwise return the match list.
772
773 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
774 {
775 if (num_cmd_matches)
776 return real_match_sp;
777 else if (num_alias_matches)
778 return alias_match_sp;
779 else
780 return user_match_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000781 }
782 }
Greg Claytonc7bece562013-01-25 18:06:21 +0000783 else if (matches && command_sp)
Jim Ingham279a6c22010-07-06 22:46:59 +0000784 {
785 matches->AppendString (cmd_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000786 }
787
788
Greg Claytonc7bece562013-01-25 18:06:21 +0000789 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000790}
791
Greg Claytonde164aa2011-04-20 16:37:46 +0000792bool
793CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
794{
795 if (name && name[0])
796 {
797 std::string name_sstr(name);
Enrico Granatae00af802012-10-01 17:19:37 +0000798 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
799 if (found && !can_replace)
800 return false;
801 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata21dfcd92012-09-28 23:57:51 +0000802 return false;
Greg Claytonde164aa2011-04-20 16:37:46 +0000803 m_command_dict[name_sstr] = cmd_sp;
804 return true;
805 }
806 return false;
807}
808
Enrico Granata223383e2011-08-16 23:24:13 +0000809bool
Enrico Granata0a305db2011-11-07 22:57:04 +0000810CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata223383e2011-08-16 23:24:13 +0000811 const lldb::CommandObjectSP &cmd_sp,
812 bool can_replace)
813{
Enrico Granata0a305db2011-11-07 22:57:04 +0000814 if (!name.empty())
Enrico Granata223383e2011-08-16 23:24:13 +0000815 {
Enrico Granata0a305db2011-11-07 22:57:04 +0000816
817 const char* name_cstr = name.c_str();
818
819 // do not allow replacement of internal commands
820 if (CommandExists(name_cstr))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000821 {
822 if (can_replace == false)
823 return false;
824 if (m_command_dict[name]->IsRemovable() == false)
825 return false;
826 }
Enrico Granata0a305db2011-11-07 22:57:04 +0000827
Enrico Granata21dfcd92012-09-28 23:57:51 +0000828 if (UserCommandExists(name_cstr))
829 {
830 if (can_replace == false)
831 return false;
832 if (m_user_dict[name]->IsRemovable() == false)
833 return false;
834 }
835
Enrico Granata0a305db2011-11-07 22:57:04 +0000836 m_user_dict[name] = cmd_sp;
Enrico Granata223383e2011-08-16 23:24:13 +0000837 return true;
838 }
839 return false;
840}
Greg Claytonde164aa2011-04-20 16:37:46 +0000841
Jim Ingham279a6c22010-07-06 22:46:59 +0000842CommandObjectSP
843CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000844{
Caroline Tice472362e2010-12-14 18:51:39 +0000845 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
846 CommandObjectSP ret_val; // Possibly empty return value.
847
Ed Masted78c9572014-04-20 00:31:37 +0000848 if (cmd_cstr == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000849 return ret_val;
850
851 if (cmd_words.GetArgumentCount() == 1)
Ed Masted78c9572014-04-20 00:31:37 +0000852 return GetCommandSP(cmd_cstr, include_aliases, true, nullptr);
Caroline Tice472362e2010-12-14 18:51:39 +0000853 else
854 {
855 // We have a multi-word command (seemingly), so we need to do more work.
856 // First, get the cmd_obj_sp for the first word in the command.
Ed Masted78c9572014-04-20 00:31:37 +0000857 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, nullptr);
858 if (cmd_obj_sp.get() != nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000859 {
860 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
861 // command name), and find the appropriate sub-command SP for each command word....
862 size_t end = cmd_words.GetArgumentCount();
863 for (size_t j= 1; j < end; ++j)
864 {
865 if (cmd_obj_sp->IsMultiwordObject())
866 {
Greg Clayton998255b2012-10-13 02:07:45 +0000867 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Ed Masted78c9572014-04-20 00:31:37 +0000868 if (cmd_obj_sp.get() == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000869 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
870 return ret_val;
871 }
872 else
873 // We have more words in the command name, but we don't have a multiword object. Fail and return
874 // empty 'ret_val'.
875 return ret_val;
876 }
877 // We successfully looped through all the command words and got valid command objects for them. Assign the
878 // last object retrieved to 'ret_val'.
879 ret_val = cmd_obj_sp;
880 }
881 }
882 return ret_val;
Jim Ingham279a6c22010-07-06 22:46:59 +0000883}
884
885CommandObject *
886CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
887{
888 return GetCommandSPExact (cmd_cstr, include_aliases).get();
889}
890
891CommandObject *
892CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
893{
894 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
895
896 // If we didn't find an exact match to the command string in the commands, look in
897 // the aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000898
899 if (command_obj)
900 return command_obj;
Jim Ingham279a6c22010-07-06 22:46:59 +0000901
Enrico Granata5342c442013-06-18 18:01:08 +0000902 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
Jim Ingham279a6c22010-07-06 22:46:59 +0000903
Enrico Granata5342c442013-06-18 18:01:08 +0000904 if (command_obj)
905 return command_obj;
906
907 // If there wasn't an exact match then look for an inexact one in just the commands
Ed Masted78c9572014-04-20 00:31:37 +0000908 command_obj = GetCommandSP(cmd_cstr, false, false, nullptr).get();
Matt Kopec038ff812013-04-23 16:17:32 +0000909
910 // Finally, if there wasn't an inexact match among the commands, look for an inexact
911 // match in both the commands and aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000912
913 if (command_obj)
914 {
915 if (matches)
916 matches->AppendString(command_obj->GetCommandName());
917 return command_obj;
918 }
919
920 return GetCommandSP(cmd_cstr, true, false, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000921}
922
923bool
924CommandInterpreter::CommandExists (const char *cmd)
925{
926 return m_command_dict.find(cmd) != m_command_dict.end();
927}
928
929bool
Caroline Ticeca90c472011-05-06 21:37:15 +0000930CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
931 const char *options_args,
932 OptionArgVectorSP &option_arg_vector_sp)
933{
934 bool success = true;
935 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
936
937 if (!options_args || (strlen (options_args) < 1))
938 return true;
939
940 std::string options_string (options_args);
941 Args args (options_args);
942 CommandReturnObject result;
943 // Check to see if the command being aliased can take any command options.
944 Options *options = cmd_obj_sp->GetOptions ();
945 if (options)
946 {
947 // See if any options were specified as part of the alias; if so, handle them appropriately.
948 options->NotifyOptionParsingStarting ();
949 args.Unshift ("dummy_arg");
950 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
951 args.Shift ();
952 if (result.Succeeded())
953 options->VerifyPartialOptions (result);
954 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
955 {
956 result.AppendError ("Unable to create requested alias.\n");
957 return false;
958 }
959 }
960
Greg Clayton5521f992011-10-28 21:38:01 +0000961 if (!options_string.empty())
Caroline Ticeca90c472011-05-06 21:37:15 +0000962 {
963 if (cmd_obj_sp->WantsRawCommandString ())
964 option_arg_vector->push_back (OptionArgPair ("<argument>",
965 OptionArgValue (-1,
966 options_string)));
967 else
968 {
Greg Claytonc7bece562013-01-25 18:06:21 +0000969 const size_t argc = args.GetArgumentCount();
Caroline Ticeca90c472011-05-06 21:37:15 +0000970 for (size_t i = 0; i < argc; ++i)
971 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
972 option_arg_vector->push_back
973 (OptionArgPair ("<argument>",
974 OptionArgValue (-1,
975 std::string (args.GetArgumentAtIndex (i)))));
976 }
977 }
978
979 return success;
980}
981
982bool
Jim Ingham298f3782013-04-03 00:25:49 +0000983CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name)
984{
985 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
986 if (exact_match)
987 {
988 full_name.assign(cmd);
989 return exact_match;
990 }
991 else
992 {
993 StringList matches;
994 size_t num_alias_matches;
995 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches);
996 if (num_alias_matches == 1)
997 {
998 // Make sure this isn't shadowing a command in the regular command space:
999 StringList regular_matches;
1000 const bool include_aliases = false;
1001 const bool exact = false;
1002 CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, &regular_matches));
1003 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1004 return false;
1005 else
1006 {
1007 full_name.assign (matches.GetStringAtIndex(0));
1008 return true;
1009 }
1010 }
1011 else
1012 return false;
1013 }
1014}
1015
1016bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001017CommandInterpreter::AliasExists (const char *cmd)
1018{
1019 return m_alias_dict.find(cmd) != m_alias_dict.end();
1020}
1021
1022bool
1023CommandInterpreter::UserCommandExists (const char *cmd)
1024{
1025 return m_user_dict.find(cmd) != m_user_dict.end();
1026}
1027
1028void
1029CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
1030{
Jim Ingham279a6c22010-07-06 22:46:59 +00001031 command_obj_sp->SetIsAlias (true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001032 m_alias_dict[alias_name] = command_obj_sp;
1033}
1034
1035bool
1036CommandInterpreter::RemoveAlias (const char *alias_name)
1037{
1038 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
1039 if (pos != m_alias_dict.end())
1040 {
1041 m_alias_dict.erase(pos);
1042 return true;
1043 }
1044 return false;
1045}
1046bool
1047CommandInterpreter::RemoveUser (const char *alias_name)
1048{
1049 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1050 if (pos != m_user_dict.end())
1051 {
1052 m_user_dict.erase(pos);
1053 return true;
1054 }
1055 return false;
1056}
1057
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001058void
1059CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
1060{
1061 help_string.Printf ("'%s", command_name);
1062 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1063
Sean Callanan9a028512012-08-09 00:50:26 +00001064 if (option_arg_vector_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001065 {
1066 OptionArgVector *options = option_arg_vector_sp.get();
Andy Gibbsa297a972013-06-19 19:04:53 +00001067 for (size_t i = 0; i < options->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001068 {
1069 OptionArgPair cur_option = (*options)[i];
1070 std::string opt = cur_option.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00001071 OptionArgValue value_pair = cur_option.second;
1072 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001073 if (opt.compare("<argument>") == 0)
1074 {
1075 help_string.Printf (" %s", value.c_str());
1076 }
1077 else
1078 {
1079 help_string.Printf (" %s", opt.c_str());
1080 if ((value.compare ("<no-argument>") != 0)
1081 && (value.compare ("<need-argument") != 0))
1082 {
1083 help_string.Printf (" %s", value.c_str());
1084 }
1085 }
1086 }
1087 }
1088
1089 help_string.Printf ("'");
1090}
1091
Greg Clayton12fc3e02010-08-26 22:05:43 +00001092size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001093CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
1094{
1095 CommandObject::CommandMap::const_iterator pos;
Greg Clayton12fc3e02010-08-26 22:05:43 +00001096 CommandObject::CommandMap::const_iterator end = dict.end();
1097 size_t max_len = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001098
Greg Clayton12fc3e02010-08-26 22:05:43 +00001099 for (pos = dict.begin(); pos != end; ++pos)
1100 {
1101 size_t len = pos->first.size();
1102 if (max_len < len)
1103 max_len = len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001104 }
Greg Clayton12fc3e02010-08-26 22:05:43 +00001105 return max_len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001106}
1107
1108void
Enrico Granata223383e2011-08-16 23:24:13 +00001109CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata08633ee2011-09-09 17:49:36 +00001110 uint32_t cmd_types)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001111{
1112 CommandObject::CommandMap::const_iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +00001113 size_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata223383e2011-08-16 23:24:13 +00001114
1115 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116 {
Enrico Granata223383e2011-08-16 23:24:13 +00001117
1118 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
1119 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001120
Enrico Granata223383e2011-08-16 23:24:13 +00001121 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1122 {
1123 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1124 max_len);
1125 }
1126 result.AppendMessage("");
1127
1128 }
1129
Greg Clayton5521f992011-10-28 21:38:01 +00001130 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001131 {
Jim Ingham49e80a12010-10-22 18:47:16 +00001132 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chenb89982d2011-04-21 00:39:18 +00001133 "(see 'help command alias' for more info):");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134 result.AppendMessage("");
Greg Clayton12fc3e02010-08-26 22:05:43 +00001135 max_len = FindLongestCommandWord (m_alias_dict);
1136
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001137 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1138 {
1139 StreamString sstr;
1140 StreamString translation_and_help;
1141 std::string entry_name = pos->first;
1142 std::string second_entry = pos->second.get()->GetCommandName();
1143 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1144
1145 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1146 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1147 translation_and_help.GetData(), max_len);
1148 }
1149 result.AppendMessage("");
1150 }
1151
Greg Clayton5521f992011-10-28 21:38:01 +00001152 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001153 {
1154 result.AppendMessage ("The following is a list of your current user-defined commands:");
1155 result.AppendMessage("");
Enrico Granata223383e2011-08-16 23:24:13 +00001156 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001157 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1158 {
Enrico Granata223383e2011-08-16 23:24:13 +00001159 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1160 max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001161 }
1162 result.AppendMessage("");
1163 }
1164
1165 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1166}
1167
Caroline Tice844d2302010-12-09 22:52:49 +00001168CommandObject *
1169CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001170{
Caroline Tice844d2302010-12-09 22:52:49 +00001171 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1172 // eventually be invoked by the given command line.
1173
Ed Masted78c9572014-04-20 00:31:37 +00001174 CommandObject *cmd_obj = nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001175 std::string white_space (" \t\v");
1176 size_t start = command_string.find_first_not_of (white_space);
1177 size_t end = 0;
1178 bool done = false;
1179 while (!done)
1180 {
1181 if (start != std::string::npos)
1182 {
1183 // Get the next word from command_string.
1184 end = command_string.find_first_of (white_space, start);
1185 if (end == std::string::npos)
1186 end = command_string.size();
1187 std::string cmd_word = command_string.substr (start, end - start);
1188
Ed Masted78c9572014-04-20 00:31:37 +00001189 if (cmd_obj == nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001190 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1191 // command or alias.
1192 cmd_obj = GetCommandObject (cmd_word.c_str());
1193 else if (cmd_obj->IsMultiwordObject ())
1194 {
1195 // 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 +00001196 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001197 if (sub_cmd_obj)
1198 cmd_obj = sub_cmd_obj;
1199 else // cmd_word was not a valid sub-command word, so we are donee
1200 done = true;
1201 }
1202 else
1203 // We have a cmd_obj and it is not a multi-word object, so we are done.
1204 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001205
Caroline Tice844d2302010-12-09 22:52:49 +00001206 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1207 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1208 // next word.
1209
1210 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1211 done = true;
1212 else
1213 start = command_string.find_first_not_of (white_space, end);
1214 }
1215 else
1216 // Unable to find any more words.
1217 done = true;
1218 }
1219
1220 if (end == command_string.size())
1221 command_string.clear();
1222 else
1223 command_string = command_string.substr(end);
1224
1225 return cmd_obj;
1226}
1227
Greg Clayton51964162011-10-25 00:36:27 +00001228static const char *k_white_space = " \t\v";
Greg Clayton5521f992011-10-28 21:38:01 +00001229static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton51964162011-10-25 00:36:27 +00001230static void
1231StripLeadingSpaces (std::string &s)
Caroline Tice844d2302010-12-09 22:52:49 +00001232{
Greg Clayton51964162011-10-25 00:36:27 +00001233 if (!s.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001234 {
Greg Clayton51964162011-10-25 00:36:27 +00001235 size_t pos = s.find_first_not_of (k_white_space);
1236 if (pos == std::string::npos)
1237 s.clear();
1238 else if (pos == 0)
1239 return;
1240 s.erase (0, pos);
1241 }
1242}
1243
Greg Clayton93c62e62011-11-09 23:25:03 +00001244static size_t
1245FindArgumentTerminator (const std::string &s)
1246{
Greg Clayton93c62e62011-11-09 23:25:03 +00001247 const size_t s_len = s.size();
1248 size_t offset = 0;
1249 while (offset < s_len)
1250 {
1251 size_t pos = s.find ("--", offset);
1252 if (pos == std::string::npos)
1253 break;
1254 if (pos > 0)
1255 {
1256 if (isspace(s[pos-1]))
1257 {
1258 // Check if the string ends "\s--" (where \s is a space character)
1259 // or if we have "\s--\s".
1260 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1261 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001262 return pos;
1263 }
1264 }
1265 }
1266 offset = pos + 2;
1267 }
Greg Clayton93c62e62011-11-09 23:25:03 +00001268 return std::string::npos;
1269}
1270
Greg Clayton51964162011-10-25 00:36:27 +00001271static bool
Greg Clayton5521f992011-10-28 21:38:01 +00001272ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton51964162011-10-25 00:36:27 +00001273{
Greg Clayton5521f992011-10-28 21:38:01 +00001274 command.clear();
1275 suffix.clear();
Greg Clayton51964162011-10-25 00:36:27 +00001276 StripLeadingSpaces (command_string);
1277
1278 bool result = false;
1279 quote_char = '\0';
1280
1281 if (!command_string.empty())
1282 {
1283 const char first_char = command_string[0];
1284 if (first_char == '\'' || first_char == '"')
Caroline Tice844d2302010-12-09 22:52:49 +00001285 {
Greg Clayton51964162011-10-25 00:36:27 +00001286 quote_char = first_char;
1287 const size_t end_quote_pos = command_string.find (quote_char, 1);
1288 if (end_quote_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001289 {
Greg Clayton5521f992011-10-28 21:38:01 +00001290 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001291 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001292 }
1293 else
1294 {
Greg Clayton5521f992011-10-28 21:38:01 +00001295 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton51964162011-10-25 00:36:27 +00001296 if (end_quote_pos + 1 < command_string.size())
1297 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1298 else
1299 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001300 }
Caroline Tice844d2302010-12-09 22:52:49 +00001301 }
1302 else
1303 {
Greg Clayton51964162011-10-25 00:36:27 +00001304 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1305 if (first_space_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001306 {
Greg Clayton5521f992011-10-28 21:38:01 +00001307 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001308 command_string.erase();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001309 }
1310 else
1311 {
Greg Clayton5521f992011-10-28 21:38:01 +00001312 command.assign (command_string, 0, first_space_pos);
1313 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice2b5e8502011-05-11 16:07:06 +00001314 }
Caroline Tice844d2302010-12-09 22:52:49 +00001315 }
Greg Clayton51964162011-10-25 00:36:27 +00001316 result = true;
Caroline Tice844d2302010-12-09 22:52:49 +00001317 }
Greg Clayton5521f992011-10-28 21:38:01 +00001318
1319
1320 if (!command.empty())
1321 {
1322 // actual commands can't start with '-' or '_'
1323 if (command[0] != '-' && command[0] != '_')
1324 {
1325 size_t pos = command.find_first_not_of(k_valid_command_chars);
1326 if (pos > 0 && pos != std::string::npos)
1327 {
1328 suffix.assign (command.begin() + pos, command.end());
1329 command.erase (pos);
1330 }
1331 }
1332 }
Greg Clayton51964162011-10-25 00:36:27 +00001333
1334 return result;
Caroline Tice844d2302010-12-09 22:52:49 +00001335}
1336
Greg Clayton5521f992011-10-28 21:38:01 +00001337CommandObject *
1338CommandInterpreter::BuildAliasResult (const char *alias_name,
1339 std::string &raw_input_string,
1340 std::string &alias_result,
1341 CommandReturnObject &result)
Caroline Tice844d2302010-12-09 22:52:49 +00001342{
Ed Masted78c9572014-04-20 00:31:37 +00001343 CommandObject *alias_cmd_obj = nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001344 Args cmd_args (raw_input_string.c_str());
1345 alias_cmd_obj = GetCommandObject (alias_name);
1346 StreamString result_str;
1347
1348 if (alias_cmd_obj)
1349 {
1350 std::string alias_name_str = alias_name;
1351 if ((cmd_args.GetArgumentCount() == 0)
1352 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1353 cmd_args.Unshift (alias_name);
1354
1355 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1356 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1357
1358 if (option_arg_vector_sp.get())
1359 {
1360 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1361
Andy Gibbsa297a972013-06-19 19:04:53 +00001362 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Caroline Tice844d2302010-12-09 22:52:49 +00001363 {
1364 OptionArgPair option_pair = (*option_arg_vector)[i];
1365 OptionArgValue value_pair = option_pair.second;
1366 int value_type = value_pair.first;
1367 std::string option = option_pair.first;
1368 std::string value = value_pair.second;
1369 if (option.compare ("<argument>") == 0)
1370 result_str.Printf (" %s", value.c_str());
1371 else
1372 {
1373 result_str.Printf (" %s", option.c_str());
Virgile Belloe2607b52013-09-05 16:42:23 +00001374 if (value_type != OptionParser::eOptionalArgument)
Caroline Tice844d2302010-12-09 22:52:49 +00001375 result_str.Printf (" ");
Virgile Belloe2607b52013-09-05 16:42:23 +00001376 if (value.compare ("<OptionParser::eNoArgument>") != 0)
Caroline Tice844d2302010-12-09 22:52:49 +00001377 {
1378 int index = GetOptionArgumentPosition (value.c_str());
1379 if (index == 0)
1380 result_str.Printf ("%s", value.c_str());
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001381 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Caroline Tice844d2302010-12-09 22:52:49 +00001382 {
1383
1384 result.AppendErrorWithFormat
1385 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1386 index);
1387 result.SetStatus (eReturnStatusFailed);
Greg Clayton5521f992011-10-28 21:38:01 +00001388 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001389 }
1390 else
1391 {
1392 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1393 if (strpos != std::string::npos)
1394 raw_input_string = raw_input_string.erase (strpos,
1395 strlen (cmd_args.GetArgumentAtIndex (index)));
1396 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1397 }
1398 }
1399 }
1400 }
1401 }
1402
1403 alias_result = result_str.GetData();
1404 }
Greg Clayton5521f992011-10-28 21:38:01 +00001405 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001406}
1407
Greg Clayton5a314712011-10-14 07:41:33 +00001408Error
1409CommandInterpreter::PreprocessCommand (std::string &command)
1410{
1411 // The command preprocessor needs to do things to the command
1412 // line before any parsing of arguments or anything else is done.
1413 // The only current stuff that gets proprocessed is anyting enclosed
1414 // in backtick ('`') characters is evaluated as an expression and
1415 // the result of the expression must be a scalar that can be substituted
1416 // into the command. An example would be:
1417 // (lldb) memory read `$rsp + 20`
1418 Error error; // Error for any expressions that might not evaluate
1419 size_t start_backtick;
1420 size_t pos = 0;
1421 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1422 {
1423 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1424 {
1425 // The backtick was preceeded by a '\' character, remove the slash
1426 // and don't treat the backtick as the start of an expression
1427 command.erase(start_backtick-1, 1);
1428 // No need to add one to start_backtick since we just deleted a char
1429 pos = start_backtick;
1430 }
1431 else
1432 {
1433 const size_t expr_content_start = start_backtick + 1;
1434 const size_t end_backtick = command.find ('`', expr_content_start);
1435 if (end_backtick == std::string::npos)
1436 return error;
1437 else if (end_backtick == expr_content_start)
1438 {
1439 // Empty expression (two backticks in a row)
1440 command.erase (start_backtick, 2);
1441 }
1442 else
1443 {
1444 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1445
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00001446 ExecutionContext exe_ctx(GetExecutionContext());
1447 Target *target = exe_ctx.GetTargetPtr();
Johnny Chen51ea0ad2011-10-29 00:21:50 +00001448 // Get a dummy target to allow for calculator mode while processing backticks.
1449 // This also helps break the infinite loop caused when target is null.
1450 if (!target)
1451 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Clayton5a314712011-10-14 07:41:33 +00001452 if (target)
1453 {
Greg Clayton5a314712011-10-14 07:41:33 +00001454 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001455
Jim Ingham35e1bda2012-10-16 21:41:58 +00001456 EvaluateExpressionOptions options;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00001457 options.SetCoerceToId(false);
1458 options.SetUnwindOnError(true);
1459 options.SetIgnoreBreakpoints(true);
1460 options.SetKeepInMemory(false);
1461 options.SetTryAllThreads(true);
1462 options.SetTimeoutUsec(0);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001463
Jim Ingham1624a2d2014-05-05 02:26:40 +00001464 ExpressionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad4439aa2012-09-05 20:41:26 +00001465 exe_ctx.GetFramePtr(),
Enrico Granata3372f582012-07-16 23:10:35 +00001466 expr_result_valobj_sp,
Enrico Granatad4439aa2012-09-05 20:41:26 +00001467 options);
1468
Jim Ingham8646d3c2014-05-05 02:47:44 +00001469 if (expr_result == eExpressionCompleted)
Greg Clayton5a314712011-10-14 07:41:33 +00001470 {
1471 Scalar scalar;
1472 if (expr_result_valobj_sp->ResolveValue (scalar))
1473 {
1474 command.erase (start_backtick, end_backtick - start_backtick + 1);
1475 StreamString value_strm;
1476 const bool show_type = false;
1477 scalar.GetValue (&value_strm, show_type);
1478 size_t value_string_size = value_strm.GetSize();
1479 if (value_string_size)
1480 {
1481 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1482 pos = start_backtick + value_string_size;
1483 continue;
1484 }
1485 else
1486 {
1487 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1488 }
1489 }
1490 else
1491 {
1492 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1493 }
1494 }
1495 else
1496 {
1497 if (expr_result_valobj_sp)
1498 error = expr_result_valobj_sp->GetError();
1499 if (error.Success())
1500 {
1501
1502 switch (expr_result)
1503 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00001504 case eExpressionSetupError:
Greg Clayton5a314712011-10-14 07:41:33 +00001505 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1506 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001507 case eExpressionParseError:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001508 error.SetErrorStringWithFormat ("expression parse error for the expression '%s'", expr_str.c_str());
1509 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001510 case eExpressionResultUnavailable:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001511 error.SetErrorStringWithFormat ("expression error fetching result for the expression '%s'", expr_str.c_str());
Jim Ingham8646d3c2014-05-05 02:47:44 +00001512 case eExpressionCompleted:
Greg Clayton5a314712011-10-14 07:41:33 +00001513 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001514 case eExpressionDiscarded:
Greg Clayton5a314712011-10-14 07:41:33 +00001515 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1516 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001517 case eExpressionInterrupted:
Greg Clayton5a314712011-10-14 07:41:33 +00001518 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1519 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001520 case eExpressionHitBreakpoint:
Jim Ingham184e9812013-01-15 02:47:48 +00001521 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1522 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001523 case eExpressionTimedOut:
Greg Clayton5a314712011-10-14 07:41:33 +00001524 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1525 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001526 case eExpressionStoppedForDebug:
Greg Claytonc28ce782013-11-08 23:38:26 +00001527 error.SetErrorStringWithFormat("expression stop at entry point for debugging for the expression '%s'", expr_str.c_str());
1528 break;
Greg Clayton5a314712011-10-14 07:41:33 +00001529 }
1530 }
1531 }
1532 }
1533 }
1534 if (error.Fail())
1535 break;
1536 }
1537 }
1538 return error;
1539}
1540
1541
Caroline Tice844d2302010-12-09 22:52:49 +00001542bool
1543CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata5f5ab602012-05-31 01:09:06 +00001544 LazyBool lazy_add_to_history,
Caroline Tice844d2302010-12-09 22:52:49 +00001545 CommandReturnObject &result,
Jim Inghame16c50a2011-02-18 00:54:25 +00001546 ExecutionContext *override_context,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001547 bool repeat_on_empty_command,
1548 bool no_context_switching)
Jim Inghame16c50a2011-02-18 00:54:25 +00001549
Caroline Tice844d2302010-12-09 22:52:49 +00001550{
Jim Inghame16c50a2011-02-18 00:54:25 +00001551
Caroline Tice844d2302010-12-09 22:52:49 +00001552 bool done = false;
Ed Masted78c9572014-04-20 00:31:37 +00001553 CommandObject *cmd_obj = nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001554 bool wants_raw_input = false;
1555 std::string command_string (command_line);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001556 std::string original_command_string (command_line);
Caroline Tice844d2302010-12-09 22:52:49 +00001557
Greg Clayton5160ce52013-03-27 23:08:40 +00001558 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001559 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1560
1561 // Make a scoped cleanup object that will clear the crash description string
1562 // on exit of this function.
Ed Masted78c9572014-04-20 00:31:37 +00001563 lldb_utility::CleanUp <const char *> crash_description_cleanup(nullptr, Host::SetCrashDescription);
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001564
Caroline Tice844d2302010-12-09 22:52:49 +00001565 if (log)
1566 log->Printf ("Processing command: %s", command_line);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001567
Jim Ingham30244832010-11-04 23:08:45 +00001568 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1569
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001570 if (!no_context_switching)
1571 UpdateExecutionContext (override_context);
Enrico Granata5f5ab602012-05-31 01:09:06 +00001572
Enrico Granata5f5ab602012-05-31 01:09:06 +00001573 bool add_to_history;
1574 if (lazy_add_to_history == eLazyBoolCalculate)
1575 add_to_history = (m_command_source_depth == 0);
1576 else
1577 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1578
Jim Inghame16c50a2011-02-18 00:54:25 +00001579 bool empty_command = false;
1580 bool comment_command = false;
1581 if (command_string.empty())
1582 empty_command = true;
1583 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001584 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001585 const char *k_space_characters = "\t\n\v\f\r ";
1586
1587 size_t non_space = command_string.find_first_not_of (k_space_characters);
1588 // Check for empty line or comment line (lines whose first
1589 // non-space character is the comment character for this interpreter)
1590 if (non_space == std::string::npos)
1591 empty_command = true;
1592 else if (command_string[non_space] == m_comment_char)
1593 comment_command = true;
Enrico Granata7594f142013-06-17 22:51:50 +00001594 else if (command_string[non_space] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001595 {
Enrico Granata7594f142013-06-17 22:51:50 +00001596 const char *history_string = m_command_history.FindString(command_string.c_str() + non_space);
Ed Masted78c9572014-04-20 00:31:37 +00001597 if (history_string == nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001598 {
1599 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1600 result.SetStatus(eReturnStatusFailed);
1601 return false;
1602 }
1603 add_to_history = false;
1604 command_string = history_string;
1605 original_command_string = history_string;
1606 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001607 }
1608
1609 if (empty_command)
1610 {
1611 if (repeat_on_empty_command)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001612 {
Enrico Granata7594f142013-06-17 22:51:50 +00001613 if (m_command_history.IsEmpty())
Jim Inghame16c50a2011-02-18 00:54:25 +00001614 {
1615 result.AppendError ("empty command");
1616 result.SetStatus(eReturnStatusFailed);
1617 return false;
1618 }
1619 else
1620 {
1621 command_line = m_repeat_command.c_str();
1622 command_string = command_line;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001623 original_command_string = command_line;
Jim Inghame16c50a2011-02-18 00:54:25 +00001624 if (m_repeat_command.empty())
1625 {
1626 result.AppendErrorWithFormat("No auto repeat.\n");
1627 result.SetStatus (eReturnStatusFailed);
1628 return false;
1629 }
1630 }
1631 add_to_history = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001632 }
1633 else
1634 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001635 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1636 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001637 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001638 }
1639 else if (comment_command)
1640 {
1641 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1642 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001643 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001644
Greg Clayton5a314712011-10-14 07:41:33 +00001645
1646 Error error (PreprocessCommand (command_string));
1647
1648 if (error.Fail())
1649 {
1650 result.AppendError (error.AsCString());
1651 result.SetStatus(eReturnStatusFailed);
1652 return false;
1653 }
Caroline Tice844d2302010-12-09 22:52:49 +00001654 // Phase 1.
1655
1656 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1657 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1658 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1659 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1660 // 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 +00001661 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Tice844d2302010-12-09 22:52:49 +00001662 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Ticed9d63362010-12-07 19:58:26 +00001663
Caroline Tice844d2302010-12-09 22:52:49 +00001664 StreamString revised_command_line;
Caroline Tice01274c02010-12-11 08:16:56 +00001665 size_t actual_cmd_name_len = 0;
Greg Clayton5521f992011-10-28 21:38:01 +00001666 std::string next_word;
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001667 StringList matches;
Caroline Tice844d2302010-12-09 22:52:49 +00001668 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001669 {
Caroline Tice2b5e8502011-05-11 16:07:06 +00001670 char quote_char = '\0';
Greg Clayton5521f992011-10-28 21:38:01 +00001671 std::string suffix;
1672 ExtractCommand (command_string, next_word, suffix, quote_char);
Ed Masted78c9572014-04-20 00:31:37 +00001673 if (cmd_obj == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001674 {
Jim Ingham298f3782013-04-03 00:25:49 +00001675 std::string full_name;
1676 if (GetAliasFullName(next_word.c_str(), full_name))
Caroline Tice472362e2010-12-14 18:51:39 +00001677 {
Greg Clayton5521f992011-10-28 21:38:01 +00001678 std::string alias_result;
Jim Ingham298f3782013-04-03 00:25:49 +00001679 cmd_obj = BuildAliasResult (full_name.c_str(), command_string, alias_result, result);
Greg Clayton5521f992011-10-28 21:38:01 +00001680 revised_command_line.Printf ("%s", alias_result.c_str());
1681 if (cmd_obj)
1682 {
1683 wants_raw_input = cmd_obj->WantsRawCommandString ();
1684 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1685 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001686 }
1687 else
1688 {
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001689 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton5521f992011-10-28 21:38:01 +00001690 if (cmd_obj)
1691 {
1692 actual_cmd_name_len += next_word.length();
1693 revised_command_line.Printf ("%s", next_word.c_str());
1694 wants_raw_input = cmd_obj->WantsRawCommandString ();
1695 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001696 else
Greg Clayton5521f992011-10-28 21:38:01 +00001697 {
1698 revised_command_line.Printf ("%s", next_word.c_str());
1699 }
Caroline Tice844d2302010-12-09 22:52:49 +00001700 }
1701 }
1702 else
1703 {
Greg Clayton5521f992011-10-28 21:38:01 +00001704 if (cmd_obj->IsMultiwordObject ())
1705 {
Greg Clayton998255b2012-10-13 02:07:45 +00001706 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
Greg Clayton5521f992011-10-28 21:38:01 +00001707 if (sub_cmd_obj)
1708 {
1709 actual_cmd_name_len += next_word.length() + 1;
1710 revised_command_line.Printf (" %s", next_word.c_str());
1711 cmd_obj = sub_cmd_obj;
1712 wants_raw_input = cmd_obj->WantsRawCommandString ();
1713 }
1714 else
1715 {
1716 if (quote_char)
1717 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1718 else
1719 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1720 done = true;
1721 }
1722 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001723 else
Greg Clayton5521f992011-10-28 21:38:01 +00001724 {
1725 if (quote_char)
1726 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1727 else
1728 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1729 done = true;
1730 }
Caroline Tice844d2302010-12-09 22:52:49 +00001731 }
1732
Ed Masted78c9572014-04-20 00:31:37 +00001733 if (cmd_obj == nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001734 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001735 const size_t num_matches = matches.GetSize();
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001736 if (matches.GetSize() > 1) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001737 StreamString error_msg;
1738 error_msg.Printf ("Ambiguous command '%s'. Possible matches:\n", next_word.c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001739
1740 for (uint32_t i = 0; i < num_matches; ++i) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001741 error_msg.Printf ("\t%s\n", matches.GetStringAtIndex(i));
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001742 }
Greg Claytonc7bece562013-01-25 18:06:21 +00001743 result.AppendRawError (error_msg.GetString().c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001744 } else {
1745 // We didn't have only one match, otherwise we wouldn't get here.
1746 assert(num_matches == 0);
1747 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1748 }
Caroline Tice844d2302010-12-09 22:52:49 +00001749 result.SetStatus (eReturnStatusFailed);
1750 return false;
1751 }
1752
Greg Clayton5521f992011-10-28 21:38:01 +00001753 if (cmd_obj->IsMultiwordObject ())
1754 {
1755 if (!suffix.empty())
1756 {
1757
Enrico Granataaded51d2013-06-12 00:44:43 +00001758 result.AppendErrorWithFormat ("command '%s' did not recognize '%s%s%s' as valid (subcommand might be invalid).\n",
1759 cmd_obj->GetCommandName(),
1760 next_word.empty() ? "" : next_word.c_str(),
1761 next_word.empty() ? " -- " : " ",
Greg Clayton5521f992011-10-28 21:38:01 +00001762 suffix.c_str());
1763 result.SetStatus (eReturnStatusFailed);
1764 return false;
1765 }
1766 }
1767 else
1768 {
1769 // If we found a normal command, we are done
1770 done = true;
1771 if (!suffix.empty())
1772 {
1773 switch (suffix[0])
1774 {
1775 case '/':
1776 // GDB format suffixes
Greg Clayton52ec56c2011-10-29 00:57:28 +00001777 {
1778 Options *command_options = cmd_obj->GetOptions();
1779 if (command_options && command_options->SupportsLongOption("gdb-format"))
1780 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001781 std::string gdb_format_option ("--gdb-format=");
1782 gdb_format_option += (suffix.c_str() + 1);
1783
1784 bool inserted = false;
1785 std::string &cmd = revised_command_line.GetString();
1786 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1787 if (arg_terminator_idx != std::string::npos)
1788 {
1789 // Insert the gdb format option before the "--" that terminates options
1790 gdb_format_option.append(1,' ');
1791 cmd.insert(arg_terminator_idx, gdb_format_option);
1792 inserted = true;
1793 }
1794
1795 if (!inserted)
1796 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1797
1798 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1799 revised_command_line.PutCString (" --");
Greg Clayton52ec56c2011-10-29 00:57:28 +00001800 }
1801 else
1802 {
1803 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1804 cmd_obj->GetCommandName());
1805 result.SetStatus (eReturnStatusFailed);
1806 return false;
1807 }
1808 }
Greg Clayton5521f992011-10-28 21:38:01 +00001809 break;
Johnny Chen8e9383d2011-10-31 22:22:06 +00001810
1811 default:
1812 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1813 suffix.c_str());
1814 result.SetStatus (eReturnStatusFailed);
1815 return false;
1816
Greg Clayton5521f992011-10-28 21:38:01 +00001817 }
1818 }
1819 }
Caroline Tice844d2302010-12-09 22:52:49 +00001820 if (command_string.length() == 0)
1821 done = true;
1822
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001823 }
Caroline Tice844d2302010-12-09 22:52:49 +00001824
Greg Clayton5521f992011-10-28 21:38:01 +00001825 if (!command_string.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001826 revised_command_line.Printf (" %s", command_string.c_str());
1827
1828 // End of Phase 1.
1829 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1830 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1831 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1832 // wants_raw_input specifies whether the Execute method expects raw input or not.
1833
1834
1835 if (log)
1836 {
1837 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1838 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1839 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1840 }
1841
1842 // Phase 2.
1843 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1844 // CommandObject, with the appropriate arguments.
1845
Ed Masted78c9572014-04-20 00:31:37 +00001846 if (cmd_obj != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001847 {
1848 if (add_to_history)
1849 {
1850 Args command_args (revised_command_line.GetData());
1851 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
Ed Masted78c9572014-04-20 00:31:37 +00001852 if (repeat_command != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001853 m_repeat_command.assign(repeat_command);
1854 else
Jim Inghama5a97eb2011-07-12 03:12:18 +00001855 m_repeat_command.assign(original_command_string.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001856
Enrico Granata7594f142013-06-17 22:51:50 +00001857 m_command_history.AppendString (original_command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001858 }
1859
1860 command_string = revised_command_line.GetData();
1861 std::string command_name (cmd_obj->GetCommandName());
Caroline Tice01274c02010-12-11 08:16:56 +00001862 std::string remainder;
1863 if (actual_cmd_name_len < command_string.length())
1864 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1865 // than cmd_obj->GetCommandName(), because name completion
1866 // allows users to enter short versions of the names,
1867 // e.g. 'br s' for 'breakpoint set'.
Caroline Tice844d2302010-12-09 22:52:49 +00001868
1869 // Remove any initial spaces
1870 std::string white_space (" \t\v");
1871 size_t pos = remainder.find_first_not_of (white_space);
1872 if (pos != 0 && pos != std::string::npos)
Greg Claytona3482592011-04-22 20:58:45 +00001873 remainder.erase(0, pos);
Caroline Tice844d2302010-12-09 22:52:49 +00001874
1875 if (log)
Jason Molendabfb36ff2011-08-25 00:20:04 +00001876 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001877
Jim Ingham5a988412012-06-08 21:56:10 +00001878 cmd_obj->Execute (remainder.c_str(), result);
Caroline Tice844d2302010-12-09 22:52:49 +00001879 }
1880 else
1881 {
1882 // We didn't find the first command object, so complete the first argument.
1883 Args command_args (revised_command_line.GetData());
1884 StringList matches;
1885 int num_matches;
1886 int cursor_index = 0;
1887 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1888 bool word_complete;
1889 num_matches = HandleCompletionMatches (command_args,
1890 cursor_index,
1891 cursor_char_position,
1892 0,
1893 -1,
1894 word_complete,
1895 matches);
1896
1897 if (num_matches > 0)
1898 {
1899 std::string error_msg;
1900 error_msg.assign ("ambiguous command '");
1901 error_msg.append(command_args.GetArgumentAtIndex(0));
1902 error_msg.append ("'.");
1903
1904 error_msg.append (" Possible completions:");
1905 for (int i = 0; i < num_matches; i++)
1906 {
1907 error_msg.append ("\n\t");
1908 error_msg.append (matches.GetStringAtIndex (i));
1909 }
1910 error_msg.append ("\n");
Greg Claytonc7bece562013-01-25 18:06:21 +00001911 result.AppendRawError (error_msg.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001912 }
1913 else
1914 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1915
1916 result.SetStatus (eReturnStatusFailed);
1917 }
1918
Jason Molendabfb36ff2011-08-25 00:20:04 +00001919 if (log)
1920 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1921
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001922 return result.Succeeded();
1923}
1924
1925int
1926CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1927 int &cursor_index,
1928 int &cursor_char_position,
1929 int match_start_point,
1930 int max_return_elements,
Jim Ingham558ce122010-06-30 05:02:46 +00001931 bool &word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001932 StringList &matches)
1933{
1934 int num_command_matches = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001935 bool look_for_subcommand = false;
Jim Ingham558ce122010-06-30 05:02:46 +00001936
1937 // For any of the command completions a unique match will be a complete word.
1938 word_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001939
1940 if (cursor_index == -1)
1941 {
1942 // We got nothing on the command line, so return the list of commands
Jim Ingham279a6c22010-07-06 22:46:59 +00001943 bool include_aliases = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001944 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1945 }
1946 else if (cursor_index == 0)
1947 {
1948 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Ingham279a6c22010-07-06 22:46:59 +00001949 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001950 num_command_matches = matches.GetSize();
1951
1952 if (num_command_matches == 1
1953 && cmd_obj && cmd_obj->IsMultiwordObject()
Ed Masted78c9572014-04-20 00:31:37 +00001954 && matches.GetStringAtIndex(0) != nullptr
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001955 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1956 {
Greg Clayton765d2e22013-12-10 19:14:04 +00001957 if (parsed_line.GetArgumentCount() == 1)
1958 {
1959 word_complete = true;
1960 }
1961 else
1962 {
1963 look_for_subcommand = true;
1964 num_command_matches = 0;
1965 matches.DeleteStringAtIndex(0);
1966 parsed_line.AppendArgument ("");
1967 cursor_index++;
1968 cursor_char_position = 0;
1969 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001970 }
1971 }
1972
1973 if (cursor_index > 0 || look_for_subcommand)
1974 {
1975 // We are completing further on into a commands arguments, so find the command and tell it
1976 // to complete the command.
1977 // First see if there is a matching initial command:
Jim Ingham279a6c22010-07-06 22:46:59 +00001978 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Ed Masted78c9572014-04-20 00:31:37 +00001979 if (command_object == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001980 {
1981 return 0;
1982 }
1983 else
1984 {
1985 parsed_line.Shift();
1986 cursor_index--;
Greg Claytona7015092010-09-18 01:14:36 +00001987 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton66111032010-06-23 01:19:29 +00001988 cursor_index,
1989 cursor_char_position,
1990 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001991 max_return_elements,
1992 word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001993 matches);
1994 }
1995 }
1996
1997 return num_command_matches;
1998
1999}
2000
2001int
2002CommandInterpreter::HandleCompletion (const char *current_line,
2003 const char *cursor,
2004 const char *last_char,
2005 int match_start_point,
2006 int max_return_elements,
2007 StringList &matches)
2008{
2009 // We parse the argument up to the cursor, so the last argument in parsed_line is
2010 // the one containing the cursor, and the cursor is after the last character.
2011
2012 Args parsed_line(current_line, last_char - current_line);
2013 Args partial_parsed_line(current_line, cursor - current_line);
2014
Jim Inghama5a97eb2011-07-12 03:12:18 +00002015 // Don't complete comments, and if the line we are completing is just the history repeat character,
2016 // substitute the appropriate history line.
2017 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
2018 if (first_arg)
2019 {
2020 if (first_arg[0] == m_comment_char)
2021 return 0;
Enrico Granata7594f142013-06-17 22:51:50 +00002022 else if (first_arg[0] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002023 {
Enrico Granata7594f142013-06-17 22:51:50 +00002024 const char *history_string = m_command_history.FindString (first_arg);
Ed Masted78c9572014-04-20 00:31:37 +00002025 if (history_string != nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002026 {
2027 matches.Clear();
2028 matches.InsertStringAtIndex(0, history_string);
2029 return -2;
2030 }
2031 else
2032 return 0;
2033
2034 }
2035 }
2036
2037
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002038 int num_args = partial_parsed_line.GetArgumentCount();
2039 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
2040 int cursor_char_position;
2041
2042 if (cursor_index == -1)
2043 cursor_char_position = 0;
2044 else
2045 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamfe0c4252010-12-14 19:56:01 +00002046
2047 if (cursor > current_line && cursor[-1] == ' ')
2048 {
2049 // We are just after a space. If we are in an argument, then we will continue
2050 // parsing, but if we are between arguments, then we have to complete whatever the next
2051 // element would be.
2052 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
2053 // protected by a quote) then the space will also be in the parsed argument...
2054
2055 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
2056 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
2057 {
Greg Clayton765d2e22013-12-10 19:14:04 +00002058 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '\0');
Jim Inghamfe0c4252010-12-14 19:56:01 +00002059 cursor_index++;
2060 cursor_char_position = 0;
2061 }
2062 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002063
2064 int num_command_matches;
2065
2066 matches.Clear();
2067
2068 // Only max_return_elements == -1 is supported at present:
2069 assert (max_return_elements == -1);
Jim Ingham558ce122010-06-30 05:02:46 +00002070 bool word_complete;
Greg Clayton66111032010-06-23 01:19:29 +00002071 num_command_matches = HandleCompletionMatches (parsed_line,
2072 cursor_index,
2073 cursor_char_position,
2074 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00002075 max_return_elements,
2076 word_complete,
Greg Clayton66111032010-06-23 01:19:29 +00002077 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002078
2079 if (num_command_matches <= 0)
2080 return num_command_matches;
2081
2082 if (num_args == 0)
2083 {
2084 // If we got an empty string, insert nothing.
2085 matches.InsertStringAtIndex(0, "");
2086 }
2087 else
2088 {
2089 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
2090 // put an empty string in element 0.
2091 std::string command_partial_str;
2092 if (cursor_index >= 0)
Jim Ingham49e80a12010-10-22 18:47:16 +00002093 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
2094 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002095
2096 std::string common_prefix;
2097 matches.LongestCommonPrefix (common_prefix);
Greg Claytonc7bece562013-01-25 18:06:21 +00002098 const size_t partial_name_len = command_partial_str.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002099
2100 // If we matched a unique single command, add a space...
Jim Ingham558ce122010-06-30 05:02:46 +00002101 // Only do this if the completer told us this was a complete word, however...
2102 if (num_command_matches == 1 && word_complete)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002103 {
2104 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
2105 if (quote_char != '\0')
2106 common_prefix.push_back(quote_char);
2107
2108 common_prefix.push_back(' ');
2109 }
2110 common_prefix.erase (0, partial_name_len);
2111 matches.InsertStringAtIndex(0, common_prefix.c_str());
2112 }
2113 return num_command_matches;
2114}
2115
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002116
2117CommandInterpreter::~CommandInterpreter ()
2118{
2119}
2120
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002121void
Greg Clayton44d93782014-01-27 23:43:24 +00002122CommandInterpreter::UpdatePrompt (const char *new_prompt)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002123{
Greg Clayton44d93782014-01-27 23:43:24 +00002124 EventSP prompt_change_event_sp (new Event(eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));;
2125 BroadcastEvent (prompt_change_event_sp);
2126 if (m_command_io_handler_sp)
2127 m_command_io_handler_sp->SetPrompt(new_prompt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002128}
2129
Jim Ingham97a6dc72010-10-04 19:49:29 +00002130
2131bool
2132CommandInterpreter::Confirm (const char *message, bool default_answer)
2133{
Jim Ingham3bcdb292010-10-04 22:44:14 +00002134 // Check AutoConfirm first:
2135 if (m_debugger.GetAutoConfirm())
2136 return default_answer;
Greg Clayton44d93782014-01-27 23:43:24 +00002137
2138 IOHandlerConfirm *confirm = new IOHandlerConfirm(m_debugger,
2139 message,
2140 default_answer);
2141 IOHandlerSP io_handler_sp (confirm);
2142 m_debugger.RunIOHandler (io_handler_sp);
2143 return confirm->GetResponse();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002144}
2145
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002146OptionArgVectorSP
2147CommandInterpreter::GetAliasOptions (const char *alias_name)
2148{
2149 OptionArgMap::iterator pos;
2150 OptionArgVectorSP ret_val;
2151
2152 std::string alias (alias_name);
2153
2154 if (HasAliasOptions())
2155 {
2156 pos = m_alias_options.find (alias);
2157 if (pos != m_alias_options.end())
2158 ret_val = pos->second;
2159 }
2160
2161 return ret_val;
2162}
2163
2164void
2165CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2166{
2167 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2168 if (pos != m_alias_options.end())
2169 {
2170 m_alias_options.erase (pos);
2171 }
2172}
2173
2174void
2175CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2176{
2177 m_alias_options[alias_name] = option_arg_vector_sp;
2178}
2179
2180bool
2181CommandInterpreter::HasCommands ()
2182{
2183 return (!m_command_dict.empty());
2184}
2185
2186bool
2187CommandInterpreter::HasAliases ()
2188{
2189 return (!m_alias_dict.empty());
2190}
2191
2192bool
2193CommandInterpreter::HasUserCommands ()
2194{
2195 return (!m_user_dict.empty());
2196}
2197
2198bool
2199CommandInterpreter::HasAliasOptions ()
2200{
2201 return (!m_alias_options.empty());
2202}
2203
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002204void
Caroline Tice4ab31c92010-10-12 21:57:09 +00002205CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2206 const char *alias_name,
2207 Args &cmd_args,
Caroline Ticed9d63362010-12-07 19:58:26 +00002208 std::string &raw_input_string,
Caroline Tice4ab31c92010-10-12 21:57:09 +00002209 CommandReturnObject &result)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002210{
2211 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Ticed9d63362010-12-07 19:58:26 +00002212
2213 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002214
Caroline Ticed9d63362010-12-07 19:58:26 +00002215 // Make sure that the alias name is the 0th element in cmd_args
2216 std::string alias_name_str = alias_name;
2217 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2218 cmd_args.Unshift (alias_name);
2219
2220 Args new_args (alias_cmd_obj->GetCommandName());
2221 if (new_args.GetArgumentCount() == 2)
2222 new_args.Shift();
2223
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002224 if (option_arg_vector_sp.get())
2225 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002226 if (wants_raw_input)
2227 {
2228 // We have a command that both has command options and takes raw input. Make *sure* it has a
2229 // " -- " in the right place in the raw_input_string.
2230 size_t pos = raw_input_string.find(" -- ");
2231 if (pos == std::string::npos)
2232 {
2233 // None found; assume it goes at the beginning of the raw input string
2234 raw_input_string.insert (0, " -- ");
2235 }
2236 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002237
2238 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Greg Claytonc7bece562013-01-25 18:06:21 +00002239 const size_t old_size = cmd_args.GetArgumentCount();
Caroline Tice4ab31c92010-10-12 21:57:09 +00002240 std::vector<bool> used (old_size + 1, false);
2241
2242 used[0] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002243
Andy Gibbsa297a972013-06-19 19:04:53 +00002244 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002245 {
2246 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Ticed9d63362010-12-07 19:58:26 +00002247 OptionArgValue value_pair = option_pair.second;
2248 int value_type = value_pair.first;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002249 std::string option = option_pair.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00002250 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002251 if (option.compare ("<argument>") == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002252 {
2253 if (!wants_raw_input
2254 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2255 new_args.AppendArgument (value.c_str());
2256 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002257 else
2258 {
Virgile Belloe2607b52013-09-05 16:42:23 +00002259 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002260 new_args.AppendArgument (option.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002261 if (value.compare ("<no-argument>") != 0)
2262 {
2263 int index = GetOptionArgumentPosition (value.c_str());
2264 if (index == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002265 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002266 // value was NOT a positional argument; must be a real value
Virgile Belloe2607b52013-09-05 16:42:23 +00002267 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002268 new_args.AppendArgument (value.c_str());
2269 else
2270 {
2271 char buffer[255];
2272 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2273 new_args.AppendArgument (buffer);
2274 }
2275
2276 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002277 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002278 {
2279 result.AppendErrorWithFormat
2280 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2281 index);
2282 result.SetStatus (eReturnStatusFailed);
2283 return;
2284 }
2285 else
2286 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002287 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2288 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2289 if (strpos != std::string::npos)
2290 {
2291 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2292 }
2293
Virgile Belloe2607b52013-09-05 16:42:23 +00002294 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002295 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2296 else
2297 {
2298 char buffer[255];
2299 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2300 cmd_args.GetArgumentAtIndex (index));
2301 new_args.AppendArgument (buffer);
2302 }
Caroline Tice4ab31c92010-10-12 21:57:09 +00002303 used[index] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002304 }
2305 }
2306 }
2307 }
2308
Andy Gibbsa297a972013-06-19 19:04:53 +00002309 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002310 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002311 if (!used[j] && !wants_raw_input)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002312 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2313 }
2314
2315 cmd_args.Clear();
2316 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2317 }
2318 else
2319 {
2320 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Ticed9d63362010-12-07 19:58:26 +00002321 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2322 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2323 // input string.
2324 if (wants_raw_input)
2325 {
2326 cmd_args.Clear();
2327 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2328 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002329 return;
2330 }
2331
2332 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2333 return;
2334}
2335
2336
2337int
2338CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2339{
2340 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2341 // of zero.
2342
2343 char *cptr = (char *) in_string;
2344
2345 // Does it start with '%'
2346 if (cptr[0] == '%')
2347 {
2348 ++cptr;
2349
2350 // Is the rest of it entirely digits?
2351 if (isdigit (cptr[0]))
2352 {
2353 const char *start = cptr;
2354 while (isdigit (cptr[0]))
2355 ++cptr;
2356
2357 // We've gotten to the end of the digits; are we at the end of the string?
2358 if (cptr[0] == '\0')
2359 position = atoi (start);
2360 }
2361 }
2362
2363 return position;
2364}
2365
2366void
2367CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2368{
Jim Ingham16e0c682011-08-12 23:34:31 +00002369 FileSpec init_file;
Greg Clayton14a35512011-09-11 00:01:44 +00002370 if (in_cwd)
Jim Ingham16e0c682011-08-12 23:34:31 +00002371 {
Greg Clayton14a35512011-09-11 00:01:44 +00002372 // In the current working directory we don't load any program specific
2373 // .lldbinit files, we only look for a "./.lldbinit" file.
2374 if (m_skip_lldbinit_files)
2375 return;
2376
2377 init_file.SetFile ("./.lldbinit", true);
Jim Ingham16e0c682011-08-12 23:34:31 +00002378 }
Greg Clayton14a35512011-09-11 00:01:44 +00002379 else
Jim Ingham16e0c682011-08-12 23:34:31 +00002380 {
Greg Clayton14a35512011-09-11 00:01:44 +00002381 // If we aren't looking in the current working directory we are looking
2382 // in the home directory. We will first see if there is an application
2383 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2384 // "-" and the name of the program. If this file doesn't exist, we fall
2385 // back to just the "~/.lldbinit" file. We also obey any requests to not
2386 // load the init files.
Zachary Turnera21fee02014-08-21 21:49:24 +00002387 llvm::SmallString<64> home_dir_path;
2388 llvm::sys::path::home_directory(home_dir_path);
2389 FileSpec profilePath(home_dir_path.c_str(), false);
Zachary Turner9e757b72014-07-28 16:45:05 +00002390 profilePath.AppendPathComponent(".lldbinit");
2391 std::string init_file_path = profilePath.GetPath();
Greg Clayton14a35512011-09-11 00:01:44 +00002392
2393 if (m_skip_app_init_files == false)
2394 {
Zachary Turnera21fee02014-08-21 21:49:24 +00002395 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
Greg Clayton14a35512011-09-11 00:01:44 +00002396 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham16e0c682011-08-12 23:34:31 +00002397
Greg Clayton14a35512011-09-11 00:01:44 +00002398 if (program_name)
2399 {
2400 char program_init_file_name[PATH_MAX];
Zachary Turner9e757b72014-07-28 16:45:05 +00002401 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path.c_str(), program_name);
Greg Clayton14a35512011-09-11 00:01:44 +00002402 init_file.SetFile (program_init_file_name, true);
2403 if (!init_file.Exists())
2404 init_file.Clear();
2405 }
2406 }
2407
2408 if (!init_file && !m_skip_lldbinit_files)
Zachary Turner9e757b72014-07-28 16:45:05 +00002409 init_file.SetFile (init_file_path.c_str(), false);
Greg Clayton14a35512011-09-11 00:01:44 +00002410 }
2411
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002412 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2413 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2414
2415 if (init_file.Exists())
2416 {
Greg Clayton44d93782014-01-27 23:43:24 +00002417 const bool saved_batch = SetBatchCommandMode (true);
Greg Clayton340b0302014-02-05 17:57:57 +00002418 HandleCommandsFromFile (init_file,
Ed Masted78c9572014-04-20 00:31:37 +00002419 nullptr, // Execution context
Greg Clayton340b0302014-02-05 17:57:57 +00002420 eLazyBoolYes, // Stop on continue
2421 eLazyBoolNo, // Stop on error
2422 eLazyBoolNo, // Don't echo commands
2423 eLazyBoolNo, // Don't print command output
2424 eLazyBoolNo, // Don't add the commands that are sourced into the history buffer
2425 result);
Greg Clayton44d93782014-01-27 23:43:24 +00002426 SetBatchCommandMode (saved_batch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002427 }
2428 else
2429 {
2430 // nothing to be done if the file doesn't exist
2431 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2432 }
2433}
2434
Greg Clayton8b82f082011-04-12 05:54:46 +00002435PlatformSP
2436CommandInterpreter::GetPlatform (bool prefer_target_platform)
2437{
2438 PlatformSP platform_sp;
Greg Claytonc14ee322011-09-22 04:58:26 +00002439 if (prefer_target_platform)
2440 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002441 ExecutionContext exe_ctx(GetExecutionContext());
2442 Target *target = exe_ctx.GetTargetPtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002443 if (target)
2444 platform_sp = target->GetPlatform();
2445 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002446
2447 if (!platform_sp)
2448 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2449 return platform_sp;
2450}
2451
Jim Inghame16c50a2011-02-18 00:54:25 +00002452void
Jim Inghambad87fe2011-03-11 01:51:49 +00002453CommandInterpreter::HandleCommands (const StringList &commands,
Jim Inghame16c50a2011-02-18 00:54:25 +00002454 ExecutionContext *override_context,
2455 bool stop_on_continue,
2456 bool stop_on_error,
2457 bool echo_commands,
2458 bool print_results,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002459 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002460 CommandReturnObject &result)
2461{
2462 size_t num_lines = commands.GetSize();
Jim Inghame16c50a2011-02-18 00:54:25 +00002463
2464 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2465 // Make sure you reset this value anywhere you return from the function.
2466
2467 bool old_async_execution = m_debugger.GetAsyncExecution();
2468
2469 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2470 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2471
Ed Masted78c9572014-04-20 00:31:37 +00002472 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00002473 UpdateExecutionContext (override_context);
Jim Inghame16c50a2011-02-18 00:54:25 +00002474
2475 if (!stop_on_continue)
2476 {
2477 m_debugger.SetAsyncExecution (false);
2478 }
2479
Andy Gibbsa297a972013-06-19 19:04:53 +00002480 for (size_t idx = 0; idx < num_lines; idx++)
Jim Inghame16c50a2011-02-18 00:54:25 +00002481 {
2482 const char *cmd = commands.GetStringAtIndex(idx);
2483 if (cmd[0] == '\0')
2484 continue;
2485
Jim Inghame16c50a2011-02-18 00:54:25 +00002486 if (echo_commands)
2487 {
2488 result.AppendMessageWithFormat ("%s %s\n",
Greg Clayton44d93782014-01-27 23:43:24 +00002489 m_debugger.GetPrompt(),
2490 cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002491 }
2492
Greg Clayton9d0402b2011-02-20 02:15:07 +00002493 CommandReturnObject tmp_result;
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002494 // If override_context is not NULL, pass no_context_switching = true for
2495 // HandleCommand() since we updated our context already.
Jim Ingham076b7fc2013-05-02 23:15:37 +00002496
2497 // We might call into a regex or alias command, in which case the add_to_history will get lost. This
2498 // m_command_source_depth dingus is the way we turn off adding to the history in that case, so set it up here.
2499 if (!add_to_history)
2500 m_command_source_depth++;
Enrico Granata5f5ab602012-05-31 01:09:06 +00002501 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Ed Masted78c9572014-04-20 00:31:37 +00002502 nullptr, /* override_context */
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002503 true, /* repeat_on_empty_command */
Ed Masted78c9572014-04-20 00:31:37 +00002504 override_context != nullptr /* no_context_switching */);
Jim Ingham076b7fc2013-05-02 23:15:37 +00002505 if (!add_to_history)
2506 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002507
2508 if (print_results)
2509 {
2510 if (tmp_result.Succeeded())
Jim Ingham85e8b812011-02-19 02:53:09 +00002511 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Inghame16c50a2011-02-18 00:54:25 +00002512 }
2513
2514 if (!success || !tmp_result.Succeeded())
2515 {
Jim Inghama5038812012-04-24 02:25:07 +00002516 const char *error_msg = tmp_result.GetErrorData();
Ed Masted78c9572014-04-20 00:31:37 +00002517 if (error_msg == nullptr || error_msg[0] == '\0')
Jim Inghama5038812012-04-24 02:25:07 +00002518 error_msg = "<unknown error>.\n";
Jim Inghame16c50a2011-02-18 00:54:25 +00002519 if (stop_on_error)
2520 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002521 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' failed with %s",
2522 (uint64_t)idx, cmd, error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002523 result.SetStatus (eReturnStatusFailed);
2524 m_debugger.SetAsyncExecution (old_async_execution);
2525 return;
2526 }
2527 else if (print_results)
2528 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002529 result.AppendMessageWithFormat ("Command #%" PRIu64 " '%s' failed with %s",
2530 (uint64_t)idx + 1,
Jim Inghame16c50a2011-02-18 00:54:25 +00002531 cmd,
Jim Inghama5038812012-04-24 02:25:07 +00002532 error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002533 }
2534 }
2535
Caroline Tice969ed3d2011-05-02 20:41:46 +00002536 if (result.GetImmediateOutputStream())
2537 result.GetImmediateOutputStream()->Flush();
2538
2539 if (result.GetImmediateErrorStream())
2540 result.GetImmediateErrorStream()->Flush();
2541
Jim Inghame16c50a2011-02-18 00:54:25 +00002542 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2543 // could be running (for instance in Breakpoint Commands.
2544 // So we check the return value to see if it is has running in it.
2545 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2546 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2547 {
2548 if (stop_on_continue)
2549 {
2550 // If we caused the target to proceed, and we're going to stop in that case, set the
2551 // status in our real result before returning. This is an error if the continue was not the
2552 // last command in the set of commands to be run.
2553 if (idx != num_lines - 1)
Deepak Panickal99fbc072014-03-03 15:39:47 +00002554 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' continued the target.\n",
2555 (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002556 else
Deepak Panickal99fbc072014-03-03 15:39:47 +00002557 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' continued the target.\n", (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002558
2559 result.SetStatus(tmp_result.GetStatus());
2560 m_debugger.SetAsyncExecution (old_async_execution);
2561
2562 return;
2563 }
2564 }
2565
2566 }
2567
2568 result.SetStatus (eReturnStatusSuccessFinishResult);
2569 m_debugger.SetAsyncExecution (old_async_execution);
2570
2571 return;
2572}
2573
Greg Clayton340b0302014-02-05 17:57:57 +00002574// Make flags that we can pass into the IOHandler so our delegates can do the right thing
2575enum {
2576 eHandleCommandFlagStopOnContinue = (1u << 0),
2577 eHandleCommandFlagStopOnError = (1u << 1),
2578 eHandleCommandFlagEchoCommand = (1u << 2),
2579 eHandleCommandFlagPrintResult = (1u << 3)
2580};
2581
Jim Inghame16c50a2011-02-18 00:54:25 +00002582void
2583CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2584 ExecutionContext *context,
Greg Clayton340b0302014-02-05 17:57:57 +00002585 LazyBool stop_on_continue,
2586 LazyBool stop_on_error,
2587 LazyBool echo_command,
2588 LazyBool print_result,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002589 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002590 CommandReturnObject &result)
2591{
2592 if (cmd_file.Exists())
2593 {
Greg Clayton44d93782014-01-27 23:43:24 +00002594 StreamFileSP input_file_sp (new StreamFile());
2595
2596 std::string cmd_file_path = cmd_file.GetPath();
2597 Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), File::eOpenOptionRead);
2598
2599 if (error.Success())
2600 {
2601 Debugger &debugger = GetDebugger();
2602
Greg Clayton340b0302014-02-05 17:57:57 +00002603 uint32_t flags = 0;
2604
2605 if (stop_on_continue == eLazyBoolCalculate)
2606 {
2607 if (m_command_source_flags.empty())
2608 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002609 // Stop on continue by default
Greg Clayton340b0302014-02-05 17:57:57 +00002610 flags |= eHandleCommandFlagStopOnContinue;
2611 }
2612 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnContinue)
2613 {
2614 flags |= eHandleCommandFlagStopOnContinue;
2615 }
2616 }
2617 else if (stop_on_continue == eLazyBoolYes)
2618 {
2619 flags |= eHandleCommandFlagStopOnContinue;
2620 }
2621
2622 if (stop_on_error == eLazyBoolCalculate)
2623 {
2624 if (m_command_source_flags.empty())
2625 {
2626 if (GetStopCmdSourceOnError())
2627 flags |= eHandleCommandFlagStopOnError;
2628 }
2629 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError)
2630 {
2631 flags |= eHandleCommandFlagStopOnError;
2632 }
2633 }
2634 else if (stop_on_error == eLazyBoolYes)
2635 {
2636 flags |= eHandleCommandFlagStopOnError;
2637 }
2638
2639 if (echo_command == eLazyBoolCalculate)
2640 {
2641 if (m_command_source_flags.empty())
2642 {
2643 // Echo command by default
2644 flags |= eHandleCommandFlagEchoCommand;
2645 }
2646 else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand)
2647 {
2648 flags |= eHandleCommandFlagEchoCommand;
2649 }
2650 }
2651 else if (echo_command == eLazyBoolYes)
2652 {
2653 flags |= eHandleCommandFlagEchoCommand;
2654 }
2655
2656 if (print_result == eLazyBoolCalculate)
2657 {
2658 if (m_command_source_flags.empty())
2659 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002660 // Print output by default
2661 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002662 }
Greg Claytone4e462c2014-02-05 21:03:22 +00002663 else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult)
Greg Clayton340b0302014-02-05 17:57:57 +00002664 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002665 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002666 }
2667 }
2668 else if (print_result == eLazyBoolYes)
2669 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002670 flags |= eHandleCommandFlagPrintResult;
2671 }
2672
2673 if (flags & eHandleCommandFlagPrintResult)
2674 {
Greg Clayton8ee67312014-02-05 21:46:20 +00002675 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", cmd_file_path.c_str());
Greg Clayton340b0302014-02-05 17:57:57 +00002676 }
2677
2678 // Used for inheriting the right settings when "command source" might have
2679 // nested "command source" commands
Greg Claytone4e462c2014-02-05 21:03:22 +00002680 lldb::StreamFileSP empty_stream_sp;
Greg Clayton340b0302014-02-05 17:57:57 +00002681 m_command_source_flags.push_back(flags);
Greg Clayton44d93782014-01-27 23:43:24 +00002682 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
2683 input_file_sp,
Greg Claytone4e462c2014-02-05 21:03:22 +00002684 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader output stream
2685 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader error stream
Greg Clayton340b0302014-02-05 17:57:57 +00002686 flags,
Ed Masted78c9572014-04-20 00:31:37 +00002687 nullptr, // Pass in NULL for "editline_name" so no history is saved, or written
Greg Clayton8ee67312014-02-05 21:46:20 +00002688 debugger.GetPrompt(),
Greg Clayton44d93782014-01-27 23:43:24 +00002689 false, // Not multi-line
Greg Claytonf6913cd2014-03-07 00:53:24 +00002690 0,
Greg Clayton44d93782014-01-27 23:43:24 +00002691 *this));
Greg Clayton8ee67312014-02-05 21:46:20 +00002692 const bool old_async_execution = debugger.GetAsyncExecution();
2693
2694 // Set synchronous execution if we not stopping when we continue
2695 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2696 debugger.SetAsyncExecution (false);
2697
Greg Clayton340b0302014-02-05 17:57:57 +00002698 m_command_source_depth++;
Greg Clayton8ee67312014-02-05 21:46:20 +00002699
2700 debugger.RunIOHandler(io_handler_sp);
Greg Clayton340b0302014-02-05 17:57:57 +00002701 if (!m_command_source_flags.empty())
2702 m_command_source_flags.pop_back();
2703 m_command_source_depth--;
Greg Clayton44d93782014-01-27 23:43:24 +00002704 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Greg Clayton8ee67312014-02-05 21:46:20 +00002705 debugger.SetAsyncExecution (old_async_execution);
Greg Clayton44d93782014-01-27 23:43:24 +00002706 }
2707 else
2708 {
2709 result.AppendErrorWithFormat ("error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(), error.AsCString());
2710 result.SetStatus (eReturnStatusFailed);
2711 }
Greg Clayton8ee67312014-02-05 21:46:20 +00002712
2713
Jim Inghame16c50a2011-02-18 00:54:25 +00002714 }
2715 else
2716 {
2717 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2718 cmd_file.GetFilename().AsCString());
2719 result.SetStatus (eReturnStatusFailed);
2720 return;
2721 }
2722}
2723
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002724ScriptInterpreter *
Enrico Granatab5887262012-10-29 21:18:03 +00002725CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002726{
Ed Masted78c9572014-04-20 00:31:37 +00002727 if (m_script_interpreter_ap.get() != nullptr)
Enrico Granatab5887262012-10-29 21:18:03 +00002728 return m_script_interpreter_ap.get();
2729
2730 if (!can_create)
Ed Masted78c9572014-04-20 00:31:37 +00002731 return nullptr;
Enrico Granatab5887262012-10-29 21:18:03 +00002732
Enrico Granataa29bdad2012-07-10 18:23:48 +00002733 // <rdar://problem/11751427>
2734 // we need to protect the initialization of the script interpreter
2735 // otherwise we could end up with two threads both trying to create
2736 // their instance of it, and for some languages (e.g. Python)
2737 // this is a bulletproof recipe for disaster!
2738 // this needs to be a function-level static because multiple Debugger instances living in the same process
2739 // still need to be isolated and not try to initialize Python concurrently
Enrico Granata8b95df22012-07-10 19:04:14 +00002740 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2741 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granataa29bdad2012-07-10 18:23:48 +00002742
Greg Clayton5160ce52013-03-27 23:08:40 +00002743 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Enrico Granatab5887262012-10-29 21:18:03 +00002744 if (log)
2745 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton66111032010-06-23 01:19:29 +00002746
Caroline Tice2f88aad2011-01-14 00:29:16 +00002747 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2748 switch (script_lang)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002749 {
Greg Claytondce502e2011-11-04 03:34:56 +00002750 case eScriptLanguagePython:
2751#ifndef LLDB_DISABLE_PYTHON
2752 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2753 break;
2754#else
2755 // Fall through to the None case when python is disabled
2756#endif
Caroline Tice2f88aad2011-01-14 00:29:16 +00002757 case eScriptLanguageNone:
2758 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2759 break;
Caroline Tice2f88aad2011-01-14 00:29:16 +00002760 };
2761
2762 return m_script_interpreter_ap.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002763}
2764
2765
2766
2767bool
2768CommandInterpreter::GetSynchronous ()
2769{
2770 return m_synchronous_execution;
2771}
2772
2773void
2774CommandInterpreter::SetSynchronous (bool value)
2775{
Johnny Chenc066ab42010-10-14 01:22:03 +00002776 m_synchronous_execution = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002777}
2778
2779void
2780CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2781 const char *word_text,
2782 const char *separator,
2783 const char *help_text,
Greg Claytonc7bece562013-01-25 18:06:21 +00002784 size_t max_word_len)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002785{
Greg Claytona7015092010-09-18 01:14:36 +00002786 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2787
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002788 int indent_size = max_word_len + strlen (separator) + 2;
2789
2790 strm.IndentMore (indent_size);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002791
2792 StreamString text_strm;
Greg Claytonc7bece562013-01-25 18:06:21 +00002793 text_strm.Printf ("%-*s %s %s", (int)max_word_len, word_text, separator, help_text);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002794
2795 size_t len = text_strm.GetSize();
2796 const char *text = text_strm.GetData();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002797 if (text[len - 1] == '\n')
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002798 {
2799 text_strm.EOL();
2800 len = text_strm.GetSize();
2801 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002802
2803 if (len < max_columns)
2804 {
2805 // Output it as a single line.
2806 strm.Printf ("%s", text);
2807 }
2808 else
2809 {
2810 // We need to break it up into multiple lines.
2811 bool first_line = true;
2812 int text_width;
Greg Claytonc7bece562013-01-25 18:06:21 +00002813 size_t start = 0;
2814 size_t end = start;
2815 const size_t final_end = strlen (text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002816
2817 while (end < final_end)
2818 {
2819 if (first_line)
2820 text_width = max_columns - 1;
2821 else
2822 text_width = max_columns - indent_size - 1;
2823
2824 // Don't start the 'text' on a space, since we're already outputting the indentation.
2825 if (!first_line)
2826 {
2827 while ((start < final_end) && (text[start] == ' '))
2828 start++;
2829 }
2830
2831 end = start + text_width;
2832 if (end > final_end)
2833 end = final_end;
2834 else
2835 {
2836 // If we're not at the end of the text, make sure we break the line on white space.
2837 while (end > start
2838 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2839 end--;
Greg Clayton67cc0632012-08-22 17:17:09 +00002840 assert (end > 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002841 }
2842
Greg Claytonc7bece562013-01-25 18:06:21 +00002843 const size_t sub_len = end - start;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002844 if (start != 0)
2845 strm.EOL();
2846 if (!first_line)
2847 strm.Indent();
2848 else
2849 first_line = false;
2850 assert (start <= final_end);
2851 assert (start + sub_len <= final_end);
2852 if (sub_len > 0)
2853 strm.Write (text + start, sub_len);
2854 start = end + 1;
2855 }
2856 }
2857 strm.EOL();
2858 strm.IndentLess(indent_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002859}
2860
2861void
Enrico Granata82a7d982011-07-07 00:38:40 +00002862CommandInterpreter::OutputHelpText (Stream &strm,
2863 const char *word_text,
2864 const char *separator,
2865 const char *help_text,
2866 uint32_t max_word_len)
2867{
2868 int indent_size = max_word_len + strlen (separator) + 2;
2869
2870 strm.IndentMore (indent_size);
2871
2872 StreamString text_strm;
2873 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2874
2875 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata82a7d982011-07-07 00:38:40 +00002876
2877 size_t len = text_strm.GetSize();
2878 const char *text = text_strm.GetData();
2879
2880 uint32_t chars_left = max_columns;
2881
2882 for (uint32_t i = 0; i < len; i++)
2883 {
2884 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2885 {
Enrico Granata82a7d982011-07-07 00:38:40 +00002886 chars_left = max_columns - indent_size;
2887 strm.EOL();
2888 strm.Indent();
2889 }
2890 else
2891 {
2892 strm.PutChar(text[i]);
2893 chars_left--;
2894 }
2895
2896 }
2897
2898 strm.EOL();
2899 strm.IndentLess(indent_size);
2900}
2901
2902void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002903CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
Jim Inghamaf3753e2013-05-17 01:30:37 +00002904 StringList &commands_help, bool search_builtin_commands, bool search_user_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002905{
2906 CommandObject::CommandMap::const_iterator pos;
2907
Jim Inghamaf3753e2013-05-17 01:30:37 +00002908 if (search_builtin_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002909 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00002910 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002911 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00002912 const char *command_name = pos->first.c_str();
2913 CommandObject *cmd_obj = pos->second.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002914
Jim Inghamaf3753e2013-05-17 01:30:37 +00002915 if (cmd_obj->HelpTextContainsWord (search_word))
2916 {
2917 commands_found.AppendString (command_name);
2918 commands_help.AppendString (cmd_obj->GetHelp());
2919 }
2920
2921 if (cmd_obj->IsMultiwordObject())
2922 cmd_obj->AproposAllSubCommands (command_name,
2923 search_word,
2924 commands_found,
2925 commands_help);
2926
2927 }
2928 }
2929
2930 if (search_user_commands)
2931 {
2932 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
2933 {
2934 const char *command_name = pos->first.c_str();
2935 CommandObject *cmd_obj = pos->second.get();
2936
2937 if (cmd_obj->HelpTextContainsWord (search_word))
2938 {
2939 commands_found.AppendString (command_name);
2940 commands_help.AppendString (cmd_obj->GetHelp());
2941 }
2942
2943 if (cmd_obj->IsMultiwordObject())
2944 cmd_obj->AproposAllSubCommands (command_name,
2945 search_word,
2946 commands_found,
2947 commands_help);
2948
2949 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002950 }
2951}
Greg Clayton8b82f082011-04-12 05:54:46 +00002952
Greg Clayton8b82f082011-04-12 05:54:46 +00002953void
2954CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2955{
Ed Masted78c9572014-04-20 00:31:37 +00002956 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00002957 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002958 m_exe_ctx_ref = *override_context;
Greg Clayton8b82f082011-04-12 05:54:46 +00002959 }
2960 else
2961 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002962 const bool adopt_selected = true;
2963 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Clayton8b82f082011-04-12 05:54:46 +00002964 }
2965}
Greg Clayton44d93782014-01-27 23:43:24 +00002966
2967
2968size_t
2969CommandInterpreter::GetProcessOutput ()
2970{
2971 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
2972 char stdio_buffer[1024];
2973 size_t len;
2974 size_t total_bytes = 0;
2975 Error error;
2976 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
2977 if (target_sp)
2978 {
2979 ProcessSP process_sp (target_sp->GetProcessSP());
2980 if (process_sp)
2981 {
2982 while ((len = process_sp->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2983 {
2984 size_t bytes_written = len;
2985 m_debugger.GetOutputFile()->Write (stdio_buffer, bytes_written);
2986 total_bytes += len;
2987 }
2988 while ((len = process_sp->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2989 {
2990 size_t bytes_written = len;
2991 m_debugger.GetErrorFile()->Write (stdio_buffer, bytes_written);
2992 total_bytes += len;
2993 }
2994 }
2995 }
2996 return total_bytes;
2997}
2998
2999void
3000CommandInterpreter::IOHandlerInputComplete (IOHandler &io_handler, std::string &line)
3001{
Greg Clayton340b0302014-02-05 17:57:57 +00003002 const bool is_interactive = io_handler.GetIsInteractive();
3003 if (is_interactive == false)
3004 {
3005 // When we are not interactive, don't execute blank lines. This will happen
3006 // sourcing a commands file. We don't want blank lines to repeat the previous
3007 // command and cause any errors to occur (like redefining an alias, get an error
3008 // and stop parsing the commands file).
3009 if (line.empty())
3010 return;
3011
3012 // When using a non-interactive file handle (like when sourcing commands from a file)
3013 // we need to echo the command out so we don't just see the command output and no
3014 // command...
3015 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
3016 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(), line.c_str());
3017 }
3018
Greg Clayton44d93782014-01-27 23:43:24 +00003019 lldb_private::CommandReturnObject result;
3020 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
3021
Greg Clayton44d93782014-01-27 23:43:24 +00003022 // Now emit the command output text from the command we just executed
Greg Clayton340b0302014-02-05 17:57:57 +00003023 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult))
3024 {
3025 // Display any STDOUT/STDERR _prior_ to emitting the command result text
3026 GetProcessOutput ();
3027
Greg Clayton8ee67312014-02-05 21:46:20 +00003028 if (!result.GetImmediateOutputStream())
3029 {
3030 const char *output = result.GetOutputData();
3031 if (output && output[0])
3032 io_handler.GetOutputStreamFile()->PutCString(output);
3033 }
Greg Clayton44d93782014-01-27 23:43:24 +00003034
Greg Clayton340b0302014-02-05 17:57:57 +00003035 // Now emit the command error text from the command we just executed
Greg Clayton8ee67312014-02-05 21:46:20 +00003036 if (!result.GetImmediateErrorStream())
3037 {
3038 const char *error = result.GetErrorData();
3039 if (error && error[0])
3040 io_handler.GetErrorStreamFile()->PutCString(error);
3041 }
Greg Clayton340b0302014-02-05 17:57:57 +00003042 }
Greg Clayton44d93782014-01-27 23:43:24 +00003043
3044 switch (result.GetStatus())
3045 {
3046 case eReturnStatusInvalid:
3047 case eReturnStatusSuccessFinishNoResult:
3048 case eReturnStatusSuccessFinishResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003049 case eReturnStatusStarted:
3050 break;
3051
Greg Clayton44d93782014-01-27 23:43:24 +00003052 case eReturnStatusSuccessContinuingNoResult:
3053 case eReturnStatusSuccessContinuingResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003054 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
3055 io_handler.SetIsDone(true);
3056 break;
3057
Greg Clayton44d93782014-01-27 23:43:24 +00003058 case eReturnStatusFailed:
Greg Clayton340b0302014-02-05 17:57:57 +00003059 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
3060 io_handler.SetIsDone(true);
Greg Clayton44d93782014-01-27 23:43:24 +00003061 break;
3062
3063 case eReturnStatusQuit:
3064 io_handler.SetIsDone(true);
3065 break;
3066 }
3067}
3068
Greg Claytonf0066ad2014-05-02 00:45:31 +00003069bool
3070CommandInterpreter::IOHandlerInterrupt (IOHandler &io_handler)
3071{
3072 ExecutionContext exe_ctx (GetExecutionContext());
3073 Process *process = exe_ctx.GetProcessPtr();
3074
3075 if (process)
3076 {
3077 StateType state = process->GetState();
3078 if (StateIsRunningState(state))
3079 {
3080 process->Halt();
3081 return true; // Don't do any updating when we are running
3082 }
3083 }
3084 return false;
3085}
3086
Greg Clayton44d93782014-01-27 23:43:24 +00003087void
3088CommandInterpreter::GetLLDBCommandsFromIOHandler (const char *prompt,
3089 IOHandlerDelegate &delegate,
3090 bool asynchronously,
3091 void *baton)
3092{
3093 Debugger &debugger = GetDebugger();
3094 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
3095 "lldb", // Name of input reader for history
3096 prompt, // Prompt
3097 true, // Get multiple lines
Greg Claytonf6913cd2014-03-07 00:53:24 +00003098 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003099 delegate)); // IOHandlerDelegate
3100
3101 if (io_handler_sp)
3102 {
3103 io_handler_sp->SetUserData (baton);
3104 if (asynchronously)
3105 debugger.PushIOHandler(io_handler_sp);
3106 else
3107 debugger.RunIOHandler(io_handler_sp);
3108 }
3109
3110}
3111
3112
3113void
3114CommandInterpreter::GetPythonCommandsFromIOHandler (const char *prompt,
3115 IOHandlerDelegate &delegate,
3116 bool asynchronously,
3117 void *baton)
3118{
3119 Debugger &debugger = GetDebugger();
3120 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
3121 "lldb-python", // Name of input reader for history
3122 prompt, // Prompt
3123 true, // Get multiple lines
Greg Claytonf6913cd2014-03-07 00:53:24 +00003124 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003125 delegate)); // IOHandlerDelegate
3126
3127 if (io_handler_sp)
3128 {
3129 io_handler_sp->SetUserData (baton);
3130 if (asynchronously)
3131 debugger.PushIOHandler(io_handler_sp);
3132 else
3133 debugger.RunIOHandler(io_handler_sp);
3134 }
3135
3136}
3137
3138bool
3139CommandInterpreter::IsActive ()
3140{
3141 return m_debugger.IsTopIOHandler (m_command_io_handler_sp);
3142}
3143
3144void
3145CommandInterpreter::RunCommandInterpreter(bool auto_handle_events,
3146 bool spawn_thread)
3147{
Greg Clayton380f3d82014-07-31 19:46:19 +00003148 // Only get one line at a time
3149 const bool multiple_lines = false;
3150
3151 // Always re-create the IOHandlerEditline in case the input
3152 // changed. The old instance might have had a non-interactive
3153 // input and now it does or vice versa.
3154 m_command_io_handler_sp.reset(new IOHandlerEditline (m_debugger,
3155 m_debugger.GetInputFile(),
3156 m_debugger.GetOutputFile(),
3157 m_debugger.GetErrorFile(),
3158 eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult,
3159 "lldb",
3160 m_debugger.GetPrompt(),
3161 multiple_lines,
3162 0, // Don't show line numbers
3163 *this));
Greg Clayton06357c92014-07-30 17:38:47 +00003164
Greg Clayton44d93782014-01-27 23:43:24 +00003165 m_debugger.PushIOHandler(m_command_io_handler_sp);
3166
3167 if (auto_handle_events)
3168 m_debugger.StartEventHandlerThread();
3169
3170 if (spawn_thread)
3171 {
3172 m_debugger.StartIOHandlerThread();
3173 }
3174 else
3175 {
3176 m_debugger.ExecuteIOHanders();
3177
3178 if (auto_handle_events)
3179 m_debugger.StopEventHandlerThread();
3180 }
3181
3182}
3183