blob: 33a0912307ddc59d29aa4afed92d519edd6cec67 [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"
Enrico Granatab5887262012-10-29 21:18:03 +000054
55#include "lldb/Interpreter/Args.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000056#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000057#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000058#include "lldb/Interpreter/CommandReturnObject.h"
Enrico Granatab5887262012-10-29 21:18:03 +000059#include "lldb/Interpreter/Options.h"
60#include "lldb/Interpreter/ScriptInterpreterNone.h"
61#include "lldb/Interpreter/ScriptInterpreterPython.h"
62
63
Chris Lattner30fdc8d2010-06-08 16:52:24 +000064#include "lldb/Target/Process.h"
65#include "lldb/Target/Thread.h"
66#include "lldb/Target/TargetList.h"
67
Enrico Granatab5887262012-10-29 21:18:03 +000068#include "lldb/Utility/CleanUp.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000069
Saleem Abdulrasool28606952014-06-27 05:17:41 +000070#include "llvm/ADT/STLExtras.h"
71
Chris Lattner30fdc8d2010-06-08 16:52:24 +000072using namespace lldb;
73using namespace lldb_private;
74
Greg Clayton754a9362012-08-23 00:22:02 +000075
76static PropertyDefinition
77g_properties[] =
78{
Ed Masted78c9572014-04-20 00:31:37 +000079 { "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." },
80 { "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." },
81 { "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." },
82 { nullptr , OptionValue::eTypeInvalid, true, 0 , nullptr, nullptr, nullptr }
Greg Clayton754a9362012-08-23 00:22:02 +000083};
84
85enum
86{
Enrico Granatabcba2b22013-01-17 21:36:19 +000087 ePropertyExpandRegexAliases = 0,
Enrico Granata012d4fc2013-06-11 01:26:35 +000088 ePropertyPromptOnQuit = 1,
89 ePropertyStopCmdSourceOnError = 2
Greg Clayton754a9362012-08-23 00:22:02 +000090};
91
Jim Ingham4bddaeb2012-02-16 06:50:00 +000092ConstString &
93CommandInterpreter::GetStaticBroadcasterClass ()
94{
95 static ConstString class_name ("lldb.commandInterpreter");
96 return class_name;
97}
98
Chris Lattner30fdc8d2010-06-08 16:52:24 +000099CommandInterpreter::CommandInterpreter
100(
Greg Clayton66111032010-06-23 01:19:29 +0000101 Debugger &debugger,
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000102 ScriptLanguage script_language,
Greg Clayton66111032010-06-23 01:19:29 +0000103 bool synchronous_execution
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000104) :
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000105 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton754a9362012-08-23 00:22:02 +0000106 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton44d93782014-01-27 23:43:24 +0000107 IOHandlerDelegate (IOHandlerDelegate::Completion::LLDBCommand),
Greg Clayton66111032010-06-23 01:19:29 +0000108 m_debugger (debugger),
Greg Clayton6eee5aa2010-10-11 01:05:37 +0000109 m_synchronous_execution (synchronous_execution),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000110 m_skip_lldbinit_files (false),
Jim Ingham16e0c682011-08-12 23:34:31 +0000111 m_skip_app_init_files (false),
Jim Inghame16c50a2011-02-18 00:54:25 +0000112 m_script_interpreter_ap (),
Greg Clayton44d93782014-01-27 23:43:24 +0000113 m_command_io_handler_sp (),
Caroline Ticed61c10b2011-06-16 16:27:19 +0000114 m_comment_char ('#'),
Johnny Chen4ac1d9e2012-08-09 22:06:10 +0000115 m_batch_command_mode (false),
Enrico Granata5f5ab602012-05-31 01:09:06 +0000116 m_truncation_warning(eNoTruncation),
117 m_command_source_depth (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000118{
Greg Clayton67cc0632012-08-22 17:17:09 +0000119 debugger.SetScriptLanguage (script_language);
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000120 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
121 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton67cc0632012-08-22 17:17:09 +0000122 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000123 CheckInWithManager ();
Greg Clayton754a9362012-08-23 00:22:02 +0000124 m_collection_sp->Initialize (g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000125}
126
Greg Clayton754a9362012-08-23 00:22:02 +0000127bool
128CommandInterpreter::GetExpandRegexAliases () const
129{
130 const uint32_t idx = ePropertyExpandRegexAliases;
Ed Masted78c9572014-04-20 00:31:37 +0000131 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000132}
133
Enrico Granatabcba2b22013-01-17 21:36:19 +0000134bool
135CommandInterpreter::GetPromptOnQuit () const
136{
137 const uint32_t idx = ePropertyPromptOnQuit;
Ed Masted78c9572014-04-20 00:31:37 +0000138 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000139}
Greg Clayton754a9362012-08-23 00:22:02 +0000140
Enrico Granata012d4fc2013-06-11 01:26:35 +0000141bool
142CommandInterpreter::GetStopCmdSourceOnError () const
143{
144 const uint32_t idx = ePropertyStopCmdSourceOnError;
Ed Masted78c9572014-04-20 00:31:37 +0000145 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000146}
147
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000148void
149CommandInterpreter::Initialize ()
150{
151 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
152
153 CommandReturnObject result;
154
155 LoadCommandDictionary ();
156
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000157 // Set up some initial aliases.
Caroline Ticeca90c472011-05-06 21:37:15 +0000158 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
159 if (cmd_obj_sp)
160 {
161 AddAlias ("q", cmd_obj_sp);
162 AddAlias ("exit", cmd_obj_sp);
163 }
Sean Callanan247e62a2012-05-04 23:15:02 +0000164
Johnny Chen6d675242012-08-24 18:15:45 +0000165 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callanan247e62a2012-05-04 23:15:02 +0000166 if (cmd_obj_sp)
167 {
168 AddAlias ("attach", cmd_obj_sp);
169 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000170
Johnny Chen6d675242012-08-24 18:15:45 +0000171 cmd_obj_sp = GetCommandSPExact ("process detach",false);
172 if (cmd_obj_sp)
173 {
174 AddAlias ("detach", cmd_obj_sp);
175 }
176
Caroline Ticeca90c472011-05-06 21:37:15 +0000177 cmd_obj_sp = GetCommandSPExact ("process continue", false);
178 if (cmd_obj_sp)
179 {
180 AddAlias ("c", cmd_obj_sp);
181 AddAlias ("continue", cmd_obj_sp);
182 }
183
184 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
185 if (cmd_obj_sp)
186 AddAlias ("b", cmd_obj_sp);
187
Jim Inghamca36cd12012-10-05 19:16:31 +0000188 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
189 if (cmd_obj_sp)
190 AddAlias ("tbreak", cmd_obj_sp);
191
Caroline Ticeca90c472011-05-06 21:37:15 +0000192 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
193 if (cmd_obj_sp)
Jason Molendaf385f122011-10-22 00:47:41 +0000194 {
195 AddAlias ("stepi", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000196 AddAlias ("si", cmd_obj_sp);
Jason Molendaf385f122011-10-22 00:47:41 +0000197 }
198
199 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
200 if (cmd_obj_sp)
201 {
202 AddAlias ("nexti", cmd_obj_sp);
203 AddAlias ("ni", cmd_obj_sp);
204 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000205
206 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
207 if (cmd_obj_sp)
208 {
209 AddAlias ("s", cmd_obj_sp);
210 AddAlias ("step", cmd_obj_sp);
211 }
212
213 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
214 if (cmd_obj_sp)
215 {
216 AddAlias ("n", cmd_obj_sp);
217 AddAlias ("next", cmd_obj_sp);
218 }
219
220 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
221 if (cmd_obj_sp)
222 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000223 AddAlias ("finish", cmd_obj_sp);
224 }
225
Jim Ingham6d6d1072011-12-02 01:12:59 +0000226 cmd_obj_sp = GetCommandSPExact ("frame select", false);
227 if (cmd_obj_sp)
228 {
229 AddAlias ("f", cmd_obj_sp);
230 }
231
Jim Inghamca36cd12012-10-05 19:16:31 +0000232 cmd_obj_sp = GetCommandSPExact ("thread select", false);
233 if (cmd_obj_sp)
234 {
235 AddAlias ("t", cmd_obj_sp);
236 }
237
Richard Mittonf86248d2013-09-12 02:20:34 +0000238 cmd_obj_sp = GetCommandSPExact ("_regexp-jump",false);
239 if (cmd_obj_sp)
240 {
241 AddAlias ("j", cmd_obj_sp);
242 AddAlias ("jump", cmd_obj_sp);
243 }
244
Greg Clayton6bade322013-02-01 23:33:03 +0000245 cmd_obj_sp = GetCommandSPExact ("_regexp-list", false);
Caroline Ticeca90c472011-05-06 21:37:15 +0000246 if (cmd_obj_sp)
247 {
248 AddAlias ("l", cmd_obj_sp);
249 AddAlias ("list", cmd_obj_sp);
250 }
251
Greg Claytonef5651d2013-02-12 18:52:24 +0000252 cmd_obj_sp = GetCommandSPExact ("_regexp-env", false);
253 if (cmd_obj_sp)
254 {
255 AddAlias ("env", cmd_obj_sp);
256 }
257
Caroline Ticeca90c472011-05-06 21:37:15 +0000258 cmd_obj_sp = GetCommandSPExact ("memory read", false);
259 if (cmd_obj_sp)
260 AddAlias ("x", cmd_obj_sp);
261
262 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
263 if (cmd_obj_sp)
264 AddAlias ("up", cmd_obj_sp);
265
266 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
267 if (cmd_obj_sp)
268 AddAlias ("down", cmd_obj_sp);
269
Jason Molenda0c8e0062011-10-25 02:11:20 +0000270 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000271 if (cmd_obj_sp)
272 AddAlias ("display", cmd_obj_sp);
Jim Ingham7e18e422011-10-24 18:37:00 +0000273
274 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
275 if (cmd_obj_sp)
276 AddAlias ("dis", cmd_obj_sp);
277
278 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
279 if (cmd_obj_sp)
280 AddAlias ("di", cmd_obj_sp);
281
282
Jason Molendabc7748b2011-10-22 01:30:52 +0000283
Jason Molenda0c8e0062011-10-25 02:11:20 +0000284 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000285 if (cmd_obj_sp)
286 AddAlias ("undisplay", cmd_obj_sp);
287
Jim Ingham71bf2992012-10-10 16:51:31 +0000288 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
289 if (cmd_obj_sp)
290 AddAlias ("bt", cmd_obj_sp);
291
Caroline Ticeca90c472011-05-06 21:37:15 +0000292 cmd_obj_sp = GetCommandSPExact ("target create", false);
293 if (cmd_obj_sp)
294 AddAlias ("file", cmd_obj_sp);
295
296 cmd_obj_sp = GetCommandSPExact ("target modules", false);
297 if (cmd_obj_sp)
298 AddAlias ("image", cmd_obj_sp);
299
300
301 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghamffba2292011-03-22 02:29:32 +0000302
Caroline Ticeca90c472011-05-06 21:37:15 +0000303 cmd_obj_sp = GetCommandSPExact ("expression", false);
304 if (cmd_obj_sp)
Sean Callanan90e579f2013-04-17 17:23:58 +0000305 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000306 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
307 AddAlias ("p", cmd_obj_sp);
308 AddAlias ("print", cmd_obj_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000309 AddAlias ("call", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000310 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
311 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000312 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000313
314 alias_arguments_vector_sp.reset (new OptionArgVector);
Greg Clayton9e57dcd2013-05-15 01:03:08 +0000315 ProcessAliasOptionsArgs (cmd_obj_sp, "-O -- ", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000316 AddAlias ("po", cmd_obj_sp);
317 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
318 }
319
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000320 cmd_obj_sp = GetCommandSPExact ("process kill", false);
321 if (cmd_obj_sp)
Greg Claytone86fd742012-09-27 00:02:27 +0000322 {
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000323 AddAlias ("kill", cmd_obj_sp);
Greg Claytone86fd742012-09-27 00:02:27 +0000324 }
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000325
Caroline Ticeca90c472011-05-06 21:37:15 +0000326 cmd_obj_sp = GetCommandSPExact ("process launch", false);
327 if (cmd_obj_sp)
328 {
329 alias_arguments_vector_sp.reset (new OptionArgVector);
Todd Fiala013434e2014-07-09 01:29:05 +0000330#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Jason Molenda85da3122012-07-06 02:46:23 +0000331 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
332#else
Ed Maste7c566672013-09-05 21:38:45 +0000333 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=" LLDB_DEFAULT_SHELL " --", alias_arguments_vector_sp);
Jason Molenda85da3122012-07-06 02:46:23 +0000334#endif
Caroline Ticeca90c472011-05-06 21:37:15 +0000335 AddAlias ("r", cmd_obj_sp);
336 AddAlias ("run", cmd_obj_sp);
337 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
338 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
339 }
Greg Clayton843d62d2012-03-29 21:47:51 +0000340
341 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
342 if (cmd_obj_sp)
343 {
344 AddAlias ("add-dsym", cmd_obj_sp);
345 }
Sean Callananfc732752012-05-21 18:25:19 +0000346
347 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
348 if (cmd_obj_sp)
349 {
350 alias_arguments_vector_sp.reset (new OptionArgVector);
351 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
Jim Ingham06d282d2012-10-18 23:24:12 +0000352 AddAlias ("rbreak", cmd_obj_sp);
353 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
Sean Callananfc732752012-05-21 18:25:19 +0000354 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000355}
356
Greg Clayton0c4129f2014-04-25 00:35:14 +0000357void
358CommandInterpreter::Clear()
359{
360 m_command_io_handler_sp.reset();
Greg Claytoned6499f2014-04-25 23:55:12 +0000361
362 if (m_script_interpreter_ap)
363 m_script_interpreter_ap->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000364}
365
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000366const char *
367CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
368{
369 // This function has not yet been implemented.
370
371 // Look for any embedded script command
372 // If found,
373 // get interpreter object from the command dictionary,
374 // call execute_one_command on it,
375 // get the results as a string,
376 // substitute that string for current stuff.
377
378 return arg;
379}
380
381
382void
383CommandInterpreter::LoadCommandDictionary ()
384{
385 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
386
Caroline Ticedaccaa92010-09-20 20:44:43 +0000387 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000388
Greg Claytona7015092010-09-18 01:14:36 +0000389 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000390 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Johnny Chenb89982d2011-04-21 00:39:18 +0000391 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000392 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
393 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000394 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton44d93782014-01-27 23:43:24 +0000395 m_command_dict["gui"] = CommandObjectSP (new CommandObjectGUI (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000396 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000397 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
398 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonded470d2011-03-19 01:12:21 +0000399 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata21dfcd92012-09-28 23:57:51 +0000400 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000401 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000402 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000403 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000404 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000405 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Inghamebc09c32010-07-07 03:36:20 +0000406 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000407 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
408 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata223383e2011-08-16 23:24:13 +0000409 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen31c39da2010-12-23 20:21:44 +0000410 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chenf04ee932011-09-22 18:04:58 +0000411 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000412
Jim Inghamca36cd12012-10-05 19:16:31 +0000413 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
414 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
Greg Clayton722e8852013-02-08 02:54:24 +0000415 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
Greg Clayton1b3815c2013-01-30 00:18:29 +0000416 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000417 {"^(-.*)$", "breakpoint set %1"},
418 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
Greg Clayton722e8852013-02-08 02:54:24 +0000419 {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000420 {"^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"}};
421
Saleem Abdulrasool28606952014-06-27 05:17:41 +0000422 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000423
Greg Clayton7b0992d2013-04-18 22:45:39 +0000424 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytona7015092010-09-18 01:14:36 +0000425 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000426 "_regexp-break",
Johnny Chenb417dcd2012-08-23 00:32:22 +0000427 "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 +0000428 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
429 2,
430 CommandCompletions::eSymbolCompletion |
431 CommandCompletions::eSourceFileCompletion));
Jim Inghamca36cd12012-10-05 19:16:31 +0000432
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000433 if (break_regex_cmd_ap.get())
434 {
Jim Inghamca36cd12012-10-05 19:16:31 +0000435 bool success = true;
436 for (size_t i = 0; i < num_regexes; i++)
437 {
438 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
439 if (!success)
440 break;
441 }
442 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
443
444 if (success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000445 {
446 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
447 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
448 }
449 }
Jim Inghamffba2292011-03-22 02:29:32 +0000450
Greg Clayton7b0992d2013-04-18 22:45:39 +0000451 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamca36cd12012-10-05 19:16:31 +0000452 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
453 "_regexp-tbreak",
454 "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 +0000455 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
456 2,
457 CommandCompletions::eSymbolCompletion |
458 CommandCompletions::eSourceFileCompletion));
Jim Inghamca36cd12012-10-05 19:16:31 +0000459
460 if (tbreak_regex_cmd_ap.get())
461 {
462 bool success = true;
463 for (size_t i = 0; i < num_regexes; i++)
464 {
465 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
466 char buffer[1024];
467 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
468 assert (num_printed < 1024);
469 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
470 if (!success)
471 break;
472 }
473 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
474
475 if (success)
476 {
477 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
478 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
479 }
480 }
481
Greg Clayton7b0992d2013-04-18 22:45:39 +0000482 std::unique_ptr<CommandObjectRegexCommand>
Johnny Chen6d675242012-08-24 18:15:45 +0000483 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
484 "_regexp-attach",
485 "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 +0000486 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]",
487 2));
Johnny Chen6d675242012-08-24 18:15:45 +0000488 if (attach_regex_cmd_ap.get())
489 {
Greg Clayton3cb4c7d2012-12-15 01:19:07 +0000490 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
491 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
492 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
493 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
Johnny Chen6d675242012-08-24 18:15:45 +0000494 {
495 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
496 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
497 }
498 }
499
Greg Clayton7b0992d2013-04-18 22:45:39 +0000500 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000501 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000502 "_regexp-down",
503 "Go down \"n\" frames in the stack (1 frame by default).",
504 "_regexp-down [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000505 if (down_regex_cmd_ap.get())
506 {
507 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
508 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
509 {
510 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
511 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
512 }
513 }
514
Greg Clayton7b0992d2013-04-18 22:45:39 +0000515 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000516 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000517 "_regexp-up",
518 "Go up \"n\" frames in the stack (1 frame by default).",
519 "_regexp-up [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000520 if (up_regex_cmd_ap.get())
521 {
522 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
523 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
524 {
525 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
526 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
527 }
528 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000529
Greg Clayton7b0992d2013-04-18 22:45:39 +0000530 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000531 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000532 "_regexp-display",
533 "Add an expression evaluation stop-hook.",
534 "_regexp-display expression", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000535 if (display_regex_cmd_ap.get())
536 {
537 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
538 {
539 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
540 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
541 }
542 }
543
Greg Clayton7b0992d2013-04-18 22:45:39 +0000544 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000545 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000546 "_regexp-undisplay",
547 "Remove an expression evaluation stop-hook.",
548 "_regexp-undisplay stop-hook-number", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000549 if (undisplay_regex_cmd_ap.get())
550 {
551 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
552 {
553 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
554 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
555 }
556 }
557
Greg Clayton7b0992d2013-04-18 22:45:39 +0000558 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000559 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000560 "gdb-remote",
561 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
562 "gdb-remote [<hostname>:]<portnum>", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000563 if (connect_gdb_remote_cmd_ap.get())
564 {
565 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
566 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
567 {
568 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
569 m_command_dict[command_sp->GetCommandName ()] = command_sp;
570 }
571 }
572
Greg Clayton7b0992d2013-04-18 22:45:39 +0000573 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000574 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
575 "kdp-remote",
Jason Molendaa7dcb332012-10-23 03:05:16 +0000576 "Connect to a remote KDP server. udp port 41139 is the default port number.",
577 "kdp-remote <hostname>[:<portnum>]", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000578 if (connect_kdp_remote_cmd_ap.get())
579 {
580 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molendac36b1842012-09-27 02:47:55 +0000581 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000582 {
583 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
584 m_command_dict[command_sp->GetCommandName ()] = command_sp;
585 }
586 }
587
Greg Clayton7b0992d2013-04-18 22:45:39 +0000588 std::unique_ptr<CommandObjectRegexCommand>
Jason Molenda4cddfed2012-10-05 05:29:32 +0000589 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jim Ingham71bf2992012-10-10 16:51:31 +0000590 "_regexp-bt",
Jason Molenda4cddfed2012-10-05 05:29:32 +0000591 "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.",
592 "bt [<digit>|all]", 2));
593 if (bt_regex_cmd_ap.get())
594 {
595 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
596 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
597 // so now "bt 3" is the preferred form, in line with gdb.
598 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
599 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
600 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
601 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
602 {
603 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
604 m_command_dict[command_sp->GetCommandName ()] = command_sp;
605 }
606 }
607
Greg Clayton7b0992d2013-04-18 22:45:39 +0000608 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton6bade322013-02-01 23:33:03 +0000609 list_regex_cmd_ap(new CommandObjectRegexCommand (*this,
610 "_regexp-list",
611 "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 +0000612 "_regexp-list [<line>]\n_regexp-list [<file>:<line>]\n_regexp-list [<file>:<line>]",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000613 2,
614 CommandCompletions::eSourceFileCompletion));
Greg Clayton6bade322013-02-01 23:33:03 +0000615 if (list_regex_cmd_ap.get())
616 {
617 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") &&
618 list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") &&
619 list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") &&
Greg Claytond9010962013-02-12 18:42:05 +0000620 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") &&
Greg Claytone4ca5152013-03-13 18:25:49 +0000621 list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") &&
Greg Clayton6bade322013-02-01 23:33:03 +0000622 list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") &&
623 list_regex_cmd_ap->AddRegexCommand("^$", "source list"))
624 {
625 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
626 m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp;
627 }
628 }
629
Greg Clayton7b0992d2013-04-18 22:45:39 +0000630 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytonef5651d2013-02-12 18:52:24 +0000631 env_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000632 "_regexp-env",
633 "Implements a shortcut to viewing and setting environment variables.",
634 "_regexp-env\n_regexp-env FOO=BAR", 2));
Greg Claytonef5651d2013-02-12 18:52:24 +0000635 if (env_regex_cmd_ap.get())
636 {
637 if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") &&
638 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1"))
639 {
640 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
641 m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp;
642 }
643 }
644
Richard Mittonf86248d2013-09-12 02:20:34 +0000645 std::unique_ptr<CommandObjectRegexCommand>
646 jump_regex_cmd_ap(new CommandObjectRegexCommand (*this,
647 "_regexp-jump",
648 "Sets the program counter to a new address.",
649 "_regexp-jump [<line>]\n"
650 "_regexp-jump [<+-lineoffset>]\n"
651 "_regexp-jump [<file>:<line>]\n"
652 "_regexp-jump [*<addr>]\n", 2));
653 if (jump_regex_cmd_ap.get())
654 {
655 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") &&
656 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") &&
657 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") &&
658 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1"))
659 {
660 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
661 m_command_dict[jump_regex_cmd_sp->GetCommandName ()] = jump_regex_cmd_sp;
662 }
663 }
664
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000665}
666
667int
668CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
669 StringList &matches)
670{
671 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
672
673 if (include_aliases)
674 {
675 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
676 }
677
678 return matches.GetSize();
679}
680
681CommandObjectSP
682CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
683{
684 CommandObject::CommandMap::iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +0000685 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000686
687 std::string cmd(cmd_cstr);
688
689 if (HasCommands())
690 {
691 pos = m_command_dict.find(cmd);
692 if (pos != m_command_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000693 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000694 }
695
696 if (include_aliases && HasAliases())
697 {
698 pos = m_alias_dict.find(cmd);
699 if (pos != m_alias_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000700 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000701 }
702
703 if (HasUserCommands())
704 {
705 pos = m_user_dict.find(cmd);
706 if (pos != m_user_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000707 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000708 }
709
Greg Claytonc7bece562013-01-25 18:06:21 +0000710 if (!exact && !command_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000711 {
Jim Ingham279a6c22010-07-06 22:46:59 +0000712 // We will only get into here if we didn't find any exact matches.
713
714 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
715
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000716 StringList local_matches;
Ed Masted78c9572014-04-20 00:31:37 +0000717 if (matches == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000718 matches = &local_matches;
719
Jim Ingham279a6c22010-07-06 22:46:59 +0000720 unsigned int num_cmd_matches = 0;
721 unsigned int num_alias_matches = 0;
722 unsigned int num_user_matches = 0;
723
724 // Look through the command dictionaries one by one, and if we get only one match from any of
725 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
726
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000727 if (HasCommands())
728 {
729 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
730 }
731
732 if (num_cmd_matches == 1)
733 {
734 cmd.assign(matches->GetStringAtIndex(0));
735 pos = m_command_dict.find(cmd);
736 if (pos != m_command_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000737 real_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000738 }
739
Jim Ingham490ac552010-06-24 20:28:42 +0000740 if (include_aliases && HasAliases())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000741 {
742 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
743
744 }
745
Jim Ingham279a6c22010-07-06 22:46:59 +0000746 if (num_alias_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000747 {
748 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
749 pos = m_alias_dict.find(cmd);
750 if (pos != m_alias_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000751 alias_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000752 }
753
Jim Ingham490ac552010-06-24 20:28:42 +0000754 if (HasUserCommands())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000755 {
756 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
757 }
758
Jim Ingham279a6c22010-07-06 22:46:59 +0000759 if (num_user_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000760 {
761 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
762
763 pos = m_user_dict.find (cmd);
764 if (pos != m_user_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000765 user_match_sp = pos->second;
766 }
767
768 // If we got exactly one match, return that, otherwise return the match list.
769
770 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
771 {
772 if (num_cmd_matches)
773 return real_match_sp;
774 else if (num_alias_matches)
775 return alias_match_sp;
776 else
777 return user_match_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000778 }
779 }
Greg Claytonc7bece562013-01-25 18:06:21 +0000780 else if (matches && command_sp)
Jim Ingham279a6c22010-07-06 22:46:59 +0000781 {
782 matches->AppendString (cmd_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000783 }
784
785
Greg Claytonc7bece562013-01-25 18:06:21 +0000786 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000787}
788
Greg Claytonde164aa2011-04-20 16:37:46 +0000789bool
790CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
791{
792 if (name && name[0])
793 {
794 std::string name_sstr(name);
Enrico Granatae00af802012-10-01 17:19:37 +0000795 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
796 if (found && !can_replace)
797 return false;
798 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata21dfcd92012-09-28 23:57:51 +0000799 return false;
Greg Claytonde164aa2011-04-20 16:37:46 +0000800 m_command_dict[name_sstr] = cmd_sp;
801 return true;
802 }
803 return false;
804}
805
Enrico Granata223383e2011-08-16 23:24:13 +0000806bool
Enrico Granata0a305db2011-11-07 22:57:04 +0000807CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata223383e2011-08-16 23:24:13 +0000808 const lldb::CommandObjectSP &cmd_sp,
809 bool can_replace)
810{
Enrico Granata0a305db2011-11-07 22:57:04 +0000811 if (!name.empty())
Enrico Granata223383e2011-08-16 23:24:13 +0000812 {
Enrico Granata0a305db2011-11-07 22:57:04 +0000813
814 const char* name_cstr = name.c_str();
815
816 // do not allow replacement of internal commands
817 if (CommandExists(name_cstr))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000818 {
819 if (can_replace == false)
820 return false;
821 if (m_command_dict[name]->IsRemovable() == false)
822 return false;
823 }
Enrico Granata0a305db2011-11-07 22:57:04 +0000824
Enrico Granata21dfcd92012-09-28 23:57:51 +0000825 if (UserCommandExists(name_cstr))
826 {
827 if (can_replace == false)
828 return false;
829 if (m_user_dict[name]->IsRemovable() == false)
830 return false;
831 }
832
Enrico Granata0a305db2011-11-07 22:57:04 +0000833 m_user_dict[name] = cmd_sp;
Enrico Granata223383e2011-08-16 23:24:13 +0000834 return true;
835 }
836 return false;
837}
Greg Claytonde164aa2011-04-20 16:37:46 +0000838
Jim Ingham279a6c22010-07-06 22:46:59 +0000839CommandObjectSP
840CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000841{
Caroline Tice472362e2010-12-14 18:51:39 +0000842 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
843 CommandObjectSP ret_val; // Possibly empty return value.
844
Ed Masted78c9572014-04-20 00:31:37 +0000845 if (cmd_cstr == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000846 return ret_val;
847
848 if (cmd_words.GetArgumentCount() == 1)
Ed Masted78c9572014-04-20 00:31:37 +0000849 return GetCommandSP(cmd_cstr, include_aliases, true, nullptr);
Caroline Tice472362e2010-12-14 18:51:39 +0000850 else
851 {
852 // We have a multi-word command (seemingly), so we need to do more work.
853 // First, get the cmd_obj_sp for the first word in the command.
Ed Masted78c9572014-04-20 00:31:37 +0000854 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, nullptr);
855 if (cmd_obj_sp.get() != nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000856 {
857 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
858 // command name), and find the appropriate sub-command SP for each command word....
859 size_t end = cmd_words.GetArgumentCount();
860 for (size_t j= 1; j < end; ++j)
861 {
862 if (cmd_obj_sp->IsMultiwordObject())
863 {
Greg Clayton998255b2012-10-13 02:07:45 +0000864 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Ed Masted78c9572014-04-20 00:31:37 +0000865 if (cmd_obj_sp.get() == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000866 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
867 return ret_val;
868 }
869 else
870 // We have more words in the command name, but we don't have a multiword object. Fail and return
871 // empty 'ret_val'.
872 return ret_val;
873 }
874 // We successfully looped through all the command words and got valid command objects for them. Assign the
875 // last object retrieved to 'ret_val'.
876 ret_val = cmd_obj_sp;
877 }
878 }
879 return ret_val;
Jim Ingham279a6c22010-07-06 22:46:59 +0000880}
881
882CommandObject *
883CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
884{
885 return GetCommandSPExact (cmd_cstr, include_aliases).get();
886}
887
888CommandObject *
889CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
890{
891 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
892
893 // If we didn't find an exact match to the command string in the commands, look in
894 // the aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000895
896 if (command_obj)
897 return command_obj;
Jim Ingham279a6c22010-07-06 22:46:59 +0000898
Enrico Granata5342c442013-06-18 18:01:08 +0000899 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
Jim Ingham279a6c22010-07-06 22:46:59 +0000900
Enrico Granata5342c442013-06-18 18:01:08 +0000901 if (command_obj)
902 return command_obj;
903
904 // If there wasn't an exact match then look for an inexact one in just the commands
Ed Masted78c9572014-04-20 00:31:37 +0000905 command_obj = GetCommandSP(cmd_cstr, false, false, nullptr).get();
Matt Kopec038ff812013-04-23 16:17:32 +0000906
907 // Finally, if there wasn't an inexact match among the commands, look for an inexact
908 // match in both the commands and aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000909
910 if (command_obj)
911 {
912 if (matches)
913 matches->AppendString(command_obj->GetCommandName());
914 return command_obj;
915 }
916
917 return GetCommandSP(cmd_cstr, true, false, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000918}
919
920bool
921CommandInterpreter::CommandExists (const char *cmd)
922{
923 return m_command_dict.find(cmd) != m_command_dict.end();
924}
925
926bool
Caroline Ticeca90c472011-05-06 21:37:15 +0000927CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
928 const char *options_args,
929 OptionArgVectorSP &option_arg_vector_sp)
930{
931 bool success = true;
932 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
933
934 if (!options_args || (strlen (options_args) < 1))
935 return true;
936
937 std::string options_string (options_args);
938 Args args (options_args);
939 CommandReturnObject result;
940 // Check to see if the command being aliased can take any command options.
941 Options *options = cmd_obj_sp->GetOptions ();
942 if (options)
943 {
944 // See if any options were specified as part of the alias; if so, handle them appropriately.
945 options->NotifyOptionParsingStarting ();
946 args.Unshift ("dummy_arg");
947 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
948 args.Shift ();
949 if (result.Succeeded())
950 options->VerifyPartialOptions (result);
951 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
952 {
953 result.AppendError ("Unable to create requested alias.\n");
954 return false;
955 }
956 }
957
Greg Clayton5521f992011-10-28 21:38:01 +0000958 if (!options_string.empty())
Caroline Ticeca90c472011-05-06 21:37:15 +0000959 {
960 if (cmd_obj_sp->WantsRawCommandString ())
961 option_arg_vector->push_back (OptionArgPair ("<argument>",
962 OptionArgValue (-1,
963 options_string)));
964 else
965 {
Greg Claytonc7bece562013-01-25 18:06:21 +0000966 const size_t argc = args.GetArgumentCount();
Caroline Ticeca90c472011-05-06 21:37:15 +0000967 for (size_t i = 0; i < argc; ++i)
968 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
969 option_arg_vector->push_back
970 (OptionArgPair ("<argument>",
971 OptionArgValue (-1,
972 std::string (args.GetArgumentAtIndex (i)))));
973 }
974 }
975
976 return success;
977}
978
979bool
Jim Ingham298f3782013-04-03 00:25:49 +0000980CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name)
981{
982 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
983 if (exact_match)
984 {
985 full_name.assign(cmd);
986 return exact_match;
987 }
988 else
989 {
990 StringList matches;
991 size_t num_alias_matches;
992 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches);
993 if (num_alias_matches == 1)
994 {
995 // Make sure this isn't shadowing a command in the regular command space:
996 StringList regular_matches;
997 const bool include_aliases = false;
998 const bool exact = false;
999 CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, &regular_matches));
1000 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1001 return false;
1002 else
1003 {
1004 full_name.assign (matches.GetStringAtIndex(0));
1005 return true;
1006 }
1007 }
1008 else
1009 return false;
1010 }
1011}
1012
1013bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001014CommandInterpreter::AliasExists (const char *cmd)
1015{
1016 return m_alias_dict.find(cmd) != m_alias_dict.end();
1017}
1018
1019bool
1020CommandInterpreter::UserCommandExists (const char *cmd)
1021{
1022 return m_user_dict.find(cmd) != m_user_dict.end();
1023}
1024
1025void
1026CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
1027{
Jim Ingham279a6c22010-07-06 22:46:59 +00001028 command_obj_sp->SetIsAlias (true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001029 m_alias_dict[alias_name] = command_obj_sp;
1030}
1031
1032bool
1033CommandInterpreter::RemoveAlias (const char *alias_name)
1034{
1035 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
1036 if (pos != m_alias_dict.end())
1037 {
1038 m_alias_dict.erase(pos);
1039 return true;
1040 }
1041 return false;
1042}
1043bool
1044CommandInterpreter::RemoveUser (const char *alias_name)
1045{
1046 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1047 if (pos != m_user_dict.end())
1048 {
1049 m_user_dict.erase(pos);
1050 return true;
1051 }
1052 return false;
1053}
1054
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001055void
1056CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
1057{
1058 help_string.Printf ("'%s", command_name);
1059 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1060
Sean Callanan9a028512012-08-09 00:50:26 +00001061 if (option_arg_vector_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001062 {
1063 OptionArgVector *options = option_arg_vector_sp.get();
Andy Gibbsa297a972013-06-19 19:04:53 +00001064 for (size_t i = 0; i < options->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001065 {
1066 OptionArgPair cur_option = (*options)[i];
1067 std::string opt = cur_option.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00001068 OptionArgValue value_pair = cur_option.second;
1069 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070 if (opt.compare("<argument>") == 0)
1071 {
1072 help_string.Printf (" %s", value.c_str());
1073 }
1074 else
1075 {
1076 help_string.Printf (" %s", opt.c_str());
1077 if ((value.compare ("<no-argument>") != 0)
1078 && (value.compare ("<need-argument") != 0))
1079 {
1080 help_string.Printf (" %s", value.c_str());
1081 }
1082 }
1083 }
1084 }
1085
1086 help_string.Printf ("'");
1087}
1088
Greg Clayton12fc3e02010-08-26 22:05:43 +00001089size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001090CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
1091{
1092 CommandObject::CommandMap::const_iterator pos;
Greg Clayton12fc3e02010-08-26 22:05:43 +00001093 CommandObject::CommandMap::const_iterator end = dict.end();
1094 size_t max_len = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001095
Greg Clayton12fc3e02010-08-26 22:05:43 +00001096 for (pos = dict.begin(); pos != end; ++pos)
1097 {
1098 size_t len = pos->first.size();
1099 if (max_len < len)
1100 max_len = len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001101 }
Greg Clayton12fc3e02010-08-26 22:05:43 +00001102 return max_len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001103}
1104
1105void
Enrico Granata223383e2011-08-16 23:24:13 +00001106CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata08633ee2011-09-09 17:49:36 +00001107 uint32_t cmd_types)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001108{
1109 CommandObject::CommandMap::const_iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +00001110 size_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata223383e2011-08-16 23:24:13 +00001111
1112 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001113 {
Enrico Granata223383e2011-08-16 23:24:13 +00001114
1115 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
1116 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001117
Enrico Granata223383e2011-08-16 23:24:13 +00001118 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1119 {
1120 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1121 max_len);
1122 }
1123 result.AppendMessage("");
1124
1125 }
1126
Greg Clayton5521f992011-10-28 21:38:01 +00001127 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001128 {
Jim Ingham49e80a12010-10-22 18:47:16 +00001129 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chenb89982d2011-04-21 00:39:18 +00001130 "(see 'help command alias' for more info):");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001131 result.AppendMessage("");
Greg Clayton12fc3e02010-08-26 22:05:43 +00001132 max_len = FindLongestCommandWord (m_alias_dict);
1133
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1135 {
1136 StreamString sstr;
1137 StreamString translation_and_help;
1138 std::string entry_name = pos->first;
1139 std::string second_entry = pos->second.get()->GetCommandName();
1140 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1141
1142 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1143 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1144 translation_and_help.GetData(), max_len);
1145 }
1146 result.AppendMessage("");
1147 }
1148
Greg Clayton5521f992011-10-28 21:38:01 +00001149 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001150 {
1151 result.AppendMessage ("The following is a list of your current user-defined commands:");
1152 result.AppendMessage("");
Enrico Granata223383e2011-08-16 23:24:13 +00001153 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001154 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1155 {
Enrico Granata223383e2011-08-16 23:24:13 +00001156 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1157 max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001158 }
1159 result.AppendMessage("");
1160 }
1161
1162 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1163}
1164
Caroline Tice844d2302010-12-09 22:52:49 +00001165CommandObject *
1166CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001167{
Caroline Tice844d2302010-12-09 22:52:49 +00001168 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1169 // eventually be invoked by the given command line.
1170
Ed Masted78c9572014-04-20 00:31:37 +00001171 CommandObject *cmd_obj = nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001172 std::string white_space (" \t\v");
1173 size_t start = command_string.find_first_not_of (white_space);
1174 size_t end = 0;
1175 bool done = false;
1176 while (!done)
1177 {
1178 if (start != std::string::npos)
1179 {
1180 // Get the next word from command_string.
1181 end = command_string.find_first_of (white_space, start);
1182 if (end == std::string::npos)
1183 end = command_string.size();
1184 std::string cmd_word = command_string.substr (start, end - start);
1185
Ed Masted78c9572014-04-20 00:31:37 +00001186 if (cmd_obj == nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001187 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1188 // command or alias.
1189 cmd_obj = GetCommandObject (cmd_word.c_str());
1190 else if (cmd_obj->IsMultiwordObject ())
1191 {
1192 // 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 +00001193 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001194 if (sub_cmd_obj)
1195 cmd_obj = sub_cmd_obj;
1196 else // cmd_word was not a valid sub-command word, so we are donee
1197 done = true;
1198 }
1199 else
1200 // We have a cmd_obj and it is not a multi-word object, so we are done.
1201 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001202
Caroline Tice844d2302010-12-09 22:52:49 +00001203 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1204 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1205 // next word.
1206
1207 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1208 done = true;
1209 else
1210 start = command_string.find_first_not_of (white_space, end);
1211 }
1212 else
1213 // Unable to find any more words.
1214 done = true;
1215 }
1216
1217 if (end == command_string.size())
1218 command_string.clear();
1219 else
1220 command_string = command_string.substr(end);
1221
1222 return cmd_obj;
1223}
1224
Greg Clayton51964162011-10-25 00:36:27 +00001225static const char *k_white_space = " \t\v";
Greg Clayton5521f992011-10-28 21:38:01 +00001226static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton51964162011-10-25 00:36:27 +00001227static void
1228StripLeadingSpaces (std::string &s)
Caroline Tice844d2302010-12-09 22:52:49 +00001229{
Greg Clayton51964162011-10-25 00:36:27 +00001230 if (!s.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001231 {
Greg Clayton51964162011-10-25 00:36:27 +00001232 size_t pos = s.find_first_not_of (k_white_space);
1233 if (pos == std::string::npos)
1234 s.clear();
1235 else if (pos == 0)
1236 return;
1237 s.erase (0, pos);
1238 }
1239}
1240
Greg Clayton93c62e62011-11-09 23:25:03 +00001241static size_t
1242FindArgumentTerminator (const std::string &s)
1243{
Greg Clayton93c62e62011-11-09 23:25:03 +00001244 const size_t s_len = s.size();
1245 size_t offset = 0;
1246 while (offset < s_len)
1247 {
1248 size_t pos = s.find ("--", offset);
1249 if (pos == std::string::npos)
1250 break;
1251 if (pos > 0)
1252 {
1253 if (isspace(s[pos-1]))
1254 {
1255 // Check if the string ends "\s--" (where \s is a space character)
1256 // or if we have "\s--\s".
1257 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1258 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001259 return pos;
1260 }
1261 }
1262 }
1263 offset = pos + 2;
1264 }
Greg Clayton93c62e62011-11-09 23:25:03 +00001265 return std::string::npos;
1266}
1267
Greg Clayton51964162011-10-25 00:36:27 +00001268static bool
Greg Clayton5521f992011-10-28 21:38:01 +00001269ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton51964162011-10-25 00:36:27 +00001270{
Greg Clayton5521f992011-10-28 21:38:01 +00001271 command.clear();
1272 suffix.clear();
Greg Clayton51964162011-10-25 00:36:27 +00001273 StripLeadingSpaces (command_string);
1274
1275 bool result = false;
1276 quote_char = '\0';
1277
1278 if (!command_string.empty())
1279 {
1280 const char first_char = command_string[0];
1281 if (first_char == '\'' || first_char == '"')
Caroline Tice844d2302010-12-09 22:52:49 +00001282 {
Greg Clayton51964162011-10-25 00:36:27 +00001283 quote_char = first_char;
1284 const size_t end_quote_pos = command_string.find (quote_char, 1);
1285 if (end_quote_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001286 {
Greg Clayton5521f992011-10-28 21:38:01 +00001287 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001288 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001289 }
1290 else
1291 {
Greg Clayton5521f992011-10-28 21:38:01 +00001292 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton51964162011-10-25 00:36:27 +00001293 if (end_quote_pos + 1 < command_string.size())
1294 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1295 else
1296 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001297 }
Caroline Tice844d2302010-12-09 22:52:49 +00001298 }
1299 else
1300 {
Greg Clayton51964162011-10-25 00:36:27 +00001301 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1302 if (first_space_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001303 {
Greg Clayton5521f992011-10-28 21:38:01 +00001304 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001305 command_string.erase();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001306 }
1307 else
1308 {
Greg Clayton5521f992011-10-28 21:38:01 +00001309 command.assign (command_string, 0, first_space_pos);
1310 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice2b5e8502011-05-11 16:07:06 +00001311 }
Caroline Tice844d2302010-12-09 22:52:49 +00001312 }
Greg Clayton51964162011-10-25 00:36:27 +00001313 result = true;
Caroline Tice844d2302010-12-09 22:52:49 +00001314 }
Greg Clayton5521f992011-10-28 21:38:01 +00001315
1316
1317 if (!command.empty())
1318 {
1319 // actual commands can't start with '-' or '_'
1320 if (command[0] != '-' && command[0] != '_')
1321 {
1322 size_t pos = command.find_first_not_of(k_valid_command_chars);
1323 if (pos > 0 && pos != std::string::npos)
1324 {
1325 suffix.assign (command.begin() + pos, command.end());
1326 command.erase (pos);
1327 }
1328 }
1329 }
Greg Clayton51964162011-10-25 00:36:27 +00001330
1331 return result;
Caroline Tice844d2302010-12-09 22:52:49 +00001332}
1333
Greg Clayton5521f992011-10-28 21:38:01 +00001334CommandObject *
1335CommandInterpreter::BuildAliasResult (const char *alias_name,
1336 std::string &raw_input_string,
1337 std::string &alias_result,
1338 CommandReturnObject &result)
Caroline Tice844d2302010-12-09 22:52:49 +00001339{
Ed Masted78c9572014-04-20 00:31:37 +00001340 CommandObject *alias_cmd_obj = nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001341 Args cmd_args (raw_input_string.c_str());
1342 alias_cmd_obj = GetCommandObject (alias_name);
1343 StreamString result_str;
1344
1345 if (alias_cmd_obj)
1346 {
1347 std::string alias_name_str = alias_name;
1348 if ((cmd_args.GetArgumentCount() == 0)
1349 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1350 cmd_args.Unshift (alias_name);
1351
1352 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1353 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1354
1355 if (option_arg_vector_sp.get())
1356 {
1357 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1358
Andy Gibbsa297a972013-06-19 19:04:53 +00001359 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Caroline Tice844d2302010-12-09 22:52:49 +00001360 {
1361 OptionArgPair option_pair = (*option_arg_vector)[i];
1362 OptionArgValue value_pair = option_pair.second;
1363 int value_type = value_pair.first;
1364 std::string option = option_pair.first;
1365 std::string value = value_pair.second;
1366 if (option.compare ("<argument>") == 0)
1367 result_str.Printf (" %s", value.c_str());
1368 else
1369 {
1370 result_str.Printf (" %s", option.c_str());
Virgile Belloe2607b52013-09-05 16:42:23 +00001371 if (value_type != OptionParser::eOptionalArgument)
Caroline Tice844d2302010-12-09 22:52:49 +00001372 result_str.Printf (" ");
Virgile Belloe2607b52013-09-05 16:42:23 +00001373 if (value.compare ("<OptionParser::eNoArgument>") != 0)
Caroline Tice844d2302010-12-09 22:52:49 +00001374 {
1375 int index = GetOptionArgumentPosition (value.c_str());
1376 if (index == 0)
1377 result_str.Printf ("%s", value.c_str());
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001378 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Caroline Tice844d2302010-12-09 22:52:49 +00001379 {
1380
1381 result.AppendErrorWithFormat
1382 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1383 index);
1384 result.SetStatus (eReturnStatusFailed);
Greg Clayton5521f992011-10-28 21:38:01 +00001385 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001386 }
1387 else
1388 {
1389 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1390 if (strpos != std::string::npos)
1391 raw_input_string = raw_input_string.erase (strpos,
1392 strlen (cmd_args.GetArgumentAtIndex (index)));
1393 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1394 }
1395 }
1396 }
1397 }
1398 }
1399
1400 alias_result = result_str.GetData();
1401 }
Greg Clayton5521f992011-10-28 21:38:01 +00001402 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001403}
1404
Greg Clayton5a314712011-10-14 07:41:33 +00001405Error
1406CommandInterpreter::PreprocessCommand (std::string &command)
1407{
1408 // The command preprocessor needs to do things to the command
1409 // line before any parsing of arguments or anything else is done.
1410 // The only current stuff that gets proprocessed is anyting enclosed
1411 // in backtick ('`') characters is evaluated as an expression and
1412 // the result of the expression must be a scalar that can be substituted
1413 // into the command. An example would be:
1414 // (lldb) memory read `$rsp + 20`
1415 Error error; // Error for any expressions that might not evaluate
1416 size_t start_backtick;
1417 size_t pos = 0;
1418 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1419 {
1420 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1421 {
1422 // The backtick was preceeded by a '\' character, remove the slash
1423 // and don't treat the backtick as the start of an expression
1424 command.erase(start_backtick-1, 1);
1425 // No need to add one to start_backtick since we just deleted a char
1426 pos = start_backtick;
1427 }
1428 else
1429 {
1430 const size_t expr_content_start = start_backtick + 1;
1431 const size_t end_backtick = command.find ('`', expr_content_start);
1432 if (end_backtick == std::string::npos)
1433 return error;
1434 else if (end_backtick == expr_content_start)
1435 {
1436 // Empty expression (two backticks in a row)
1437 command.erase (start_backtick, 2);
1438 }
1439 else
1440 {
1441 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1442
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00001443 ExecutionContext exe_ctx(GetExecutionContext());
1444 Target *target = exe_ctx.GetTargetPtr();
Johnny Chen51ea0ad2011-10-29 00:21:50 +00001445 // Get a dummy target to allow for calculator mode while processing backticks.
1446 // This also helps break the infinite loop caused when target is null.
1447 if (!target)
1448 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Clayton5a314712011-10-14 07:41:33 +00001449 if (target)
1450 {
Greg Clayton5a314712011-10-14 07:41:33 +00001451 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001452
Jim Ingham35e1bda2012-10-16 21:41:58 +00001453 EvaluateExpressionOptions options;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00001454 options.SetCoerceToId(false);
1455 options.SetUnwindOnError(true);
1456 options.SetIgnoreBreakpoints(true);
1457 options.SetKeepInMemory(false);
1458 options.SetTryAllThreads(true);
1459 options.SetTimeoutUsec(0);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001460
Jim Ingham1624a2d2014-05-05 02:26:40 +00001461 ExpressionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad4439aa2012-09-05 20:41:26 +00001462 exe_ctx.GetFramePtr(),
Enrico Granata3372f582012-07-16 23:10:35 +00001463 expr_result_valobj_sp,
Enrico Granatad4439aa2012-09-05 20:41:26 +00001464 options);
1465
Jim Ingham8646d3c2014-05-05 02:47:44 +00001466 if (expr_result == eExpressionCompleted)
Greg Clayton5a314712011-10-14 07:41:33 +00001467 {
1468 Scalar scalar;
1469 if (expr_result_valobj_sp->ResolveValue (scalar))
1470 {
1471 command.erase (start_backtick, end_backtick - start_backtick + 1);
1472 StreamString value_strm;
1473 const bool show_type = false;
1474 scalar.GetValue (&value_strm, show_type);
1475 size_t value_string_size = value_strm.GetSize();
1476 if (value_string_size)
1477 {
1478 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1479 pos = start_backtick + value_string_size;
1480 continue;
1481 }
1482 else
1483 {
1484 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1485 }
1486 }
1487 else
1488 {
1489 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1490 }
1491 }
1492 else
1493 {
1494 if (expr_result_valobj_sp)
1495 error = expr_result_valobj_sp->GetError();
1496 if (error.Success())
1497 {
1498
1499 switch (expr_result)
1500 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00001501 case eExpressionSetupError:
Greg Clayton5a314712011-10-14 07:41:33 +00001502 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1503 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001504 case eExpressionParseError:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001505 error.SetErrorStringWithFormat ("expression parse error for the expression '%s'", expr_str.c_str());
1506 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001507 case eExpressionResultUnavailable:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001508 error.SetErrorStringWithFormat ("expression error fetching result for the expression '%s'", expr_str.c_str());
Jim Ingham8646d3c2014-05-05 02:47:44 +00001509 case eExpressionCompleted:
Greg Clayton5a314712011-10-14 07:41:33 +00001510 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001511 case eExpressionDiscarded:
Greg Clayton5a314712011-10-14 07:41:33 +00001512 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1513 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001514 case eExpressionInterrupted:
Greg Clayton5a314712011-10-14 07:41:33 +00001515 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1516 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001517 case eExpressionHitBreakpoint:
Jim Ingham184e9812013-01-15 02:47:48 +00001518 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1519 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001520 case eExpressionTimedOut:
Greg Clayton5a314712011-10-14 07:41:33 +00001521 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1522 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001523 case eExpressionStoppedForDebug:
Greg Claytonc28ce782013-11-08 23:38:26 +00001524 error.SetErrorStringWithFormat("expression stop at entry point for debugging for the expression '%s'", expr_str.c_str());
1525 break;
Greg Clayton5a314712011-10-14 07:41:33 +00001526 }
1527 }
1528 }
1529 }
1530 }
1531 if (error.Fail())
1532 break;
1533 }
1534 }
1535 return error;
1536}
1537
1538
Caroline Tice844d2302010-12-09 22:52:49 +00001539bool
1540CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata5f5ab602012-05-31 01:09:06 +00001541 LazyBool lazy_add_to_history,
Caroline Tice844d2302010-12-09 22:52:49 +00001542 CommandReturnObject &result,
Jim Inghame16c50a2011-02-18 00:54:25 +00001543 ExecutionContext *override_context,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001544 bool repeat_on_empty_command,
1545 bool no_context_switching)
Jim Inghame16c50a2011-02-18 00:54:25 +00001546
Caroline Tice844d2302010-12-09 22:52:49 +00001547{
Jim Inghame16c50a2011-02-18 00:54:25 +00001548
Caroline Tice844d2302010-12-09 22:52:49 +00001549 bool done = false;
Ed Masted78c9572014-04-20 00:31:37 +00001550 CommandObject *cmd_obj = nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001551 bool wants_raw_input = false;
1552 std::string command_string (command_line);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001553 std::string original_command_string (command_line);
Caroline Tice844d2302010-12-09 22:52:49 +00001554
Greg Clayton5160ce52013-03-27 23:08:40 +00001555 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001556 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1557
1558 // Make a scoped cleanup object that will clear the crash description string
1559 // on exit of this function.
Ed Masted78c9572014-04-20 00:31:37 +00001560 lldb_utility::CleanUp <const char *> crash_description_cleanup(nullptr, Host::SetCrashDescription);
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001561
Caroline Tice844d2302010-12-09 22:52:49 +00001562 if (log)
1563 log->Printf ("Processing command: %s", command_line);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001564
Jim Ingham30244832010-11-04 23:08:45 +00001565 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1566
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001567 if (!no_context_switching)
1568 UpdateExecutionContext (override_context);
Enrico Granata5f5ab602012-05-31 01:09:06 +00001569
Enrico Granata5f5ab602012-05-31 01:09:06 +00001570 bool add_to_history;
1571 if (lazy_add_to_history == eLazyBoolCalculate)
1572 add_to_history = (m_command_source_depth == 0);
1573 else
1574 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1575
Jim Inghame16c50a2011-02-18 00:54:25 +00001576 bool empty_command = false;
1577 bool comment_command = false;
1578 if (command_string.empty())
1579 empty_command = true;
1580 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001581 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001582 const char *k_space_characters = "\t\n\v\f\r ";
1583
1584 size_t non_space = command_string.find_first_not_of (k_space_characters);
1585 // Check for empty line or comment line (lines whose first
1586 // non-space character is the comment character for this interpreter)
1587 if (non_space == std::string::npos)
1588 empty_command = true;
1589 else if (command_string[non_space] == m_comment_char)
1590 comment_command = true;
Enrico Granata7594f142013-06-17 22:51:50 +00001591 else if (command_string[non_space] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001592 {
Enrico Granata7594f142013-06-17 22:51:50 +00001593 const char *history_string = m_command_history.FindString(command_string.c_str() + non_space);
Ed Masted78c9572014-04-20 00:31:37 +00001594 if (history_string == nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001595 {
1596 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1597 result.SetStatus(eReturnStatusFailed);
1598 return false;
1599 }
1600 add_to_history = false;
1601 command_string = history_string;
1602 original_command_string = history_string;
1603 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001604 }
1605
1606 if (empty_command)
1607 {
1608 if (repeat_on_empty_command)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001609 {
Enrico Granata7594f142013-06-17 22:51:50 +00001610 if (m_command_history.IsEmpty())
Jim Inghame16c50a2011-02-18 00:54:25 +00001611 {
1612 result.AppendError ("empty command");
1613 result.SetStatus(eReturnStatusFailed);
1614 return false;
1615 }
1616 else
1617 {
1618 command_line = m_repeat_command.c_str();
1619 command_string = command_line;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001620 original_command_string = command_line;
Jim Inghame16c50a2011-02-18 00:54:25 +00001621 if (m_repeat_command.empty())
1622 {
1623 result.AppendErrorWithFormat("No auto repeat.\n");
1624 result.SetStatus (eReturnStatusFailed);
1625 return false;
1626 }
1627 }
1628 add_to_history = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001629 }
1630 else
1631 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001632 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1633 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001634 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001635 }
1636 else if (comment_command)
1637 {
1638 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1639 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001640 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001641
Greg Clayton5a314712011-10-14 07:41:33 +00001642
1643 Error error (PreprocessCommand (command_string));
1644
1645 if (error.Fail())
1646 {
1647 result.AppendError (error.AsCString());
1648 result.SetStatus(eReturnStatusFailed);
1649 return false;
1650 }
Caroline Tice844d2302010-12-09 22:52:49 +00001651 // Phase 1.
1652
1653 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1654 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1655 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1656 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1657 // 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 +00001658 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Tice844d2302010-12-09 22:52:49 +00001659 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Ticed9d63362010-12-07 19:58:26 +00001660
Caroline Tice844d2302010-12-09 22:52:49 +00001661 StreamString revised_command_line;
Caroline Tice01274c02010-12-11 08:16:56 +00001662 size_t actual_cmd_name_len = 0;
Greg Clayton5521f992011-10-28 21:38:01 +00001663 std::string next_word;
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001664 StringList matches;
Caroline Tice844d2302010-12-09 22:52:49 +00001665 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001666 {
Caroline Tice2b5e8502011-05-11 16:07:06 +00001667 char quote_char = '\0';
Greg Clayton5521f992011-10-28 21:38:01 +00001668 std::string suffix;
1669 ExtractCommand (command_string, next_word, suffix, quote_char);
Ed Masted78c9572014-04-20 00:31:37 +00001670 if (cmd_obj == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001671 {
Jim Ingham298f3782013-04-03 00:25:49 +00001672 std::string full_name;
1673 if (GetAliasFullName(next_word.c_str(), full_name))
Caroline Tice472362e2010-12-14 18:51:39 +00001674 {
Greg Clayton5521f992011-10-28 21:38:01 +00001675 std::string alias_result;
Jim Ingham298f3782013-04-03 00:25:49 +00001676 cmd_obj = BuildAliasResult (full_name.c_str(), command_string, alias_result, result);
Greg Clayton5521f992011-10-28 21:38:01 +00001677 revised_command_line.Printf ("%s", alias_result.c_str());
1678 if (cmd_obj)
1679 {
1680 wants_raw_input = cmd_obj->WantsRawCommandString ();
1681 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1682 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001683 }
1684 else
1685 {
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001686 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton5521f992011-10-28 21:38:01 +00001687 if (cmd_obj)
1688 {
1689 actual_cmd_name_len += next_word.length();
1690 revised_command_line.Printf ("%s", next_word.c_str());
1691 wants_raw_input = cmd_obj->WantsRawCommandString ();
1692 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001693 else
Greg Clayton5521f992011-10-28 21:38:01 +00001694 {
1695 revised_command_line.Printf ("%s", next_word.c_str());
1696 }
Caroline Tice844d2302010-12-09 22:52:49 +00001697 }
1698 }
1699 else
1700 {
Greg Clayton5521f992011-10-28 21:38:01 +00001701 if (cmd_obj->IsMultiwordObject ())
1702 {
Greg Clayton998255b2012-10-13 02:07:45 +00001703 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
Greg Clayton5521f992011-10-28 21:38:01 +00001704 if (sub_cmd_obj)
1705 {
1706 actual_cmd_name_len += next_word.length() + 1;
1707 revised_command_line.Printf (" %s", next_word.c_str());
1708 cmd_obj = sub_cmd_obj;
1709 wants_raw_input = cmd_obj->WantsRawCommandString ();
1710 }
1711 else
1712 {
1713 if (quote_char)
1714 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1715 else
1716 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1717 done = true;
1718 }
1719 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001720 else
Greg Clayton5521f992011-10-28 21:38:01 +00001721 {
1722 if (quote_char)
1723 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1724 else
1725 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1726 done = true;
1727 }
Caroline Tice844d2302010-12-09 22:52:49 +00001728 }
1729
Ed Masted78c9572014-04-20 00:31:37 +00001730 if (cmd_obj == nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001731 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001732 const size_t num_matches = matches.GetSize();
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001733 if (matches.GetSize() > 1) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001734 StreamString error_msg;
1735 error_msg.Printf ("Ambiguous command '%s'. Possible matches:\n", next_word.c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001736
1737 for (uint32_t i = 0; i < num_matches; ++i) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001738 error_msg.Printf ("\t%s\n", matches.GetStringAtIndex(i));
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001739 }
Greg Claytonc7bece562013-01-25 18:06:21 +00001740 result.AppendRawError (error_msg.GetString().c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001741 } else {
1742 // We didn't have only one match, otherwise we wouldn't get here.
1743 assert(num_matches == 0);
1744 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1745 }
Caroline Tice844d2302010-12-09 22:52:49 +00001746 result.SetStatus (eReturnStatusFailed);
1747 return false;
1748 }
1749
Greg Clayton5521f992011-10-28 21:38:01 +00001750 if (cmd_obj->IsMultiwordObject ())
1751 {
1752 if (!suffix.empty())
1753 {
1754
Enrico Granataaded51d2013-06-12 00:44:43 +00001755 result.AppendErrorWithFormat ("command '%s' did not recognize '%s%s%s' as valid (subcommand might be invalid).\n",
1756 cmd_obj->GetCommandName(),
1757 next_word.empty() ? "" : next_word.c_str(),
1758 next_word.empty() ? " -- " : " ",
Greg Clayton5521f992011-10-28 21:38:01 +00001759 suffix.c_str());
1760 result.SetStatus (eReturnStatusFailed);
1761 return false;
1762 }
1763 }
1764 else
1765 {
1766 // If we found a normal command, we are done
1767 done = true;
1768 if (!suffix.empty())
1769 {
1770 switch (suffix[0])
1771 {
1772 case '/':
1773 // GDB format suffixes
Greg Clayton52ec56c2011-10-29 00:57:28 +00001774 {
1775 Options *command_options = cmd_obj->GetOptions();
1776 if (command_options && command_options->SupportsLongOption("gdb-format"))
1777 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001778 std::string gdb_format_option ("--gdb-format=");
1779 gdb_format_option += (suffix.c_str() + 1);
1780
1781 bool inserted = false;
1782 std::string &cmd = revised_command_line.GetString();
1783 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1784 if (arg_terminator_idx != std::string::npos)
1785 {
1786 // Insert the gdb format option before the "--" that terminates options
1787 gdb_format_option.append(1,' ');
1788 cmd.insert(arg_terminator_idx, gdb_format_option);
1789 inserted = true;
1790 }
1791
1792 if (!inserted)
1793 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1794
1795 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1796 revised_command_line.PutCString (" --");
Greg Clayton52ec56c2011-10-29 00:57:28 +00001797 }
1798 else
1799 {
1800 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1801 cmd_obj->GetCommandName());
1802 result.SetStatus (eReturnStatusFailed);
1803 return false;
1804 }
1805 }
Greg Clayton5521f992011-10-28 21:38:01 +00001806 break;
Johnny Chen8e9383d2011-10-31 22:22:06 +00001807
1808 default:
1809 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1810 suffix.c_str());
1811 result.SetStatus (eReturnStatusFailed);
1812 return false;
1813
Greg Clayton5521f992011-10-28 21:38:01 +00001814 }
1815 }
1816 }
Caroline Tice844d2302010-12-09 22:52:49 +00001817 if (command_string.length() == 0)
1818 done = true;
1819
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001820 }
Caroline Tice844d2302010-12-09 22:52:49 +00001821
Greg Clayton5521f992011-10-28 21:38:01 +00001822 if (!command_string.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001823 revised_command_line.Printf (" %s", command_string.c_str());
1824
1825 // End of Phase 1.
1826 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1827 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1828 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1829 // wants_raw_input specifies whether the Execute method expects raw input or not.
1830
1831
1832 if (log)
1833 {
1834 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1835 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1836 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1837 }
1838
1839 // Phase 2.
1840 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1841 // CommandObject, with the appropriate arguments.
1842
Ed Masted78c9572014-04-20 00:31:37 +00001843 if (cmd_obj != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001844 {
1845 if (add_to_history)
1846 {
1847 Args command_args (revised_command_line.GetData());
1848 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
Ed Masted78c9572014-04-20 00:31:37 +00001849 if (repeat_command != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001850 m_repeat_command.assign(repeat_command);
1851 else
Jim Inghama5a97eb2011-07-12 03:12:18 +00001852 m_repeat_command.assign(original_command_string.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001853
Enrico Granata7594f142013-06-17 22:51:50 +00001854 m_command_history.AppendString (original_command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001855 }
1856
1857 command_string = revised_command_line.GetData();
1858 std::string command_name (cmd_obj->GetCommandName());
Caroline Tice01274c02010-12-11 08:16:56 +00001859 std::string remainder;
1860 if (actual_cmd_name_len < command_string.length())
1861 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1862 // than cmd_obj->GetCommandName(), because name completion
1863 // allows users to enter short versions of the names,
1864 // e.g. 'br s' for 'breakpoint set'.
Caroline Tice844d2302010-12-09 22:52:49 +00001865
1866 // Remove any initial spaces
1867 std::string white_space (" \t\v");
1868 size_t pos = remainder.find_first_not_of (white_space);
1869 if (pos != 0 && pos != std::string::npos)
Greg Claytona3482592011-04-22 20:58:45 +00001870 remainder.erase(0, pos);
Caroline Tice844d2302010-12-09 22:52:49 +00001871
1872 if (log)
Jason Molendabfb36ff2011-08-25 00:20:04 +00001873 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001874
Jim Ingham5a988412012-06-08 21:56:10 +00001875 cmd_obj->Execute (remainder.c_str(), result);
Caroline Tice844d2302010-12-09 22:52:49 +00001876 }
1877 else
1878 {
1879 // We didn't find the first command object, so complete the first argument.
1880 Args command_args (revised_command_line.GetData());
1881 StringList matches;
1882 int num_matches;
1883 int cursor_index = 0;
1884 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1885 bool word_complete;
1886 num_matches = HandleCompletionMatches (command_args,
1887 cursor_index,
1888 cursor_char_position,
1889 0,
1890 -1,
1891 word_complete,
1892 matches);
1893
1894 if (num_matches > 0)
1895 {
1896 std::string error_msg;
1897 error_msg.assign ("ambiguous command '");
1898 error_msg.append(command_args.GetArgumentAtIndex(0));
1899 error_msg.append ("'.");
1900
1901 error_msg.append (" Possible completions:");
1902 for (int i = 0; i < num_matches; i++)
1903 {
1904 error_msg.append ("\n\t");
1905 error_msg.append (matches.GetStringAtIndex (i));
1906 }
1907 error_msg.append ("\n");
Greg Claytonc7bece562013-01-25 18:06:21 +00001908 result.AppendRawError (error_msg.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001909 }
1910 else
1911 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1912
1913 result.SetStatus (eReturnStatusFailed);
1914 }
1915
Jason Molendabfb36ff2011-08-25 00:20:04 +00001916 if (log)
1917 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1918
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001919 return result.Succeeded();
1920}
1921
1922int
1923CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1924 int &cursor_index,
1925 int &cursor_char_position,
1926 int match_start_point,
1927 int max_return_elements,
Jim Ingham558ce122010-06-30 05:02:46 +00001928 bool &word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001929 StringList &matches)
1930{
1931 int num_command_matches = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001932 bool look_for_subcommand = false;
Jim Ingham558ce122010-06-30 05:02:46 +00001933
1934 // For any of the command completions a unique match will be a complete word.
1935 word_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001936
1937 if (cursor_index == -1)
1938 {
1939 // We got nothing on the command line, so return the list of commands
Jim Ingham279a6c22010-07-06 22:46:59 +00001940 bool include_aliases = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001941 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1942 }
1943 else if (cursor_index == 0)
1944 {
1945 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Ingham279a6c22010-07-06 22:46:59 +00001946 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001947 num_command_matches = matches.GetSize();
1948
1949 if (num_command_matches == 1
1950 && cmd_obj && cmd_obj->IsMultiwordObject()
Ed Masted78c9572014-04-20 00:31:37 +00001951 && matches.GetStringAtIndex(0) != nullptr
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001952 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1953 {
Greg Clayton765d2e22013-12-10 19:14:04 +00001954 if (parsed_line.GetArgumentCount() == 1)
1955 {
1956 word_complete = true;
1957 }
1958 else
1959 {
1960 look_for_subcommand = true;
1961 num_command_matches = 0;
1962 matches.DeleteStringAtIndex(0);
1963 parsed_line.AppendArgument ("");
1964 cursor_index++;
1965 cursor_char_position = 0;
1966 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001967 }
1968 }
1969
1970 if (cursor_index > 0 || look_for_subcommand)
1971 {
1972 // We are completing further on into a commands arguments, so find the command and tell it
1973 // to complete the command.
1974 // First see if there is a matching initial command:
Jim Ingham279a6c22010-07-06 22:46:59 +00001975 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Ed Masted78c9572014-04-20 00:31:37 +00001976 if (command_object == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001977 {
1978 return 0;
1979 }
1980 else
1981 {
1982 parsed_line.Shift();
1983 cursor_index--;
Greg Claytona7015092010-09-18 01:14:36 +00001984 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton66111032010-06-23 01:19:29 +00001985 cursor_index,
1986 cursor_char_position,
1987 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001988 max_return_elements,
1989 word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001990 matches);
1991 }
1992 }
1993
1994 return num_command_matches;
1995
1996}
1997
1998int
1999CommandInterpreter::HandleCompletion (const char *current_line,
2000 const char *cursor,
2001 const char *last_char,
2002 int match_start_point,
2003 int max_return_elements,
2004 StringList &matches)
2005{
2006 // We parse the argument up to the cursor, so the last argument in parsed_line is
2007 // the one containing the cursor, and the cursor is after the last character.
2008
2009 Args parsed_line(current_line, last_char - current_line);
2010 Args partial_parsed_line(current_line, cursor - current_line);
2011
Jim Inghama5a97eb2011-07-12 03:12:18 +00002012 // Don't complete comments, and if the line we are completing is just the history repeat character,
2013 // substitute the appropriate history line.
2014 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
2015 if (first_arg)
2016 {
2017 if (first_arg[0] == m_comment_char)
2018 return 0;
Enrico Granata7594f142013-06-17 22:51:50 +00002019 else if (first_arg[0] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002020 {
Enrico Granata7594f142013-06-17 22:51:50 +00002021 const char *history_string = m_command_history.FindString (first_arg);
Ed Masted78c9572014-04-20 00:31:37 +00002022 if (history_string != nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002023 {
2024 matches.Clear();
2025 matches.InsertStringAtIndex(0, history_string);
2026 return -2;
2027 }
2028 else
2029 return 0;
2030
2031 }
2032 }
2033
2034
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002035 int num_args = partial_parsed_line.GetArgumentCount();
2036 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
2037 int cursor_char_position;
2038
2039 if (cursor_index == -1)
2040 cursor_char_position = 0;
2041 else
2042 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamfe0c4252010-12-14 19:56:01 +00002043
2044 if (cursor > current_line && cursor[-1] == ' ')
2045 {
2046 // We are just after a space. If we are in an argument, then we will continue
2047 // parsing, but if we are between arguments, then we have to complete whatever the next
2048 // element would be.
2049 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
2050 // protected by a quote) then the space will also be in the parsed argument...
2051
2052 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
2053 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
2054 {
Greg Clayton765d2e22013-12-10 19:14:04 +00002055 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '\0');
Jim Inghamfe0c4252010-12-14 19:56:01 +00002056 cursor_index++;
2057 cursor_char_position = 0;
2058 }
2059 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002060
2061 int num_command_matches;
2062
2063 matches.Clear();
2064
2065 // Only max_return_elements == -1 is supported at present:
2066 assert (max_return_elements == -1);
Jim Ingham558ce122010-06-30 05:02:46 +00002067 bool word_complete;
Greg Clayton66111032010-06-23 01:19:29 +00002068 num_command_matches = HandleCompletionMatches (parsed_line,
2069 cursor_index,
2070 cursor_char_position,
2071 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00002072 max_return_elements,
2073 word_complete,
Greg Clayton66111032010-06-23 01:19:29 +00002074 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002075
2076 if (num_command_matches <= 0)
2077 return num_command_matches;
2078
2079 if (num_args == 0)
2080 {
2081 // If we got an empty string, insert nothing.
2082 matches.InsertStringAtIndex(0, "");
2083 }
2084 else
2085 {
2086 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
2087 // put an empty string in element 0.
2088 std::string command_partial_str;
2089 if (cursor_index >= 0)
Jim Ingham49e80a12010-10-22 18:47:16 +00002090 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
2091 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002092
2093 std::string common_prefix;
2094 matches.LongestCommonPrefix (common_prefix);
Greg Claytonc7bece562013-01-25 18:06:21 +00002095 const size_t partial_name_len = command_partial_str.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002096
2097 // If we matched a unique single command, add a space...
Jim Ingham558ce122010-06-30 05:02:46 +00002098 // Only do this if the completer told us this was a complete word, however...
2099 if (num_command_matches == 1 && word_complete)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002100 {
2101 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
2102 if (quote_char != '\0')
2103 common_prefix.push_back(quote_char);
2104
2105 common_prefix.push_back(' ');
2106 }
2107 common_prefix.erase (0, partial_name_len);
2108 matches.InsertStringAtIndex(0, common_prefix.c_str());
2109 }
2110 return num_command_matches;
2111}
2112
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002113
2114CommandInterpreter::~CommandInterpreter ()
2115{
2116}
2117
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002118void
Greg Clayton44d93782014-01-27 23:43:24 +00002119CommandInterpreter::UpdatePrompt (const char *new_prompt)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002120{
Greg Clayton44d93782014-01-27 23:43:24 +00002121 EventSP prompt_change_event_sp (new Event(eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));;
2122 BroadcastEvent (prompt_change_event_sp);
2123 if (m_command_io_handler_sp)
2124 m_command_io_handler_sp->SetPrompt(new_prompt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002125}
2126
Jim Ingham97a6dc72010-10-04 19:49:29 +00002127
2128bool
2129CommandInterpreter::Confirm (const char *message, bool default_answer)
2130{
Jim Ingham3bcdb292010-10-04 22:44:14 +00002131 // Check AutoConfirm first:
2132 if (m_debugger.GetAutoConfirm())
2133 return default_answer;
Greg Clayton44d93782014-01-27 23:43:24 +00002134
2135 IOHandlerConfirm *confirm = new IOHandlerConfirm(m_debugger,
2136 message,
2137 default_answer);
2138 IOHandlerSP io_handler_sp (confirm);
2139 m_debugger.RunIOHandler (io_handler_sp);
2140 return confirm->GetResponse();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002141}
2142
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002143OptionArgVectorSP
2144CommandInterpreter::GetAliasOptions (const char *alias_name)
2145{
2146 OptionArgMap::iterator pos;
2147 OptionArgVectorSP ret_val;
2148
2149 std::string alias (alias_name);
2150
2151 if (HasAliasOptions())
2152 {
2153 pos = m_alias_options.find (alias);
2154 if (pos != m_alias_options.end())
2155 ret_val = pos->second;
2156 }
2157
2158 return ret_val;
2159}
2160
2161void
2162CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2163{
2164 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2165 if (pos != m_alias_options.end())
2166 {
2167 m_alias_options.erase (pos);
2168 }
2169}
2170
2171void
2172CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2173{
2174 m_alias_options[alias_name] = option_arg_vector_sp;
2175}
2176
2177bool
2178CommandInterpreter::HasCommands ()
2179{
2180 return (!m_command_dict.empty());
2181}
2182
2183bool
2184CommandInterpreter::HasAliases ()
2185{
2186 return (!m_alias_dict.empty());
2187}
2188
2189bool
2190CommandInterpreter::HasUserCommands ()
2191{
2192 return (!m_user_dict.empty());
2193}
2194
2195bool
2196CommandInterpreter::HasAliasOptions ()
2197{
2198 return (!m_alias_options.empty());
2199}
2200
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002201void
Caroline Tice4ab31c92010-10-12 21:57:09 +00002202CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2203 const char *alias_name,
2204 Args &cmd_args,
Caroline Ticed9d63362010-12-07 19:58:26 +00002205 std::string &raw_input_string,
Caroline Tice4ab31c92010-10-12 21:57:09 +00002206 CommandReturnObject &result)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002207{
2208 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Ticed9d63362010-12-07 19:58:26 +00002209
2210 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002211
Caroline Ticed9d63362010-12-07 19:58:26 +00002212 // Make sure that the alias name is the 0th element in cmd_args
2213 std::string alias_name_str = alias_name;
2214 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2215 cmd_args.Unshift (alias_name);
2216
2217 Args new_args (alias_cmd_obj->GetCommandName());
2218 if (new_args.GetArgumentCount() == 2)
2219 new_args.Shift();
2220
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002221 if (option_arg_vector_sp.get())
2222 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002223 if (wants_raw_input)
2224 {
2225 // We have a command that both has command options and takes raw input. Make *sure* it has a
2226 // " -- " in the right place in the raw_input_string.
2227 size_t pos = raw_input_string.find(" -- ");
2228 if (pos == std::string::npos)
2229 {
2230 // None found; assume it goes at the beginning of the raw input string
2231 raw_input_string.insert (0, " -- ");
2232 }
2233 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002234
2235 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Greg Claytonc7bece562013-01-25 18:06:21 +00002236 const size_t old_size = cmd_args.GetArgumentCount();
Caroline Tice4ab31c92010-10-12 21:57:09 +00002237 std::vector<bool> used (old_size + 1, false);
2238
2239 used[0] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002240
Andy Gibbsa297a972013-06-19 19:04:53 +00002241 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002242 {
2243 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Ticed9d63362010-12-07 19:58:26 +00002244 OptionArgValue value_pair = option_pair.second;
2245 int value_type = value_pair.first;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002246 std::string option = option_pair.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00002247 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002248 if (option.compare ("<argument>") == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002249 {
2250 if (!wants_raw_input
2251 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2252 new_args.AppendArgument (value.c_str());
2253 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002254 else
2255 {
Virgile Belloe2607b52013-09-05 16:42:23 +00002256 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002257 new_args.AppendArgument (option.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002258 if (value.compare ("<no-argument>") != 0)
2259 {
2260 int index = GetOptionArgumentPosition (value.c_str());
2261 if (index == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002262 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002263 // value was NOT a positional argument; must be a real value
Virgile Belloe2607b52013-09-05 16:42:23 +00002264 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002265 new_args.AppendArgument (value.c_str());
2266 else
2267 {
2268 char buffer[255];
2269 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2270 new_args.AppendArgument (buffer);
2271 }
2272
2273 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002274 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002275 {
2276 result.AppendErrorWithFormat
2277 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2278 index);
2279 result.SetStatus (eReturnStatusFailed);
2280 return;
2281 }
2282 else
2283 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002284 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2285 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2286 if (strpos != std::string::npos)
2287 {
2288 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2289 }
2290
Virgile Belloe2607b52013-09-05 16:42:23 +00002291 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002292 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2293 else
2294 {
2295 char buffer[255];
2296 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2297 cmd_args.GetArgumentAtIndex (index));
2298 new_args.AppendArgument (buffer);
2299 }
Caroline Tice4ab31c92010-10-12 21:57:09 +00002300 used[index] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002301 }
2302 }
2303 }
2304 }
2305
Andy Gibbsa297a972013-06-19 19:04:53 +00002306 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002307 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002308 if (!used[j] && !wants_raw_input)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002309 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2310 }
2311
2312 cmd_args.Clear();
2313 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2314 }
2315 else
2316 {
2317 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Ticed9d63362010-12-07 19:58:26 +00002318 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2319 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2320 // input string.
2321 if (wants_raw_input)
2322 {
2323 cmd_args.Clear();
2324 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2325 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002326 return;
2327 }
2328
2329 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2330 return;
2331}
2332
2333
2334int
2335CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2336{
2337 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2338 // of zero.
2339
2340 char *cptr = (char *) in_string;
2341
2342 // Does it start with '%'
2343 if (cptr[0] == '%')
2344 {
2345 ++cptr;
2346
2347 // Is the rest of it entirely digits?
2348 if (isdigit (cptr[0]))
2349 {
2350 const char *start = cptr;
2351 while (isdigit (cptr[0]))
2352 ++cptr;
2353
2354 // We've gotten to the end of the digits; are we at the end of the string?
2355 if (cptr[0] == '\0')
2356 position = atoi (start);
2357 }
2358 }
2359
2360 return position;
2361}
2362
2363void
2364CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2365{
Jim Ingham16e0c682011-08-12 23:34:31 +00002366 FileSpec init_file;
Greg Clayton14a35512011-09-11 00:01:44 +00002367 if (in_cwd)
Jim Ingham16e0c682011-08-12 23:34:31 +00002368 {
Greg Clayton14a35512011-09-11 00:01:44 +00002369 // In the current working directory we don't load any program specific
2370 // .lldbinit files, we only look for a "./.lldbinit" file.
2371 if (m_skip_lldbinit_files)
2372 return;
2373
2374 init_file.SetFile ("./.lldbinit", true);
Jim Ingham16e0c682011-08-12 23:34:31 +00002375 }
Greg Clayton14a35512011-09-11 00:01:44 +00002376 else
Jim Ingham16e0c682011-08-12 23:34:31 +00002377 {
Greg Clayton14a35512011-09-11 00:01:44 +00002378 // If we aren't looking in the current working directory we are looking
2379 // in the home directory. We will first see if there is an application
2380 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2381 // "-" and the name of the program. If this file doesn't exist, we fall
2382 // back to just the "~/.lldbinit" file. We also obey any requests to not
2383 // load the init files.
Zachary Turner9e757b72014-07-28 16:45:05 +00002384 FileSpec profilePath = Host::GetUserProfileFileSpec();
2385 profilePath.AppendPathComponent(".lldbinit");
2386 std::string init_file_path = profilePath.GetPath();
Greg Clayton14a35512011-09-11 00:01:44 +00002387
2388 if (m_skip_app_init_files == false)
2389 {
2390 FileSpec program_file_spec (Host::GetProgramFileSpec());
2391 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham16e0c682011-08-12 23:34:31 +00002392
Greg Clayton14a35512011-09-11 00:01:44 +00002393 if (program_name)
2394 {
2395 char program_init_file_name[PATH_MAX];
Zachary Turner9e757b72014-07-28 16:45:05 +00002396 ::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 +00002397 init_file.SetFile (program_init_file_name, true);
2398 if (!init_file.Exists())
2399 init_file.Clear();
2400 }
2401 }
2402
2403 if (!init_file && !m_skip_lldbinit_files)
Zachary Turner9e757b72014-07-28 16:45:05 +00002404 init_file.SetFile (init_file_path.c_str(), false);
Greg Clayton14a35512011-09-11 00:01:44 +00002405 }
2406
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002407 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2408 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2409
2410 if (init_file.Exists())
2411 {
Greg Clayton44d93782014-01-27 23:43:24 +00002412 const bool saved_batch = SetBatchCommandMode (true);
Greg Clayton340b0302014-02-05 17:57:57 +00002413 HandleCommandsFromFile (init_file,
Ed Masted78c9572014-04-20 00:31:37 +00002414 nullptr, // Execution context
Greg Clayton340b0302014-02-05 17:57:57 +00002415 eLazyBoolYes, // Stop on continue
2416 eLazyBoolNo, // Stop on error
2417 eLazyBoolNo, // Don't echo commands
2418 eLazyBoolNo, // Don't print command output
2419 eLazyBoolNo, // Don't add the commands that are sourced into the history buffer
2420 result);
Greg Clayton44d93782014-01-27 23:43:24 +00002421 SetBatchCommandMode (saved_batch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002422 }
2423 else
2424 {
2425 // nothing to be done if the file doesn't exist
2426 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2427 }
2428}
2429
Greg Clayton8b82f082011-04-12 05:54:46 +00002430PlatformSP
2431CommandInterpreter::GetPlatform (bool prefer_target_platform)
2432{
2433 PlatformSP platform_sp;
Greg Claytonc14ee322011-09-22 04:58:26 +00002434 if (prefer_target_platform)
2435 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002436 ExecutionContext exe_ctx(GetExecutionContext());
2437 Target *target = exe_ctx.GetTargetPtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002438 if (target)
2439 platform_sp = target->GetPlatform();
2440 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002441
2442 if (!platform_sp)
2443 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2444 return platform_sp;
2445}
2446
Jim Inghame16c50a2011-02-18 00:54:25 +00002447void
Jim Inghambad87fe2011-03-11 01:51:49 +00002448CommandInterpreter::HandleCommands (const StringList &commands,
Jim Inghame16c50a2011-02-18 00:54:25 +00002449 ExecutionContext *override_context,
2450 bool stop_on_continue,
2451 bool stop_on_error,
2452 bool echo_commands,
2453 bool print_results,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002454 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002455 CommandReturnObject &result)
2456{
2457 size_t num_lines = commands.GetSize();
Jim Inghame16c50a2011-02-18 00:54:25 +00002458
2459 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2460 // Make sure you reset this value anywhere you return from the function.
2461
2462 bool old_async_execution = m_debugger.GetAsyncExecution();
2463
2464 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2465 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2466
Ed Masted78c9572014-04-20 00:31:37 +00002467 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00002468 UpdateExecutionContext (override_context);
Jim Inghame16c50a2011-02-18 00:54:25 +00002469
2470 if (!stop_on_continue)
2471 {
2472 m_debugger.SetAsyncExecution (false);
2473 }
2474
Andy Gibbsa297a972013-06-19 19:04:53 +00002475 for (size_t idx = 0; idx < num_lines; idx++)
Jim Inghame16c50a2011-02-18 00:54:25 +00002476 {
2477 const char *cmd = commands.GetStringAtIndex(idx);
2478 if (cmd[0] == '\0')
2479 continue;
2480
Jim Inghame16c50a2011-02-18 00:54:25 +00002481 if (echo_commands)
2482 {
2483 result.AppendMessageWithFormat ("%s %s\n",
Greg Clayton44d93782014-01-27 23:43:24 +00002484 m_debugger.GetPrompt(),
2485 cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002486 }
2487
Greg Clayton9d0402b2011-02-20 02:15:07 +00002488 CommandReturnObject tmp_result;
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002489 // If override_context is not NULL, pass no_context_switching = true for
2490 // HandleCommand() since we updated our context already.
Jim Ingham076b7fc2013-05-02 23:15:37 +00002491
2492 // We might call into a regex or alias command, in which case the add_to_history will get lost. This
2493 // m_command_source_depth dingus is the way we turn off adding to the history in that case, so set it up here.
2494 if (!add_to_history)
2495 m_command_source_depth++;
Enrico Granata5f5ab602012-05-31 01:09:06 +00002496 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Ed Masted78c9572014-04-20 00:31:37 +00002497 nullptr, /* override_context */
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002498 true, /* repeat_on_empty_command */
Ed Masted78c9572014-04-20 00:31:37 +00002499 override_context != nullptr /* no_context_switching */);
Jim Ingham076b7fc2013-05-02 23:15:37 +00002500 if (!add_to_history)
2501 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002502
2503 if (print_results)
2504 {
2505 if (tmp_result.Succeeded())
Jim Ingham85e8b812011-02-19 02:53:09 +00002506 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Inghame16c50a2011-02-18 00:54:25 +00002507 }
2508
2509 if (!success || !tmp_result.Succeeded())
2510 {
Jim Inghama5038812012-04-24 02:25:07 +00002511 const char *error_msg = tmp_result.GetErrorData();
Ed Masted78c9572014-04-20 00:31:37 +00002512 if (error_msg == nullptr || error_msg[0] == '\0')
Jim Inghama5038812012-04-24 02:25:07 +00002513 error_msg = "<unknown error>.\n";
Jim Inghame16c50a2011-02-18 00:54:25 +00002514 if (stop_on_error)
2515 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002516 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' failed with %s",
2517 (uint64_t)idx, cmd, error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002518 result.SetStatus (eReturnStatusFailed);
2519 m_debugger.SetAsyncExecution (old_async_execution);
2520 return;
2521 }
2522 else if (print_results)
2523 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002524 result.AppendMessageWithFormat ("Command #%" PRIu64 " '%s' failed with %s",
2525 (uint64_t)idx + 1,
Jim Inghame16c50a2011-02-18 00:54:25 +00002526 cmd,
Jim Inghama5038812012-04-24 02:25:07 +00002527 error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002528 }
2529 }
2530
Caroline Tice969ed3d2011-05-02 20:41:46 +00002531 if (result.GetImmediateOutputStream())
2532 result.GetImmediateOutputStream()->Flush();
2533
2534 if (result.GetImmediateErrorStream())
2535 result.GetImmediateErrorStream()->Flush();
2536
Jim Inghame16c50a2011-02-18 00:54:25 +00002537 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2538 // could be running (for instance in Breakpoint Commands.
2539 // So we check the return value to see if it is has running in it.
2540 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2541 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2542 {
2543 if (stop_on_continue)
2544 {
2545 // If we caused the target to proceed, and we're going to stop in that case, set the
2546 // status in our real result before returning. This is an error if the continue was not the
2547 // last command in the set of commands to be run.
2548 if (idx != num_lines - 1)
Deepak Panickal99fbc072014-03-03 15:39:47 +00002549 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' continued the target.\n",
2550 (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002551 else
Deepak Panickal99fbc072014-03-03 15:39:47 +00002552 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' continued the target.\n", (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002553
2554 result.SetStatus(tmp_result.GetStatus());
2555 m_debugger.SetAsyncExecution (old_async_execution);
2556
2557 return;
2558 }
2559 }
2560
2561 }
2562
2563 result.SetStatus (eReturnStatusSuccessFinishResult);
2564 m_debugger.SetAsyncExecution (old_async_execution);
2565
2566 return;
2567}
2568
Greg Clayton340b0302014-02-05 17:57:57 +00002569// Make flags that we can pass into the IOHandler so our delegates can do the right thing
2570enum {
2571 eHandleCommandFlagStopOnContinue = (1u << 0),
2572 eHandleCommandFlagStopOnError = (1u << 1),
2573 eHandleCommandFlagEchoCommand = (1u << 2),
2574 eHandleCommandFlagPrintResult = (1u << 3)
2575};
2576
Jim Inghame16c50a2011-02-18 00:54:25 +00002577void
2578CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2579 ExecutionContext *context,
Greg Clayton340b0302014-02-05 17:57:57 +00002580 LazyBool stop_on_continue,
2581 LazyBool stop_on_error,
2582 LazyBool echo_command,
2583 LazyBool print_result,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002584 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002585 CommandReturnObject &result)
2586{
2587 if (cmd_file.Exists())
2588 {
Greg Clayton44d93782014-01-27 23:43:24 +00002589 StreamFileSP input_file_sp (new StreamFile());
2590
2591 std::string cmd_file_path = cmd_file.GetPath();
2592 Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), File::eOpenOptionRead);
2593
2594 if (error.Success())
2595 {
2596 Debugger &debugger = GetDebugger();
2597
Greg Clayton340b0302014-02-05 17:57:57 +00002598 uint32_t flags = 0;
2599
2600 if (stop_on_continue == eLazyBoolCalculate)
2601 {
2602 if (m_command_source_flags.empty())
2603 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002604 // Stop on continue by default
Greg Clayton340b0302014-02-05 17:57:57 +00002605 flags |= eHandleCommandFlagStopOnContinue;
2606 }
2607 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnContinue)
2608 {
2609 flags |= eHandleCommandFlagStopOnContinue;
2610 }
2611 }
2612 else if (stop_on_continue == eLazyBoolYes)
2613 {
2614 flags |= eHandleCommandFlagStopOnContinue;
2615 }
2616
2617 if (stop_on_error == eLazyBoolCalculate)
2618 {
2619 if (m_command_source_flags.empty())
2620 {
2621 if (GetStopCmdSourceOnError())
2622 flags |= eHandleCommandFlagStopOnError;
2623 }
2624 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError)
2625 {
2626 flags |= eHandleCommandFlagStopOnError;
2627 }
2628 }
2629 else if (stop_on_error == eLazyBoolYes)
2630 {
2631 flags |= eHandleCommandFlagStopOnError;
2632 }
2633
2634 if (echo_command == eLazyBoolCalculate)
2635 {
2636 if (m_command_source_flags.empty())
2637 {
2638 // Echo command by default
2639 flags |= eHandleCommandFlagEchoCommand;
2640 }
2641 else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand)
2642 {
2643 flags |= eHandleCommandFlagEchoCommand;
2644 }
2645 }
2646 else if (echo_command == eLazyBoolYes)
2647 {
2648 flags |= eHandleCommandFlagEchoCommand;
2649 }
2650
2651 if (print_result == eLazyBoolCalculate)
2652 {
2653 if (m_command_source_flags.empty())
2654 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002655 // Print output by default
2656 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002657 }
Greg Claytone4e462c2014-02-05 21:03:22 +00002658 else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult)
Greg Clayton340b0302014-02-05 17:57:57 +00002659 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002660 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002661 }
2662 }
2663 else if (print_result == eLazyBoolYes)
2664 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002665 flags |= eHandleCommandFlagPrintResult;
2666 }
2667
2668 if (flags & eHandleCommandFlagPrintResult)
2669 {
Greg Clayton8ee67312014-02-05 21:46:20 +00002670 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", cmd_file_path.c_str());
Greg Clayton340b0302014-02-05 17:57:57 +00002671 }
2672
2673 // Used for inheriting the right settings when "command source" might have
2674 // nested "command source" commands
Greg Claytone4e462c2014-02-05 21:03:22 +00002675 lldb::StreamFileSP empty_stream_sp;
Greg Clayton340b0302014-02-05 17:57:57 +00002676 m_command_source_flags.push_back(flags);
Greg Clayton44d93782014-01-27 23:43:24 +00002677 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
2678 input_file_sp,
Greg Claytone4e462c2014-02-05 21:03:22 +00002679 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader output stream
2680 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader error stream
Greg Clayton340b0302014-02-05 17:57:57 +00002681 flags,
Ed Masted78c9572014-04-20 00:31:37 +00002682 nullptr, // Pass in NULL for "editline_name" so no history is saved, or written
Greg Clayton8ee67312014-02-05 21:46:20 +00002683 debugger.GetPrompt(),
Greg Clayton44d93782014-01-27 23:43:24 +00002684 false, // Not multi-line
Greg Claytonf6913cd2014-03-07 00:53:24 +00002685 0,
Greg Clayton44d93782014-01-27 23:43:24 +00002686 *this));
Greg Clayton8ee67312014-02-05 21:46:20 +00002687 const bool old_async_execution = debugger.GetAsyncExecution();
2688
2689 // Set synchronous execution if we not stopping when we continue
2690 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2691 debugger.SetAsyncExecution (false);
2692
Greg Clayton340b0302014-02-05 17:57:57 +00002693 m_command_source_depth++;
Greg Clayton8ee67312014-02-05 21:46:20 +00002694
2695 debugger.RunIOHandler(io_handler_sp);
Greg Clayton340b0302014-02-05 17:57:57 +00002696 if (!m_command_source_flags.empty())
2697 m_command_source_flags.pop_back();
2698 m_command_source_depth--;
Greg Clayton44d93782014-01-27 23:43:24 +00002699 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Greg Clayton8ee67312014-02-05 21:46:20 +00002700 debugger.SetAsyncExecution (old_async_execution);
Greg Clayton44d93782014-01-27 23:43:24 +00002701 }
2702 else
2703 {
2704 result.AppendErrorWithFormat ("error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(), error.AsCString());
2705 result.SetStatus (eReturnStatusFailed);
2706 }
Greg Clayton8ee67312014-02-05 21:46:20 +00002707
2708
Jim Inghame16c50a2011-02-18 00:54:25 +00002709 }
2710 else
2711 {
2712 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2713 cmd_file.GetFilename().AsCString());
2714 result.SetStatus (eReturnStatusFailed);
2715 return;
2716 }
2717}
2718
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002719ScriptInterpreter *
Enrico Granatab5887262012-10-29 21:18:03 +00002720CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002721{
Ed Masted78c9572014-04-20 00:31:37 +00002722 if (m_script_interpreter_ap.get() != nullptr)
Enrico Granatab5887262012-10-29 21:18:03 +00002723 return m_script_interpreter_ap.get();
2724
2725 if (!can_create)
Ed Masted78c9572014-04-20 00:31:37 +00002726 return nullptr;
Enrico Granatab5887262012-10-29 21:18:03 +00002727
Enrico Granataa29bdad2012-07-10 18:23:48 +00002728 // <rdar://problem/11751427>
2729 // we need to protect the initialization of the script interpreter
2730 // otherwise we could end up with two threads both trying to create
2731 // their instance of it, and for some languages (e.g. Python)
2732 // this is a bulletproof recipe for disaster!
2733 // this needs to be a function-level static because multiple Debugger instances living in the same process
2734 // still need to be isolated and not try to initialize Python concurrently
Enrico Granata8b95df22012-07-10 19:04:14 +00002735 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2736 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granataa29bdad2012-07-10 18:23:48 +00002737
Greg Clayton5160ce52013-03-27 23:08:40 +00002738 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Enrico Granatab5887262012-10-29 21:18:03 +00002739 if (log)
2740 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton66111032010-06-23 01:19:29 +00002741
Caroline Tice2f88aad2011-01-14 00:29:16 +00002742 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2743 switch (script_lang)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002744 {
Greg Claytondce502e2011-11-04 03:34:56 +00002745 case eScriptLanguagePython:
2746#ifndef LLDB_DISABLE_PYTHON
2747 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2748 break;
2749#else
2750 // Fall through to the None case when python is disabled
2751#endif
Caroline Tice2f88aad2011-01-14 00:29:16 +00002752 case eScriptLanguageNone:
2753 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2754 break;
Caroline Tice2f88aad2011-01-14 00:29:16 +00002755 };
2756
2757 return m_script_interpreter_ap.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002758}
2759
2760
2761
2762bool
2763CommandInterpreter::GetSynchronous ()
2764{
2765 return m_synchronous_execution;
2766}
2767
2768void
2769CommandInterpreter::SetSynchronous (bool value)
2770{
Johnny Chenc066ab42010-10-14 01:22:03 +00002771 m_synchronous_execution = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002772}
2773
2774void
2775CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2776 const char *word_text,
2777 const char *separator,
2778 const char *help_text,
Greg Claytonc7bece562013-01-25 18:06:21 +00002779 size_t max_word_len)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002780{
Greg Claytona7015092010-09-18 01:14:36 +00002781 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2782
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002783 int indent_size = max_word_len + strlen (separator) + 2;
2784
2785 strm.IndentMore (indent_size);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002786
2787 StreamString text_strm;
Greg Claytonc7bece562013-01-25 18:06:21 +00002788 text_strm.Printf ("%-*s %s %s", (int)max_word_len, word_text, separator, help_text);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002789
2790 size_t len = text_strm.GetSize();
2791 const char *text = text_strm.GetData();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002792 if (text[len - 1] == '\n')
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002793 {
2794 text_strm.EOL();
2795 len = text_strm.GetSize();
2796 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002797
2798 if (len < max_columns)
2799 {
2800 // Output it as a single line.
2801 strm.Printf ("%s", text);
2802 }
2803 else
2804 {
2805 // We need to break it up into multiple lines.
2806 bool first_line = true;
2807 int text_width;
Greg Claytonc7bece562013-01-25 18:06:21 +00002808 size_t start = 0;
2809 size_t end = start;
2810 const size_t final_end = strlen (text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002811
2812 while (end < final_end)
2813 {
2814 if (first_line)
2815 text_width = max_columns - 1;
2816 else
2817 text_width = max_columns - indent_size - 1;
2818
2819 // Don't start the 'text' on a space, since we're already outputting the indentation.
2820 if (!first_line)
2821 {
2822 while ((start < final_end) && (text[start] == ' '))
2823 start++;
2824 }
2825
2826 end = start + text_width;
2827 if (end > final_end)
2828 end = final_end;
2829 else
2830 {
2831 // If we're not at the end of the text, make sure we break the line on white space.
2832 while (end > start
2833 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2834 end--;
Greg Clayton67cc0632012-08-22 17:17:09 +00002835 assert (end > 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002836 }
2837
Greg Claytonc7bece562013-01-25 18:06:21 +00002838 const size_t sub_len = end - start;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002839 if (start != 0)
2840 strm.EOL();
2841 if (!first_line)
2842 strm.Indent();
2843 else
2844 first_line = false;
2845 assert (start <= final_end);
2846 assert (start + sub_len <= final_end);
2847 if (sub_len > 0)
2848 strm.Write (text + start, sub_len);
2849 start = end + 1;
2850 }
2851 }
2852 strm.EOL();
2853 strm.IndentLess(indent_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002854}
2855
2856void
Enrico Granata82a7d982011-07-07 00:38:40 +00002857CommandInterpreter::OutputHelpText (Stream &strm,
2858 const char *word_text,
2859 const char *separator,
2860 const char *help_text,
2861 uint32_t max_word_len)
2862{
2863 int indent_size = max_word_len + strlen (separator) + 2;
2864
2865 strm.IndentMore (indent_size);
2866
2867 StreamString text_strm;
2868 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2869
2870 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata82a7d982011-07-07 00:38:40 +00002871
2872 size_t len = text_strm.GetSize();
2873 const char *text = text_strm.GetData();
2874
2875 uint32_t chars_left = max_columns;
2876
2877 for (uint32_t i = 0; i < len; i++)
2878 {
2879 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2880 {
Enrico Granata82a7d982011-07-07 00:38:40 +00002881 chars_left = max_columns - indent_size;
2882 strm.EOL();
2883 strm.Indent();
2884 }
2885 else
2886 {
2887 strm.PutChar(text[i]);
2888 chars_left--;
2889 }
2890
2891 }
2892
2893 strm.EOL();
2894 strm.IndentLess(indent_size);
2895}
2896
2897void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002898CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
Jim Inghamaf3753e2013-05-17 01:30:37 +00002899 StringList &commands_help, bool search_builtin_commands, bool search_user_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002900{
2901 CommandObject::CommandMap::const_iterator pos;
2902
Jim Inghamaf3753e2013-05-17 01:30:37 +00002903 if (search_builtin_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002904 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00002905 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002906 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00002907 const char *command_name = pos->first.c_str();
2908 CommandObject *cmd_obj = pos->second.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002909
Jim Inghamaf3753e2013-05-17 01:30:37 +00002910 if (cmd_obj->HelpTextContainsWord (search_word))
2911 {
2912 commands_found.AppendString (command_name);
2913 commands_help.AppendString (cmd_obj->GetHelp());
2914 }
2915
2916 if (cmd_obj->IsMultiwordObject())
2917 cmd_obj->AproposAllSubCommands (command_name,
2918 search_word,
2919 commands_found,
2920 commands_help);
2921
2922 }
2923 }
2924
2925 if (search_user_commands)
2926 {
2927 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
2928 {
2929 const char *command_name = pos->first.c_str();
2930 CommandObject *cmd_obj = pos->second.get();
2931
2932 if (cmd_obj->HelpTextContainsWord (search_word))
2933 {
2934 commands_found.AppendString (command_name);
2935 commands_help.AppendString (cmd_obj->GetHelp());
2936 }
2937
2938 if (cmd_obj->IsMultiwordObject())
2939 cmd_obj->AproposAllSubCommands (command_name,
2940 search_word,
2941 commands_found,
2942 commands_help);
2943
2944 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002945 }
2946}
Greg Clayton8b82f082011-04-12 05:54:46 +00002947
Greg Clayton8b82f082011-04-12 05:54:46 +00002948void
2949CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2950{
Ed Masted78c9572014-04-20 00:31:37 +00002951 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00002952 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002953 m_exe_ctx_ref = *override_context;
Greg Clayton8b82f082011-04-12 05:54:46 +00002954 }
2955 else
2956 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002957 const bool adopt_selected = true;
2958 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Clayton8b82f082011-04-12 05:54:46 +00002959 }
2960}
Greg Clayton44d93782014-01-27 23:43:24 +00002961
2962
2963size_t
2964CommandInterpreter::GetProcessOutput ()
2965{
2966 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
2967 char stdio_buffer[1024];
2968 size_t len;
2969 size_t total_bytes = 0;
2970 Error error;
2971 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
2972 if (target_sp)
2973 {
2974 ProcessSP process_sp (target_sp->GetProcessSP());
2975 if (process_sp)
2976 {
2977 while ((len = process_sp->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2978 {
2979 size_t bytes_written = len;
2980 m_debugger.GetOutputFile()->Write (stdio_buffer, bytes_written);
2981 total_bytes += len;
2982 }
2983 while ((len = process_sp->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2984 {
2985 size_t bytes_written = len;
2986 m_debugger.GetErrorFile()->Write (stdio_buffer, bytes_written);
2987 total_bytes += len;
2988 }
2989 }
2990 }
2991 return total_bytes;
2992}
2993
2994void
2995CommandInterpreter::IOHandlerInputComplete (IOHandler &io_handler, std::string &line)
2996{
Greg Clayton340b0302014-02-05 17:57:57 +00002997 const bool is_interactive = io_handler.GetIsInteractive();
2998 if (is_interactive == false)
2999 {
3000 // When we are not interactive, don't execute blank lines. This will happen
3001 // sourcing a commands file. We don't want blank lines to repeat the previous
3002 // command and cause any errors to occur (like redefining an alias, get an error
3003 // and stop parsing the commands file).
3004 if (line.empty())
3005 return;
3006
3007 // When using a non-interactive file handle (like when sourcing commands from a file)
3008 // we need to echo the command out so we don't just see the command output and no
3009 // command...
3010 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
3011 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(), line.c_str());
3012 }
3013
Greg Clayton44d93782014-01-27 23:43:24 +00003014 lldb_private::CommandReturnObject result;
3015 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
3016
Greg Clayton44d93782014-01-27 23:43:24 +00003017 // Now emit the command output text from the command we just executed
Greg Clayton340b0302014-02-05 17:57:57 +00003018 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult))
3019 {
3020 // Display any STDOUT/STDERR _prior_ to emitting the command result text
3021 GetProcessOutput ();
3022
Greg Clayton8ee67312014-02-05 21:46:20 +00003023 if (!result.GetImmediateOutputStream())
3024 {
3025 const char *output = result.GetOutputData();
3026 if (output && output[0])
3027 io_handler.GetOutputStreamFile()->PutCString(output);
3028 }
Greg Clayton44d93782014-01-27 23:43:24 +00003029
Greg Clayton340b0302014-02-05 17:57:57 +00003030 // Now emit the command error text from the command we just executed
Greg Clayton8ee67312014-02-05 21:46:20 +00003031 if (!result.GetImmediateErrorStream())
3032 {
3033 const char *error = result.GetErrorData();
3034 if (error && error[0])
3035 io_handler.GetErrorStreamFile()->PutCString(error);
3036 }
Greg Clayton340b0302014-02-05 17:57:57 +00003037 }
Greg Clayton44d93782014-01-27 23:43:24 +00003038
3039 switch (result.GetStatus())
3040 {
3041 case eReturnStatusInvalid:
3042 case eReturnStatusSuccessFinishNoResult:
3043 case eReturnStatusSuccessFinishResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003044 case eReturnStatusStarted:
3045 break;
3046
Greg Clayton44d93782014-01-27 23:43:24 +00003047 case eReturnStatusSuccessContinuingNoResult:
3048 case eReturnStatusSuccessContinuingResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003049 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
3050 io_handler.SetIsDone(true);
3051 break;
3052
Greg Clayton44d93782014-01-27 23:43:24 +00003053 case eReturnStatusFailed:
Greg Clayton340b0302014-02-05 17:57:57 +00003054 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
3055 io_handler.SetIsDone(true);
Greg Clayton44d93782014-01-27 23:43:24 +00003056 break;
3057
3058 case eReturnStatusQuit:
3059 io_handler.SetIsDone(true);
3060 break;
3061 }
3062}
3063
Greg Claytonf0066ad2014-05-02 00:45:31 +00003064bool
3065CommandInterpreter::IOHandlerInterrupt (IOHandler &io_handler)
3066{
3067 ExecutionContext exe_ctx (GetExecutionContext());
3068 Process *process = exe_ctx.GetProcessPtr();
3069
3070 if (process)
3071 {
3072 StateType state = process->GetState();
3073 if (StateIsRunningState(state))
3074 {
3075 process->Halt();
3076 return true; // Don't do any updating when we are running
3077 }
3078 }
3079 return false;
3080}
3081
Greg Clayton44d93782014-01-27 23:43:24 +00003082void
3083CommandInterpreter::GetLLDBCommandsFromIOHandler (const char *prompt,
3084 IOHandlerDelegate &delegate,
3085 bool asynchronously,
3086 void *baton)
3087{
3088 Debugger &debugger = GetDebugger();
3089 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
3090 "lldb", // Name of input reader for history
3091 prompt, // Prompt
3092 true, // Get multiple lines
Greg Claytonf6913cd2014-03-07 00:53:24 +00003093 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003094 delegate)); // IOHandlerDelegate
3095
3096 if (io_handler_sp)
3097 {
3098 io_handler_sp->SetUserData (baton);
3099 if (asynchronously)
3100 debugger.PushIOHandler(io_handler_sp);
3101 else
3102 debugger.RunIOHandler(io_handler_sp);
3103 }
3104
3105}
3106
3107
3108void
3109CommandInterpreter::GetPythonCommandsFromIOHandler (const char *prompt,
3110 IOHandlerDelegate &delegate,
3111 bool asynchronously,
3112 void *baton)
3113{
3114 Debugger &debugger = GetDebugger();
3115 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
3116 "lldb-python", // Name of input reader for history
3117 prompt, // Prompt
3118 true, // Get multiple lines
Greg Claytonf6913cd2014-03-07 00:53:24 +00003119 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003120 delegate)); // IOHandlerDelegate
3121
3122 if (io_handler_sp)
3123 {
3124 io_handler_sp->SetUserData (baton);
3125 if (asynchronously)
3126 debugger.PushIOHandler(io_handler_sp);
3127 else
3128 debugger.RunIOHandler(io_handler_sp);
3129 }
3130
3131}
3132
3133bool
3134CommandInterpreter::IsActive ()
3135{
3136 return m_debugger.IsTopIOHandler (m_command_io_handler_sp);
3137}
3138
3139void
3140CommandInterpreter::RunCommandInterpreter(bool auto_handle_events,
3141 bool spawn_thread)
3142{
3143 const bool multiple_lines = false; // Only get one line at a time
3144 if (!m_command_io_handler_sp)
3145 m_command_io_handler_sp.reset(new IOHandlerEditline (m_debugger,
3146 m_debugger.GetInputFile(),
3147 m_debugger.GetOutputFile(),
3148 m_debugger.GetErrorFile(),
Greg Clayton340b0302014-02-05 17:57:57 +00003149 eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult,
Greg Clayton44d93782014-01-27 23:43:24 +00003150 "lldb",
3151 m_debugger.GetPrompt(),
3152 multiple_lines,
Greg Claytonf6913cd2014-03-07 00:53:24 +00003153 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003154 *this));
3155 m_debugger.PushIOHandler(m_command_io_handler_sp);
3156
3157 if (auto_handle_events)
3158 m_debugger.StartEventHandlerThread();
3159
3160 if (spawn_thread)
3161 {
3162 m_debugger.StartIOHandlerThread();
3163 }
3164 else
3165 {
3166 m_debugger.ExecuteIOHanders();
3167
3168 if (auto_handle_events)
3169 m_debugger.StopEventHandlerThread();
3170 }
3171
3172}
3173