blob: 76261ade3b3ed090cdbfd4a39957ad714782d365 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012#include <string>
Caroline Tice4ab31c92010-10-12 21:57:09 +000013#include <vector>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000014#include <stdlib.h>
15
Greg Clayton4a33d312011-06-23 17:59:56 +000016#include "CommandObjectScript.h"
Peter Collingbourne08405b62011-06-23 20:37:26 +000017#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000018
Eli Friedman3afb70c2010-06-13 02:17:17 +000019#include "../Commands/CommandObjectApropos.h"
20#include "../Commands/CommandObjectArgs.h"
21#include "../Commands/CommandObjectBreakpoint.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000022#include "../Commands/CommandObjectDisassemble.h"
23#include "../Commands/CommandObjectExpression.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000024#include "../Commands/CommandObjectFrame.h"
Greg Clayton44d93782014-01-27 23:43:24 +000025#include "../Commands/CommandObjectGUI.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectHelp.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000027#include "../Commands/CommandObjectLog.h"
28#include "../Commands/CommandObjectMemory.h"
Greg Claytonded470d2011-03-19 01:12:21 +000029#include "../Commands/CommandObjectPlatform.h"
Enrico Granata21dfcd92012-09-28 23:57:51 +000030#include "../Commands/CommandObjectPlugin.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000031#include "../Commands/CommandObjectProcess.h"
32#include "../Commands/CommandObjectQuit.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectRegister.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectSettings.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSource.h"
Jim Inghamebc09c32010-07-07 03:36:20 +000036#include "../Commands/CommandObjectCommands.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000037#include "../Commands/CommandObjectSyntax.h"
38#include "../Commands/CommandObjectTarget.h"
39#include "../Commands/CommandObjectThread.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000040#include "../Commands/CommandObjectType.h"
Johnny Chen31c39da2010-12-23 20:21:44 +000041#include "../Commands/CommandObjectVersion.h"
Johnny Chenf04ee932011-09-22 18:04:58 +000042#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043
Greg Clayton7d2ef162013-03-29 17:03:23 +000044
Chris Lattner30fdc8d2010-06-08 16:52:24 +000045#include "lldb/Core/Debugger.h"
Enrico Granatab5887262012-10-29 21:18:03 +000046#include "lldb/Core/Log.h"
Greg Claytonf0066ad2014-05-02 00:45:31 +000047#include "lldb/Core/State.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048#include "lldb/Core/Stream.h"
Greg Clayton44d93782014-01-27 23:43:24 +000049#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000050#include "lldb/Core/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000051
Greg Clayton44d93782014-01-27 23:43:24 +000052#include "lldb/Host/Editline.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000053#include "lldb/Host/Host.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000054#include "lldb/Host/HostInfo.h"
Enrico Granatab5887262012-10-29 21:18:03 +000055
56#include "lldb/Interpreter/Args.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000057#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000058#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000059#include "lldb/Interpreter/CommandReturnObject.h"
Enrico Granatab5887262012-10-29 21:18:03 +000060#include "lldb/Interpreter/Options.h"
61#include "lldb/Interpreter/ScriptInterpreterNone.h"
62#include "lldb/Interpreter/ScriptInterpreterPython.h"
63
64
Chris Lattner30fdc8d2010-06-08 16:52:24 +000065#include "lldb/Target/Process.h"
66#include "lldb/Target/Thread.h"
67#include "lldb/Target/TargetList.h"
68
Enrico Granatab5887262012-10-29 21:18:03 +000069#include "lldb/Utility/CleanUp.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000070
Zachary Turnera21fee02014-08-21 21:49:24 +000071#include "llvm/ADT/SmallString.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000072#include "llvm/ADT/STLExtras.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000073#include "llvm/Support/Path.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000074
Chris Lattner30fdc8d2010-06-08 16:52:24 +000075using namespace lldb;
76using namespace lldb_private;
77
Greg Clayton754a9362012-08-23 00:22:02 +000078
79static PropertyDefinition
80g_properties[] =
81{
Ed Masted78c9572014-04-20 00:31:37 +000082 { "expand-regex-aliases", OptionValue::eTypeBoolean, true, false, nullptr, nullptr, "If true, regular expression alias commands will show the expanded command that will be executed. This can be used to debug new regular expression alias commands." },
83 { "prompt-on-quit", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, LLDB will prompt you before quitting if there are any live processes being debugged. If false, LLDB will quit without asking in any case." },
84 { "stop-command-source-on-error", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, LLDB will stop running a 'command source' script upon encountering an error." },
85 { nullptr , OptionValue::eTypeInvalid, true, 0 , nullptr, nullptr, nullptr }
Greg Clayton754a9362012-08-23 00:22:02 +000086};
87
88enum
89{
Enrico Granatabcba2b22013-01-17 21:36:19 +000090 ePropertyExpandRegexAliases = 0,
Enrico Granata012d4fc2013-06-11 01:26:35 +000091 ePropertyPromptOnQuit = 1,
92 ePropertyStopCmdSourceOnError = 2
Greg Clayton754a9362012-08-23 00:22:02 +000093};
94
Jim Ingham4bddaeb2012-02-16 06:50:00 +000095ConstString &
96CommandInterpreter::GetStaticBroadcasterClass ()
97{
98 static ConstString class_name ("lldb.commandInterpreter");
99 return class_name;
100}
101
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000102CommandInterpreter::CommandInterpreter
103(
Greg Clayton66111032010-06-23 01:19:29 +0000104 Debugger &debugger,
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000105 ScriptLanguage script_language,
Greg Clayton66111032010-06-23 01:19:29 +0000106 bool synchronous_execution
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000107) :
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000108 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton754a9362012-08-23 00:22:02 +0000109 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton44d93782014-01-27 23:43:24 +0000110 IOHandlerDelegate (IOHandlerDelegate::Completion::LLDBCommand),
Greg Clayton66111032010-06-23 01:19:29 +0000111 m_debugger (debugger),
Greg Clayton6eee5aa2010-10-11 01:05:37 +0000112 m_synchronous_execution (synchronous_execution),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000113 m_skip_lldbinit_files (false),
Jim Ingham16e0c682011-08-12 23:34:31 +0000114 m_skip_app_init_files (false),
Jim Inghame16c50a2011-02-18 00:54:25 +0000115 m_script_interpreter_ap (),
Greg Clayton44d93782014-01-27 23:43:24 +0000116 m_command_io_handler_sp (),
Caroline Ticed61c10b2011-06-16 16:27:19 +0000117 m_comment_char ('#'),
Johnny Chen4ac1d9e2012-08-09 22:06:10 +0000118 m_batch_command_mode (false),
Enrico Granata5f5ab602012-05-31 01:09:06 +0000119 m_truncation_warning(eNoTruncation),
120 m_command_source_depth (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000121{
Greg Clayton67cc0632012-08-22 17:17:09 +0000122 debugger.SetScriptLanguage (script_language);
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000123 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
124 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton67cc0632012-08-22 17:17:09 +0000125 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000126 CheckInWithManager ();
Greg Clayton754a9362012-08-23 00:22:02 +0000127 m_collection_sp->Initialize (g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000128}
129
Greg Clayton754a9362012-08-23 00:22:02 +0000130bool
131CommandInterpreter::GetExpandRegexAliases () const
132{
133 const uint32_t idx = ePropertyExpandRegexAliases;
Ed Masted78c9572014-04-20 00:31:37 +0000134 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000135}
136
Enrico Granatabcba2b22013-01-17 21:36:19 +0000137bool
138CommandInterpreter::GetPromptOnQuit () const
139{
140 const uint32_t idx = ePropertyPromptOnQuit;
Ed Masted78c9572014-04-20 00:31:37 +0000141 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000142}
Greg Clayton754a9362012-08-23 00:22:02 +0000143
Enrico Granata012d4fc2013-06-11 01:26:35 +0000144bool
145CommandInterpreter::GetStopCmdSourceOnError () const
146{
147 const uint32_t idx = ePropertyStopCmdSourceOnError;
Ed Masted78c9572014-04-20 00:31:37 +0000148 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000149}
150
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000151void
152CommandInterpreter::Initialize ()
153{
154 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
155
156 CommandReturnObject result;
157
158 LoadCommandDictionary ();
159
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000160 // Set up some initial aliases.
Caroline Ticeca90c472011-05-06 21:37:15 +0000161 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
162 if (cmd_obj_sp)
163 {
164 AddAlias ("q", cmd_obj_sp);
165 AddAlias ("exit", cmd_obj_sp);
166 }
Sean Callanan247e62a2012-05-04 23:15:02 +0000167
Johnny Chen6d675242012-08-24 18:15:45 +0000168 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callanan247e62a2012-05-04 23:15:02 +0000169 if (cmd_obj_sp)
170 {
171 AddAlias ("attach", cmd_obj_sp);
172 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000173
Johnny Chen6d675242012-08-24 18:15:45 +0000174 cmd_obj_sp = GetCommandSPExact ("process detach",false);
175 if (cmd_obj_sp)
176 {
177 AddAlias ("detach", cmd_obj_sp);
178 }
179
Caroline Ticeca90c472011-05-06 21:37:15 +0000180 cmd_obj_sp = GetCommandSPExact ("process continue", false);
181 if (cmd_obj_sp)
182 {
183 AddAlias ("c", cmd_obj_sp);
184 AddAlias ("continue", cmd_obj_sp);
185 }
186
187 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
188 if (cmd_obj_sp)
189 AddAlias ("b", cmd_obj_sp);
190
Jim Inghamca36cd12012-10-05 19:16:31 +0000191 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
192 if (cmd_obj_sp)
193 AddAlias ("tbreak", cmd_obj_sp);
194
Caroline Ticeca90c472011-05-06 21:37:15 +0000195 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
196 if (cmd_obj_sp)
Jason Molendaf385f122011-10-22 00:47:41 +0000197 {
198 AddAlias ("stepi", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000199 AddAlias ("si", cmd_obj_sp);
Jason Molendaf385f122011-10-22 00:47:41 +0000200 }
201
202 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
203 if (cmd_obj_sp)
204 {
205 AddAlias ("nexti", cmd_obj_sp);
206 AddAlias ("ni", cmd_obj_sp);
207 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000208
209 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
210 if (cmd_obj_sp)
211 {
212 AddAlias ("s", cmd_obj_sp);
213 AddAlias ("step", cmd_obj_sp);
214 }
215
216 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
217 if (cmd_obj_sp)
218 {
219 AddAlias ("n", cmd_obj_sp);
220 AddAlias ("next", cmd_obj_sp);
221 }
222
223 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
224 if (cmd_obj_sp)
225 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000226 AddAlias ("finish", cmd_obj_sp);
227 }
228
Jim Ingham6d6d1072011-12-02 01:12:59 +0000229 cmd_obj_sp = GetCommandSPExact ("frame select", false);
230 if (cmd_obj_sp)
231 {
232 AddAlias ("f", cmd_obj_sp);
233 }
234
Jim Inghamca36cd12012-10-05 19:16:31 +0000235 cmd_obj_sp = GetCommandSPExact ("thread select", false);
236 if (cmd_obj_sp)
237 {
238 AddAlias ("t", cmd_obj_sp);
239 }
240
Richard Mittonf86248d2013-09-12 02:20:34 +0000241 cmd_obj_sp = GetCommandSPExact ("_regexp-jump",false);
242 if (cmd_obj_sp)
243 {
244 AddAlias ("j", cmd_obj_sp);
245 AddAlias ("jump", cmd_obj_sp);
246 }
247
Greg Clayton6bade322013-02-01 23:33:03 +0000248 cmd_obj_sp = GetCommandSPExact ("_regexp-list", false);
Caroline Ticeca90c472011-05-06 21:37:15 +0000249 if (cmd_obj_sp)
250 {
251 AddAlias ("l", cmd_obj_sp);
252 AddAlias ("list", cmd_obj_sp);
253 }
254
Greg Claytonef5651d2013-02-12 18:52:24 +0000255 cmd_obj_sp = GetCommandSPExact ("_regexp-env", false);
256 if (cmd_obj_sp)
257 {
258 AddAlias ("env", cmd_obj_sp);
259 }
260
Caroline Ticeca90c472011-05-06 21:37:15 +0000261 cmd_obj_sp = GetCommandSPExact ("memory read", false);
262 if (cmd_obj_sp)
263 AddAlias ("x", cmd_obj_sp);
264
265 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
266 if (cmd_obj_sp)
267 AddAlias ("up", cmd_obj_sp);
268
269 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
270 if (cmd_obj_sp)
271 AddAlias ("down", cmd_obj_sp);
272
Jason Molenda0c8e0062011-10-25 02:11:20 +0000273 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000274 if (cmd_obj_sp)
275 AddAlias ("display", cmd_obj_sp);
Jim Ingham7e18e422011-10-24 18:37:00 +0000276
277 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
278 if (cmd_obj_sp)
279 AddAlias ("dis", cmd_obj_sp);
280
281 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
282 if (cmd_obj_sp)
283 AddAlias ("di", cmd_obj_sp);
284
285
Jason Molendabc7748b2011-10-22 01:30:52 +0000286
Jason Molenda0c8e0062011-10-25 02:11:20 +0000287 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000288 if (cmd_obj_sp)
289 AddAlias ("undisplay", cmd_obj_sp);
290
Jim Ingham71bf2992012-10-10 16:51:31 +0000291 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
292 if (cmd_obj_sp)
293 AddAlias ("bt", cmd_obj_sp);
294
Caroline Ticeca90c472011-05-06 21:37:15 +0000295 cmd_obj_sp = GetCommandSPExact ("target create", false);
296 if (cmd_obj_sp)
297 AddAlias ("file", cmd_obj_sp);
298
299 cmd_obj_sp = GetCommandSPExact ("target modules", false);
300 if (cmd_obj_sp)
301 AddAlias ("image", cmd_obj_sp);
302
303
304 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghamffba2292011-03-22 02:29:32 +0000305
Caroline Ticeca90c472011-05-06 21:37:15 +0000306 cmd_obj_sp = GetCommandSPExact ("expression", false);
307 if (cmd_obj_sp)
Sean Callanan90e579f2013-04-17 17:23:58 +0000308 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000309 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
310 AddAlias ("p", cmd_obj_sp);
311 AddAlias ("print", cmd_obj_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000312 AddAlias ("call", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000313 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
314 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000315 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000316
317 alias_arguments_vector_sp.reset (new OptionArgVector);
Greg Clayton9e57dcd2013-05-15 01:03:08 +0000318 ProcessAliasOptionsArgs (cmd_obj_sp, "-O -- ", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000319 AddAlias ("po", cmd_obj_sp);
320 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
321 }
322
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000323 cmd_obj_sp = GetCommandSPExact ("process kill", false);
324 if (cmd_obj_sp)
Greg Claytone86fd742012-09-27 00:02:27 +0000325 {
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000326 AddAlias ("kill", cmd_obj_sp);
Greg Claytone86fd742012-09-27 00:02:27 +0000327 }
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000328
Caroline Ticeca90c472011-05-06 21:37:15 +0000329 cmd_obj_sp = GetCommandSPExact ("process launch", false);
330 if (cmd_obj_sp)
331 {
332 alias_arguments_vector_sp.reset (new OptionArgVector);
Todd Fiala013434e2014-07-09 01:29:05 +0000333#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Jason Molenda85da3122012-07-06 02:46:23 +0000334 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
335#else
Ed Maste7c566672013-09-05 21:38:45 +0000336 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=" LLDB_DEFAULT_SHELL " --", alias_arguments_vector_sp);
Jason Molenda85da3122012-07-06 02:46:23 +0000337#endif
Caroline Ticeca90c472011-05-06 21:37:15 +0000338 AddAlias ("r", cmd_obj_sp);
339 AddAlias ("run", cmd_obj_sp);
340 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
341 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
342 }
Greg Clayton843d62d2012-03-29 21:47:51 +0000343
344 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
345 if (cmd_obj_sp)
346 {
347 AddAlias ("add-dsym", cmd_obj_sp);
348 }
Sean Callananfc732752012-05-21 18:25:19 +0000349
350 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
351 if (cmd_obj_sp)
352 {
353 alias_arguments_vector_sp.reset (new OptionArgVector);
354 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
Jim Ingham06d282d2012-10-18 23:24:12 +0000355 AddAlias ("rbreak", cmd_obj_sp);
356 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
Sean Callananfc732752012-05-21 18:25:19 +0000357 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000358}
359
Greg Clayton0c4129f2014-04-25 00:35:14 +0000360void
361CommandInterpreter::Clear()
362{
363 m_command_io_handler_sp.reset();
Greg Claytoned6499f2014-04-25 23:55:12 +0000364
365 if (m_script_interpreter_ap)
366 m_script_interpreter_ap->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000367}
368
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000369const char *
370CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
371{
372 // This function has not yet been implemented.
373
374 // Look for any embedded script command
375 // If found,
376 // get interpreter object from the command dictionary,
377 // call execute_one_command on it,
378 // get the results as a string,
379 // substitute that string for current stuff.
380
381 return arg;
382}
383
384
385void
386CommandInterpreter::LoadCommandDictionary ()
387{
388 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
389
Caroline Ticedaccaa92010-09-20 20:44:43 +0000390 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000391
Greg Claytona7015092010-09-18 01:14:36 +0000392 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000393 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Johnny Chenb89982d2011-04-21 00:39:18 +0000394 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000395 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
396 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000397 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton44d93782014-01-27 23:43:24 +0000398 m_command_dict["gui"] = CommandObjectSP (new CommandObjectGUI (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000399 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000400 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
401 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonded470d2011-03-19 01:12:21 +0000402 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata21dfcd92012-09-28 23:57:51 +0000403 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000404 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000405 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000406 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000407 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000408 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Inghamebc09c32010-07-07 03:36:20 +0000409 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000410 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
411 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata223383e2011-08-16 23:24:13 +0000412 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen31c39da2010-12-23 20:21:44 +0000413 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chenf04ee932011-09-22 18:04:58 +0000414 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000415
Jim Inghamca36cd12012-10-05 19:16:31 +0000416 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
417 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
Greg Clayton722e8852013-02-08 02:54:24 +0000418 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
Greg Clayton1b3815c2013-01-30 00:18:29 +0000419 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000420 {"^(-.*)$", "breakpoint set %1"},
421 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
Greg Clayton722e8852013-02-08 02:54:24 +0000422 {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"},
Greg Clayton2d4b5122014-08-14 17:58:33 +0000423 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"}};
Jim Inghamca36cd12012-10-05 19:16:31 +0000424
Saleem Abdulrasool28606952014-06-27 05:17:41 +0000425 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000426
Greg Clayton7b0992d2013-04-18 22:45:39 +0000427 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytona7015092010-09-18 01:14:36 +0000428 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000429 "_regexp-break",
Johnny Chenb417dcd2012-08-23 00:32:22 +0000430 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000431 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
432 2,
433 CommandCompletions::eSymbolCompletion |
434 CommandCompletions::eSourceFileCompletion));
Jim Inghamca36cd12012-10-05 19:16:31 +0000435
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000436 if (break_regex_cmd_ap.get())
437 {
Jim Inghamca36cd12012-10-05 19:16:31 +0000438 bool success = true;
439 for (size_t i = 0; i < num_regexes; i++)
440 {
441 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
442 if (!success)
443 break;
444 }
445 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
446
447 if (success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000448 {
449 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
450 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
451 }
452 }
Jim Inghamffba2292011-03-22 02:29:32 +0000453
Greg Clayton7b0992d2013-04-18 22:45:39 +0000454 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamca36cd12012-10-05 19:16:31 +0000455 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
456 "_regexp-tbreak",
457 "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000458 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
459 2,
460 CommandCompletions::eSymbolCompletion |
461 CommandCompletions::eSourceFileCompletion));
Jim Inghamca36cd12012-10-05 19:16:31 +0000462
463 if (tbreak_regex_cmd_ap.get())
464 {
465 bool success = true;
466 for (size_t i = 0; i < num_regexes; i++)
467 {
468 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
469 char buffer[1024];
470 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
471 assert (num_printed < 1024);
Eric Christopher5c91d5c12014-09-09 19:26:45 +0000472 // Quiet unused variable warning for release builds.
Eric Christopher9ad83942014-09-09 08:57:33 +0000473 (void) num_printed;
Jim Inghamca36cd12012-10-05 19:16:31 +0000474 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
475 if (!success)
476 break;
477 }
478 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
479
480 if (success)
481 {
482 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
483 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
484 }
485 }
486
Greg Clayton7b0992d2013-04-18 22:45:39 +0000487 std::unique_ptr<CommandObjectRegexCommand>
Johnny Chen6d675242012-08-24 18:15:45 +0000488 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
489 "_regexp-attach",
490 "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 +0000491 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]",
492 2));
Johnny Chen6d675242012-08-24 18:15:45 +0000493 if (attach_regex_cmd_ap.get())
494 {
Greg Clayton3cb4c7d2012-12-15 01:19:07 +0000495 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
496 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
497 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
498 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
Johnny Chen6d675242012-08-24 18:15:45 +0000499 {
500 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
501 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
502 }
503 }
504
Greg Clayton7b0992d2013-04-18 22:45:39 +0000505 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000506 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000507 "_regexp-down",
508 "Go down \"n\" frames in the stack (1 frame by default).",
509 "_regexp-down [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000510 if (down_regex_cmd_ap.get())
511 {
512 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
513 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
514 {
515 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
516 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
517 }
518 }
519
Greg Clayton7b0992d2013-04-18 22:45:39 +0000520 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000521 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000522 "_regexp-up",
523 "Go up \"n\" frames in the stack (1 frame by default).",
524 "_regexp-up [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000525 if (up_regex_cmd_ap.get())
526 {
527 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
528 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
529 {
530 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
531 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
532 }
533 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000534
Greg Clayton7b0992d2013-04-18 22:45:39 +0000535 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000536 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000537 "_regexp-display",
538 "Add an expression evaluation stop-hook.",
539 "_regexp-display expression", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000540 if (display_regex_cmd_ap.get())
541 {
542 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
543 {
544 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
545 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
546 }
547 }
548
Greg Clayton7b0992d2013-04-18 22:45:39 +0000549 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000550 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000551 "_regexp-undisplay",
552 "Remove an expression evaluation stop-hook.",
553 "_regexp-undisplay stop-hook-number", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000554 if (undisplay_regex_cmd_ap.get())
555 {
556 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
557 {
558 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
559 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
560 }
561 }
562
Greg Clayton7b0992d2013-04-18 22:45:39 +0000563 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000564 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000565 "gdb-remote",
566 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
567 "gdb-remote [<hostname>:]<portnum>", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000568 if (connect_gdb_remote_cmd_ap.get())
569 {
570 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
571 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
572 {
573 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
574 m_command_dict[command_sp->GetCommandName ()] = command_sp;
575 }
576 }
577
Greg Clayton7b0992d2013-04-18 22:45:39 +0000578 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000579 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
580 "kdp-remote",
Jason Molendaa7dcb332012-10-23 03:05:16 +0000581 "Connect to a remote KDP server. udp port 41139 is the default port number.",
582 "kdp-remote <hostname>[:<portnum>]", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000583 if (connect_kdp_remote_cmd_ap.get())
584 {
585 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molendac36b1842012-09-27 02:47:55 +0000586 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000587 {
588 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
589 m_command_dict[command_sp->GetCommandName ()] = command_sp;
590 }
591 }
592
Greg Clayton7b0992d2013-04-18 22:45:39 +0000593 std::unique_ptr<CommandObjectRegexCommand>
Jason Molenda4cddfed2012-10-05 05:29:32 +0000594 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jim Ingham71bf2992012-10-10 16:51:31 +0000595 "_regexp-bt",
Jason Molenda4cddfed2012-10-05 05:29:32 +0000596 "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.",
597 "bt [<digit>|all]", 2));
598 if (bt_regex_cmd_ap.get())
599 {
600 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
601 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
602 // so now "bt 3" is the preferred form, in line with gdb.
603 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
604 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
605 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
606 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
607 {
608 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
609 m_command_dict[command_sp->GetCommandName ()] = command_sp;
610 }
611 }
612
Greg Clayton7b0992d2013-04-18 22:45:39 +0000613 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton6bade322013-02-01 23:33:03 +0000614 list_regex_cmd_ap(new CommandObjectRegexCommand (*this,
615 "_regexp-list",
616 "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 +0000617 "_regexp-list [<line>]\n_regexp-list [<file>:<line>]\n_regexp-list [<file>:<line>]",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000618 2,
619 CommandCompletions::eSourceFileCompletion));
Greg Clayton6bade322013-02-01 23:33:03 +0000620 if (list_regex_cmd_ap.get())
621 {
622 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") &&
623 list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") &&
624 list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") &&
Greg Claytond9010962013-02-12 18:42:05 +0000625 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") &&
Greg Claytone4ca5152013-03-13 18:25:49 +0000626 list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") &&
Greg Clayton6bade322013-02-01 23:33:03 +0000627 list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") &&
628 list_regex_cmd_ap->AddRegexCommand("^$", "source list"))
629 {
630 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
631 m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp;
632 }
633 }
634
Greg Clayton7b0992d2013-04-18 22:45:39 +0000635 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytonef5651d2013-02-12 18:52:24 +0000636 env_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000637 "_regexp-env",
638 "Implements a shortcut to viewing and setting environment variables.",
639 "_regexp-env\n_regexp-env FOO=BAR", 2));
Greg Claytonef5651d2013-02-12 18:52:24 +0000640 if (env_regex_cmd_ap.get())
641 {
642 if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") &&
643 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1"))
644 {
645 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
646 m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp;
647 }
648 }
649
Richard Mittonf86248d2013-09-12 02:20:34 +0000650 std::unique_ptr<CommandObjectRegexCommand>
651 jump_regex_cmd_ap(new CommandObjectRegexCommand (*this,
652 "_regexp-jump",
653 "Sets the program counter to a new address.",
654 "_regexp-jump [<line>]\n"
655 "_regexp-jump [<+-lineoffset>]\n"
656 "_regexp-jump [<file>:<line>]\n"
657 "_regexp-jump [*<addr>]\n", 2));
658 if (jump_regex_cmd_ap.get())
659 {
660 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") &&
661 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") &&
662 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") &&
663 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1"))
664 {
665 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
666 m_command_dict[jump_regex_cmd_sp->GetCommandName ()] = jump_regex_cmd_sp;
667 }
668 }
669
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000670}
671
672int
673CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
674 StringList &matches)
675{
676 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
677
678 if (include_aliases)
679 {
680 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
681 }
682
683 return matches.GetSize();
684}
685
686CommandObjectSP
687CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
688{
689 CommandObject::CommandMap::iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +0000690 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000691
692 std::string cmd(cmd_cstr);
693
694 if (HasCommands())
695 {
696 pos = m_command_dict.find(cmd);
697 if (pos != m_command_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000698 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000699 }
700
701 if (include_aliases && HasAliases())
702 {
703 pos = m_alias_dict.find(cmd);
704 if (pos != m_alias_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000705 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000706 }
707
708 if (HasUserCommands())
709 {
710 pos = m_user_dict.find(cmd);
711 if (pos != m_user_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000712 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000713 }
714
Greg Claytonc7bece562013-01-25 18:06:21 +0000715 if (!exact && !command_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000716 {
Jim Ingham279a6c22010-07-06 22:46:59 +0000717 // We will only get into here if we didn't find any exact matches.
718
719 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
720
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000721 StringList local_matches;
Ed Masted78c9572014-04-20 00:31:37 +0000722 if (matches == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000723 matches = &local_matches;
724
Jim Ingham279a6c22010-07-06 22:46:59 +0000725 unsigned int num_cmd_matches = 0;
726 unsigned int num_alias_matches = 0;
727 unsigned int num_user_matches = 0;
728
729 // Look through the command dictionaries one by one, and if we get only one match from any of
730 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
731
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000732 if (HasCommands())
733 {
734 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
735 }
736
737 if (num_cmd_matches == 1)
738 {
739 cmd.assign(matches->GetStringAtIndex(0));
740 pos = m_command_dict.find(cmd);
741 if (pos != m_command_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000742 real_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000743 }
744
Jim Ingham490ac552010-06-24 20:28:42 +0000745 if (include_aliases && HasAliases())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000746 {
747 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
748
749 }
750
Jim Ingham279a6c22010-07-06 22:46:59 +0000751 if (num_alias_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000752 {
753 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
754 pos = m_alias_dict.find(cmd);
755 if (pos != m_alias_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000756 alias_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000757 }
758
Jim Ingham490ac552010-06-24 20:28:42 +0000759 if (HasUserCommands())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000760 {
761 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
762 }
763
Jim Ingham279a6c22010-07-06 22:46:59 +0000764 if (num_user_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000765 {
766 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
767
768 pos = m_user_dict.find (cmd);
769 if (pos != m_user_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000770 user_match_sp = pos->second;
771 }
772
773 // If we got exactly one match, return that, otherwise return the match list.
774
775 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
776 {
777 if (num_cmd_matches)
778 return real_match_sp;
779 else if (num_alias_matches)
780 return alias_match_sp;
781 else
782 return user_match_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000783 }
784 }
Greg Claytonc7bece562013-01-25 18:06:21 +0000785 else if (matches && command_sp)
Jim Ingham279a6c22010-07-06 22:46:59 +0000786 {
787 matches->AppendString (cmd_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000788 }
789
790
Greg Claytonc7bece562013-01-25 18:06:21 +0000791 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000792}
793
Greg Claytonde164aa2011-04-20 16:37:46 +0000794bool
795CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
796{
797 if (name && name[0])
798 {
799 std::string name_sstr(name);
Enrico Granatae00af802012-10-01 17:19:37 +0000800 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
801 if (found && !can_replace)
802 return false;
803 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata21dfcd92012-09-28 23:57:51 +0000804 return false;
Greg Claytonde164aa2011-04-20 16:37:46 +0000805 m_command_dict[name_sstr] = cmd_sp;
806 return true;
807 }
808 return false;
809}
810
Enrico Granata223383e2011-08-16 23:24:13 +0000811bool
Enrico Granata0a305db2011-11-07 22:57:04 +0000812CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata223383e2011-08-16 23:24:13 +0000813 const lldb::CommandObjectSP &cmd_sp,
814 bool can_replace)
815{
Enrico Granata0a305db2011-11-07 22:57:04 +0000816 if (!name.empty())
Enrico Granata223383e2011-08-16 23:24:13 +0000817 {
Enrico Granata0a305db2011-11-07 22:57:04 +0000818
819 const char* name_cstr = name.c_str();
820
821 // do not allow replacement of internal commands
822 if (CommandExists(name_cstr))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000823 {
824 if (can_replace == false)
825 return false;
826 if (m_command_dict[name]->IsRemovable() == false)
827 return false;
828 }
Enrico Granata0a305db2011-11-07 22:57:04 +0000829
Enrico Granata21dfcd92012-09-28 23:57:51 +0000830 if (UserCommandExists(name_cstr))
831 {
832 if (can_replace == false)
833 return false;
834 if (m_user_dict[name]->IsRemovable() == false)
835 return false;
836 }
837
Enrico Granata0a305db2011-11-07 22:57:04 +0000838 m_user_dict[name] = cmd_sp;
Enrico Granata223383e2011-08-16 23:24:13 +0000839 return true;
840 }
841 return false;
842}
Greg Claytonde164aa2011-04-20 16:37:46 +0000843
Jim Ingham279a6c22010-07-06 22:46:59 +0000844CommandObjectSP
845CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000846{
Caroline Tice472362e2010-12-14 18:51:39 +0000847 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
848 CommandObjectSP ret_val; // Possibly empty return value.
849
Ed Masted78c9572014-04-20 00:31:37 +0000850 if (cmd_cstr == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000851 return ret_val;
852
853 if (cmd_words.GetArgumentCount() == 1)
Ed Masted78c9572014-04-20 00:31:37 +0000854 return GetCommandSP(cmd_cstr, include_aliases, true, nullptr);
Caroline Tice472362e2010-12-14 18:51:39 +0000855 else
856 {
857 // We have a multi-word command (seemingly), so we need to do more work.
858 // First, get the cmd_obj_sp for the first word in the command.
Ed Masted78c9572014-04-20 00:31:37 +0000859 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, nullptr);
860 if (cmd_obj_sp.get() != nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000861 {
862 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
863 // command name), and find the appropriate sub-command SP for each command word....
864 size_t end = cmd_words.GetArgumentCount();
865 for (size_t j= 1; j < end; ++j)
866 {
867 if (cmd_obj_sp->IsMultiwordObject())
868 {
Greg Clayton998255b2012-10-13 02:07:45 +0000869 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Ed Masted78c9572014-04-20 00:31:37 +0000870 if (cmd_obj_sp.get() == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000871 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
872 return ret_val;
873 }
874 else
875 // We have more words in the command name, but we don't have a multiword object. Fail and return
876 // empty 'ret_val'.
877 return ret_val;
878 }
879 // We successfully looped through all the command words and got valid command objects for them. Assign the
880 // last object retrieved to 'ret_val'.
881 ret_val = cmd_obj_sp;
882 }
883 }
884 return ret_val;
Jim Ingham279a6c22010-07-06 22:46:59 +0000885}
886
887CommandObject *
888CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
889{
890 return GetCommandSPExact (cmd_cstr, include_aliases).get();
891}
892
893CommandObject *
894CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
895{
896 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
897
898 // If we didn't find an exact match to the command string in the commands, look in
899 // the aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000900
901 if (command_obj)
902 return command_obj;
Jim Ingham279a6c22010-07-06 22:46:59 +0000903
Enrico Granata5342c442013-06-18 18:01:08 +0000904 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
Jim Ingham279a6c22010-07-06 22:46:59 +0000905
Enrico Granata5342c442013-06-18 18:01:08 +0000906 if (command_obj)
907 return command_obj;
908
909 // If there wasn't an exact match then look for an inexact one in just the commands
Ed Masted78c9572014-04-20 00:31:37 +0000910 command_obj = GetCommandSP(cmd_cstr, false, false, nullptr).get();
Matt Kopec038ff812013-04-23 16:17:32 +0000911
912 // Finally, if there wasn't an inexact match among the commands, look for an inexact
913 // match in both the commands and aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000914
915 if (command_obj)
916 {
917 if (matches)
918 matches->AppendString(command_obj->GetCommandName());
919 return command_obj;
920 }
921
922 return GetCommandSP(cmd_cstr, true, false, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000923}
924
925bool
926CommandInterpreter::CommandExists (const char *cmd)
927{
928 return m_command_dict.find(cmd) != m_command_dict.end();
929}
930
931bool
Caroline Ticeca90c472011-05-06 21:37:15 +0000932CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
933 const char *options_args,
934 OptionArgVectorSP &option_arg_vector_sp)
935{
936 bool success = true;
937 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
938
939 if (!options_args || (strlen (options_args) < 1))
940 return true;
941
942 std::string options_string (options_args);
943 Args args (options_args);
944 CommandReturnObject result;
945 // Check to see if the command being aliased can take any command options.
946 Options *options = cmd_obj_sp->GetOptions ();
947 if (options)
948 {
949 // See if any options were specified as part of the alias; if so, handle them appropriately.
950 options->NotifyOptionParsingStarting ();
951 args.Unshift ("dummy_arg");
952 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
953 args.Shift ();
954 if (result.Succeeded())
955 options->VerifyPartialOptions (result);
956 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
957 {
958 result.AppendError ("Unable to create requested alias.\n");
959 return false;
960 }
961 }
962
Greg Clayton5521f992011-10-28 21:38:01 +0000963 if (!options_string.empty())
Caroline Ticeca90c472011-05-06 21:37:15 +0000964 {
965 if (cmd_obj_sp->WantsRawCommandString ())
966 option_arg_vector->push_back (OptionArgPair ("<argument>",
967 OptionArgValue (-1,
968 options_string)));
969 else
970 {
Greg Claytonc7bece562013-01-25 18:06:21 +0000971 const size_t argc = args.GetArgumentCount();
Caroline Ticeca90c472011-05-06 21:37:15 +0000972 for (size_t i = 0; i < argc; ++i)
973 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
974 option_arg_vector->push_back
975 (OptionArgPair ("<argument>",
976 OptionArgValue (-1,
977 std::string (args.GetArgumentAtIndex (i)))));
978 }
979 }
980
981 return success;
982}
983
984bool
Jim Ingham298f3782013-04-03 00:25:49 +0000985CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name)
986{
987 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
988 if (exact_match)
989 {
990 full_name.assign(cmd);
991 return exact_match;
992 }
993 else
994 {
995 StringList matches;
996 size_t num_alias_matches;
997 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches);
998 if (num_alias_matches == 1)
999 {
1000 // Make sure this isn't shadowing a command in the regular command space:
1001 StringList regular_matches;
1002 const bool include_aliases = false;
1003 const bool exact = false;
1004 CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, &regular_matches));
1005 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1006 return false;
1007 else
1008 {
1009 full_name.assign (matches.GetStringAtIndex(0));
1010 return true;
1011 }
1012 }
1013 else
1014 return false;
1015 }
1016}
1017
1018bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001019CommandInterpreter::AliasExists (const char *cmd)
1020{
1021 return m_alias_dict.find(cmd) != m_alias_dict.end();
1022}
1023
1024bool
1025CommandInterpreter::UserCommandExists (const char *cmd)
1026{
1027 return m_user_dict.find(cmd) != m_user_dict.end();
1028}
1029
1030void
1031CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
1032{
Jim Ingham279a6c22010-07-06 22:46:59 +00001033 command_obj_sp->SetIsAlias (true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001034 m_alias_dict[alias_name] = command_obj_sp;
1035}
1036
1037bool
1038CommandInterpreter::RemoveAlias (const char *alias_name)
1039{
1040 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
1041 if (pos != m_alias_dict.end())
1042 {
1043 m_alias_dict.erase(pos);
1044 return true;
1045 }
1046 return false;
1047}
1048bool
1049CommandInterpreter::RemoveUser (const char *alias_name)
1050{
1051 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1052 if (pos != m_user_dict.end())
1053 {
1054 m_user_dict.erase(pos);
1055 return true;
1056 }
1057 return false;
1058}
1059
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001060void
1061CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
1062{
1063 help_string.Printf ("'%s", command_name);
1064 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1065
Sean Callanan9a028512012-08-09 00:50:26 +00001066 if (option_arg_vector_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001067 {
1068 OptionArgVector *options = option_arg_vector_sp.get();
Andy Gibbsa297a972013-06-19 19:04:53 +00001069 for (size_t i = 0; i < options->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070 {
1071 OptionArgPair cur_option = (*options)[i];
1072 std::string opt = cur_option.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00001073 OptionArgValue value_pair = cur_option.second;
1074 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001075 if (opt.compare("<argument>") == 0)
1076 {
1077 help_string.Printf (" %s", value.c_str());
1078 }
1079 else
1080 {
1081 help_string.Printf (" %s", opt.c_str());
1082 if ((value.compare ("<no-argument>") != 0)
1083 && (value.compare ("<need-argument") != 0))
1084 {
1085 help_string.Printf (" %s", value.c_str());
1086 }
1087 }
1088 }
1089 }
1090
1091 help_string.Printf ("'");
1092}
1093
Greg Clayton12fc3e02010-08-26 22:05:43 +00001094size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001095CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
1096{
1097 CommandObject::CommandMap::const_iterator pos;
Greg Clayton12fc3e02010-08-26 22:05:43 +00001098 CommandObject::CommandMap::const_iterator end = dict.end();
1099 size_t max_len = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001100
Greg Clayton12fc3e02010-08-26 22:05:43 +00001101 for (pos = dict.begin(); pos != end; ++pos)
1102 {
1103 size_t len = pos->first.size();
1104 if (max_len < len)
1105 max_len = len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001106 }
Greg Clayton12fc3e02010-08-26 22:05:43 +00001107 return max_len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001108}
1109
1110void
Enrico Granata223383e2011-08-16 23:24:13 +00001111CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata08633ee2011-09-09 17:49:36 +00001112 uint32_t cmd_types)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001113{
1114 CommandObject::CommandMap::const_iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +00001115 size_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata223383e2011-08-16 23:24:13 +00001116
1117 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001118 {
Enrico Granata223383e2011-08-16 23:24:13 +00001119
1120 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
1121 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001122
Enrico Granata223383e2011-08-16 23:24:13 +00001123 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1124 {
1125 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1126 max_len);
1127 }
1128 result.AppendMessage("");
1129
1130 }
1131
Greg Clayton5521f992011-10-28 21:38:01 +00001132 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001133 {
Jim Ingham49e80a12010-10-22 18:47:16 +00001134 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chenb89982d2011-04-21 00:39:18 +00001135 "(see 'help command alias' for more info):");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001136 result.AppendMessage("");
Greg Clayton12fc3e02010-08-26 22:05:43 +00001137 max_len = FindLongestCommandWord (m_alias_dict);
1138
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001139 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1140 {
1141 StreamString sstr;
1142 StreamString translation_and_help;
1143 std::string entry_name = pos->first;
1144 std::string second_entry = pos->second.get()->GetCommandName();
1145 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1146
1147 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1148 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1149 translation_and_help.GetData(), max_len);
1150 }
1151 result.AppendMessage("");
1152 }
1153
Greg Clayton5521f992011-10-28 21:38:01 +00001154 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001155 {
1156 result.AppendMessage ("The following is a list of your current user-defined commands:");
1157 result.AppendMessage("");
Enrico Granata223383e2011-08-16 23:24:13 +00001158 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001159 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1160 {
Enrico Granata223383e2011-08-16 23:24:13 +00001161 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1162 max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001163 }
1164 result.AppendMessage("");
1165 }
1166
1167 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1168}
1169
Caroline Tice844d2302010-12-09 22:52:49 +00001170CommandObject *
1171CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001172{
Caroline Tice844d2302010-12-09 22:52:49 +00001173 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1174 // eventually be invoked by the given command line.
1175
Ed Masted78c9572014-04-20 00:31:37 +00001176 CommandObject *cmd_obj = nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001177 std::string white_space (" \t\v");
1178 size_t start = command_string.find_first_not_of (white_space);
1179 size_t end = 0;
1180 bool done = false;
1181 while (!done)
1182 {
1183 if (start != std::string::npos)
1184 {
1185 // Get the next word from command_string.
1186 end = command_string.find_first_of (white_space, start);
1187 if (end == std::string::npos)
1188 end = command_string.size();
1189 std::string cmd_word = command_string.substr (start, end - start);
1190
Ed Masted78c9572014-04-20 00:31:37 +00001191 if (cmd_obj == nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001192 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1193 // command or alias.
1194 cmd_obj = GetCommandObject (cmd_word.c_str());
1195 else if (cmd_obj->IsMultiwordObject ())
1196 {
1197 // 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 +00001198 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001199 if (sub_cmd_obj)
1200 cmd_obj = sub_cmd_obj;
1201 else // cmd_word was not a valid sub-command word, so we are donee
1202 done = true;
1203 }
1204 else
1205 // We have a cmd_obj and it is not a multi-word object, so we are done.
1206 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001207
Caroline Tice844d2302010-12-09 22:52:49 +00001208 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1209 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1210 // next word.
1211
1212 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1213 done = true;
1214 else
1215 start = command_string.find_first_not_of (white_space, end);
1216 }
1217 else
1218 // Unable to find any more words.
1219 done = true;
1220 }
1221
1222 if (end == command_string.size())
1223 command_string.clear();
1224 else
1225 command_string = command_string.substr(end);
1226
1227 return cmd_obj;
1228}
1229
Greg Clayton51964162011-10-25 00:36:27 +00001230static const char *k_white_space = " \t\v";
Greg Clayton5521f992011-10-28 21:38:01 +00001231static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton51964162011-10-25 00:36:27 +00001232static void
1233StripLeadingSpaces (std::string &s)
Caroline Tice844d2302010-12-09 22:52:49 +00001234{
Greg Clayton51964162011-10-25 00:36:27 +00001235 if (!s.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001236 {
Greg Clayton51964162011-10-25 00:36:27 +00001237 size_t pos = s.find_first_not_of (k_white_space);
1238 if (pos == std::string::npos)
1239 s.clear();
1240 else if (pos == 0)
1241 return;
1242 s.erase (0, pos);
1243 }
1244}
1245
Greg Clayton93c62e62011-11-09 23:25:03 +00001246static size_t
1247FindArgumentTerminator (const std::string &s)
1248{
Greg Clayton93c62e62011-11-09 23:25:03 +00001249 const size_t s_len = s.size();
1250 size_t offset = 0;
1251 while (offset < s_len)
1252 {
1253 size_t pos = s.find ("--", offset);
1254 if (pos == std::string::npos)
1255 break;
1256 if (pos > 0)
1257 {
1258 if (isspace(s[pos-1]))
1259 {
1260 // Check if the string ends "\s--" (where \s is a space character)
1261 // or if we have "\s--\s".
1262 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1263 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001264 return pos;
1265 }
1266 }
1267 }
1268 offset = pos + 2;
1269 }
Greg Clayton93c62e62011-11-09 23:25:03 +00001270 return std::string::npos;
1271}
1272
Greg Clayton51964162011-10-25 00:36:27 +00001273static bool
Greg Clayton5521f992011-10-28 21:38:01 +00001274ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton51964162011-10-25 00:36:27 +00001275{
Greg Clayton5521f992011-10-28 21:38:01 +00001276 command.clear();
1277 suffix.clear();
Greg Clayton51964162011-10-25 00:36:27 +00001278 StripLeadingSpaces (command_string);
1279
1280 bool result = false;
1281 quote_char = '\0';
1282
1283 if (!command_string.empty())
1284 {
1285 const char first_char = command_string[0];
1286 if (first_char == '\'' || first_char == '"')
Caroline Tice844d2302010-12-09 22:52:49 +00001287 {
Greg Clayton51964162011-10-25 00:36:27 +00001288 quote_char = first_char;
1289 const size_t end_quote_pos = command_string.find (quote_char, 1);
1290 if (end_quote_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001291 {
Greg Clayton5521f992011-10-28 21:38:01 +00001292 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001293 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001294 }
1295 else
1296 {
Greg Clayton5521f992011-10-28 21:38:01 +00001297 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton51964162011-10-25 00:36:27 +00001298 if (end_quote_pos + 1 < command_string.size())
1299 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1300 else
1301 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001302 }
Caroline Tice844d2302010-12-09 22:52:49 +00001303 }
1304 else
1305 {
Greg Clayton51964162011-10-25 00:36:27 +00001306 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1307 if (first_space_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001308 {
Greg Clayton5521f992011-10-28 21:38:01 +00001309 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001310 command_string.erase();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001311 }
1312 else
1313 {
Greg Clayton5521f992011-10-28 21:38:01 +00001314 command.assign (command_string, 0, first_space_pos);
1315 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice2b5e8502011-05-11 16:07:06 +00001316 }
Caroline Tice844d2302010-12-09 22:52:49 +00001317 }
Greg Clayton51964162011-10-25 00:36:27 +00001318 result = true;
Caroline Tice844d2302010-12-09 22:52:49 +00001319 }
Greg Clayton5521f992011-10-28 21:38:01 +00001320
1321
1322 if (!command.empty())
1323 {
1324 // actual commands can't start with '-' or '_'
1325 if (command[0] != '-' && command[0] != '_')
1326 {
1327 size_t pos = command.find_first_not_of(k_valid_command_chars);
1328 if (pos > 0 && pos != std::string::npos)
1329 {
1330 suffix.assign (command.begin() + pos, command.end());
1331 command.erase (pos);
1332 }
1333 }
1334 }
Greg Clayton51964162011-10-25 00:36:27 +00001335
1336 return result;
Caroline Tice844d2302010-12-09 22:52:49 +00001337}
1338
Greg Clayton5521f992011-10-28 21:38:01 +00001339CommandObject *
1340CommandInterpreter::BuildAliasResult (const char *alias_name,
1341 std::string &raw_input_string,
1342 std::string &alias_result,
1343 CommandReturnObject &result)
Caroline Tice844d2302010-12-09 22:52:49 +00001344{
Ed Masted78c9572014-04-20 00:31:37 +00001345 CommandObject *alias_cmd_obj = nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001346 Args cmd_args (raw_input_string.c_str());
1347 alias_cmd_obj = GetCommandObject (alias_name);
1348 StreamString result_str;
1349
1350 if (alias_cmd_obj)
1351 {
1352 std::string alias_name_str = alias_name;
1353 if ((cmd_args.GetArgumentCount() == 0)
1354 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1355 cmd_args.Unshift (alias_name);
1356
1357 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1358 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1359
1360 if (option_arg_vector_sp.get())
1361 {
1362 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1363
Andy Gibbsa297a972013-06-19 19:04:53 +00001364 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Caroline Tice844d2302010-12-09 22:52:49 +00001365 {
1366 OptionArgPair option_pair = (*option_arg_vector)[i];
1367 OptionArgValue value_pair = option_pair.second;
1368 int value_type = value_pair.first;
1369 std::string option = option_pair.first;
1370 std::string value = value_pair.second;
1371 if (option.compare ("<argument>") == 0)
1372 result_str.Printf (" %s", value.c_str());
1373 else
1374 {
1375 result_str.Printf (" %s", option.c_str());
Virgile Belloe2607b52013-09-05 16:42:23 +00001376 if (value_type != OptionParser::eOptionalArgument)
Caroline Tice844d2302010-12-09 22:52:49 +00001377 result_str.Printf (" ");
Virgile Belloe2607b52013-09-05 16:42:23 +00001378 if (value.compare ("<OptionParser::eNoArgument>") != 0)
Caroline Tice844d2302010-12-09 22:52:49 +00001379 {
1380 int index = GetOptionArgumentPosition (value.c_str());
1381 if (index == 0)
1382 result_str.Printf ("%s", value.c_str());
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001383 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Caroline Tice844d2302010-12-09 22:52:49 +00001384 {
1385
1386 result.AppendErrorWithFormat
1387 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1388 index);
1389 result.SetStatus (eReturnStatusFailed);
Greg Clayton5521f992011-10-28 21:38:01 +00001390 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001391 }
1392 else
1393 {
1394 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1395 if (strpos != std::string::npos)
1396 raw_input_string = raw_input_string.erase (strpos,
1397 strlen (cmd_args.GetArgumentAtIndex (index)));
1398 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1399 }
1400 }
1401 }
1402 }
1403 }
1404
1405 alias_result = result_str.GetData();
1406 }
Greg Clayton5521f992011-10-28 21:38:01 +00001407 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001408}
1409
Greg Clayton5a314712011-10-14 07:41:33 +00001410Error
1411CommandInterpreter::PreprocessCommand (std::string &command)
1412{
1413 // The command preprocessor needs to do things to the command
1414 // line before any parsing of arguments or anything else is done.
1415 // The only current stuff that gets proprocessed is anyting enclosed
1416 // in backtick ('`') characters is evaluated as an expression and
1417 // the result of the expression must be a scalar that can be substituted
1418 // into the command. An example would be:
1419 // (lldb) memory read `$rsp + 20`
1420 Error error; // Error for any expressions that might not evaluate
1421 size_t start_backtick;
1422 size_t pos = 0;
1423 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1424 {
1425 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1426 {
1427 // The backtick was preceeded by a '\' character, remove the slash
1428 // and don't treat the backtick as the start of an expression
1429 command.erase(start_backtick-1, 1);
1430 // No need to add one to start_backtick since we just deleted a char
1431 pos = start_backtick;
1432 }
1433 else
1434 {
1435 const size_t expr_content_start = start_backtick + 1;
1436 const size_t end_backtick = command.find ('`', expr_content_start);
1437 if (end_backtick == std::string::npos)
1438 return error;
1439 else if (end_backtick == expr_content_start)
1440 {
1441 // Empty expression (two backticks in a row)
1442 command.erase (start_backtick, 2);
1443 }
1444 else
1445 {
1446 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1447
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00001448 ExecutionContext exe_ctx(GetExecutionContext());
1449 Target *target = exe_ctx.GetTargetPtr();
Johnny Chen51ea0ad2011-10-29 00:21:50 +00001450 // Get a dummy target to allow for calculator mode while processing backticks.
1451 // This also helps break the infinite loop caused when target is null.
1452 if (!target)
1453 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Clayton5a314712011-10-14 07:41:33 +00001454 if (target)
1455 {
Greg Clayton5a314712011-10-14 07:41:33 +00001456 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001457
Jim Ingham35e1bda2012-10-16 21:41:58 +00001458 EvaluateExpressionOptions options;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00001459 options.SetCoerceToId(false);
1460 options.SetUnwindOnError(true);
1461 options.SetIgnoreBreakpoints(true);
1462 options.SetKeepInMemory(false);
1463 options.SetTryAllThreads(true);
1464 options.SetTimeoutUsec(0);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001465
Jim Ingham1624a2d2014-05-05 02:26:40 +00001466 ExpressionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad4439aa2012-09-05 20:41:26 +00001467 exe_ctx.GetFramePtr(),
Enrico Granata3372f582012-07-16 23:10:35 +00001468 expr_result_valobj_sp,
Enrico Granatad4439aa2012-09-05 20:41:26 +00001469 options);
1470
Jim Ingham8646d3c2014-05-05 02:47:44 +00001471 if (expr_result == eExpressionCompleted)
Greg Clayton5a314712011-10-14 07:41:33 +00001472 {
1473 Scalar scalar;
1474 if (expr_result_valobj_sp->ResolveValue (scalar))
1475 {
1476 command.erase (start_backtick, end_backtick - start_backtick + 1);
1477 StreamString value_strm;
1478 const bool show_type = false;
1479 scalar.GetValue (&value_strm, show_type);
1480 size_t value_string_size = value_strm.GetSize();
1481 if (value_string_size)
1482 {
1483 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1484 pos = start_backtick + value_string_size;
1485 continue;
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 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1495 }
1496 }
1497 else
1498 {
1499 if (expr_result_valobj_sp)
1500 error = expr_result_valobj_sp->GetError();
1501 if (error.Success())
1502 {
1503
1504 switch (expr_result)
1505 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00001506 case eExpressionSetupError:
Greg Clayton5a314712011-10-14 07:41:33 +00001507 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1508 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001509 case eExpressionParseError:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001510 error.SetErrorStringWithFormat ("expression parse error for the expression '%s'", expr_str.c_str());
1511 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001512 case eExpressionResultUnavailable:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001513 error.SetErrorStringWithFormat ("expression error fetching result for the expression '%s'", expr_str.c_str());
Jim Ingham8646d3c2014-05-05 02:47:44 +00001514 case eExpressionCompleted:
Greg Clayton5a314712011-10-14 07:41:33 +00001515 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001516 case eExpressionDiscarded:
Greg Clayton5a314712011-10-14 07:41:33 +00001517 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1518 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001519 case eExpressionInterrupted:
Greg Clayton5a314712011-10-14 07:41:33 +00001520 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1521 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001522 case eExpressionHitBreakpoint:
Jim Ingham184e9812013-01-15 02:47:48 +00001523 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1524 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001525 case eExpressionTimedOut:
Greg Clayton5a314712011-10-14 07:41:33 +00001526 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1527 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001528 case eExpressionStoppedForDebug:
Greg Claytonc28ce782013-11-08 23:38:26 +00001529 error.SetErrorStringWithFormat("expression stop at entry point for debugging for the expression '%s'", expr_str.c_str());
1530 break;
Greg Clayton5a314712011-10-14 07:41:33 +00001531 }
1532 }
1533 }
1534 }
1535 }
1536 if (error.Fail())
1537 break;
1538 }
1539 }
1540 return error;
1541}
1542
1543
Caroline Tice844d2302010-12-09 22:52:49 +00001544bool
1545CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata5f5ab602012-05-31 01:09:06 +00001546 LazyBool lazy_add_to_history,
Caroline Tice844d2302010-12-09 22:52:49 +00001547 CommandReturnObject &result,
Jim Inghame16c50a2011-02-18 00:54:25 +00001548 ExecutionContext *override_context,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001549 bool repeat_on_empty_command,
1550 bool no_context_switching)
Jim Inghame16c50a2011-02-18 00:54:25 +00001551
Caroline Tice844d2302010-12-09 22:52:49 +00001552{
Jim Inghame16c50a2011-02-18 00:54:25 +00001553
Caroline Tice844d2302010-12-09 22:52:49 +00001554 bool done = false;
Ed Masted78c9572014-04-20 00:31:37 +00001555 CommandObject *cmd_obj = nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001556 bool wants_raw_input = false;
1557 std::string command_string (command_line);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001558 std::string original_command_string (command_line);
Caroline Tice844d2302010-12-09 22:52:49 +00001559
Greg Clayton5160ce52013-03-27 23:08:40 +00001560 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001561 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1562
1563 // Make a scoped cleanup object that will clear the crash description string
1564 // on exit of this function.
Ed Masted78c9572014-04-20 00:31:37 +00001565 lldb_utility::CleanUp <const char *> crash_description_cleanup(nullptr, Host::SetCrashDescription);
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001566
Caroline Tice844d2302010-12-09 22:52:49 +00001567 if (log)
1568 log->Printf ("Processing command: %s", command_line);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001569
Jim Ingham30244832010-11-04 23:08:45 +00001570 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1571
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001572 if (!no_context_switching)
1573 UpdateExecutionContext (override_context);
Enrico Granata5f5ab602012-05-31 01:09:06 +00001574
Enrico Granata5f5ab602012-05-31 01:09:06 +00001575 bool add_to_history;
1576 if (lazy_add_to_history == eLazyBoolCalculate)
1577 add_to_history = (m_command_source_depth == 0);
1578 else
1579 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1580
Jim Inghame16c50a2011-02-18 00:54:25 +00001581 bool empty_command = false;
1582 bool comment_command = false;
1583 if (command_string.empty())
1584 empty_command = true;
1585 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001586 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001587 const char *k_space_characters = "\t\n\v\f\r ";
1588
1589 size_t non_space = command_string.find_first_not_of (k_space_characters);
1590 // Check for empty line or comment line (lines whose first
1591 // non-space character is the comment character for this interpreter)
1592 if (non_space == std::string::npos)
1593 empty_command = true;
1594 else if (command_string[non_space] == m_comment_char)
1595 comment_command = true;
Enrico Granata7594f142013-06-17 22:51:50 +00001596 else if (command_string[non_space] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001597 {
Enrico Granata7594f142013-06-17 22:51:50 +00001598 const char *history_string = m_command_history.FindString(command_string.c_str() + non_space);
Ed Masted78c9572014-04-20 00:31:37 +00001599 if (history_string == nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001600 {
1601 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1602 result.SetStatus(eReturnStatusFailed);
1603 return false;
1604 }
1605 add_to_history = false;
1606 command_string = history_string;
1607 original_command_string = history_string;
1608 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001609 }
1610
1611 if (empty_command)
1612 {
1613 if (repeat_on_empty_command)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001614 {
Enrico Granata7594f142013-06-17 22:51:50 +00001615 if (m_command_history.IsEmpty())
Jim Inghame16c50a2011-02-18 00:54:25 +00001616 {
1617 result.AppendError ("empty command");
1618 result.SetStatus(eReturnStatusFailed);
1619 return false;
1620 }
1621 else
1622 {
1623 command_line = m_repeat_command.c_str();
1624 command_string = command_line;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001625 original_command_string = command_line;
Jim Inghame16c50a2011-02-18 00:54:25 +00001626 if (m_repeat_command.empty())
1627 {
1628 result.AppendErrorWithFormat("No auto repeat.\n");
1629 result.SetStatus (eReturnStatusFailed);
1630 return false;
1631 }
1632 }
1633 add_to_history = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001634 }
1635 else
1636 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001637 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1638 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001639 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001640 }
1641 else if (comment_command)
1642 {
1643 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1644 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001645 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001646
Greg Clayton5a314712011-10-14 07:41:33 +00001647
1648 Error error (PreprocessCommand (command_string));
1649
1650 if (error.Fail())
1651 {
1652 result.AppendError (error.AsCString());
1653 result.SetStatus(eReturnStatusFailed);
1654 return false;
1655 }
Caroline Tice844d2302010-12-09 22:52:49 +00001656 // Phase 1.
1657
1658 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1659 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1660 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1661 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1662 // 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 +00001663 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Tice844d2302010-12-09 22:52:49 +00001664 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Ticed9d63362010-12-07 19:58:26 +00001665
Caroline Tice844d2302010-12-09 22:52:49 +00001666 StreamString revised_command_line;
Caroline Tice01274c02010-12-11 08:16:56 +00001667 size_t actual_cmd_name_len = 0;
Greg Clayton5521f992011-10-28 21:38:01 +00001668 std::string next_word;
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001669 StringList matches;
Caroline Tice844d2302010-12-09 22:52:49 +00001670 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001671 {
Caroline Tice2b5e8502011-05-11 16:07:06 +00001672 char quote_char = '\0';
Greg Clayton5521f992011-10-28 21:38:01 +00001673 std::string suffix;
1674 ExtractCommand (command_string, next_word, suffix, quote_char);
Ed Masted78c9572014-04-20 00:31:37 +00001675 if (cmd_obj == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001676 {
Jim Ingham298f3782013-04-03 00:25:49 +00001677 std::string full_name;
1678 if (GetAliasFullName(next_word.c_str(), full_name))
Caroline Tice472362e2010-12-14 18:51:39 +00001679 {
Greg Clayton5521f992011-10-28 21:38:01 +00001680 std::string alias_result;
Jim Ingham298f3782013-04-03 00:25:49 +00001681 cmd_obj = BuildAliasResult (full_name.c_str(), command_string, alias_result, result);
Greg Clayton5521f992011-10-28 21:38:01 +00001682 revised_command_line.Printf ("%s", alias_result.c_str());
1683 if (cmd_obj)
1684 {
1685 wants_raw_input = cmd_obj->WantsRawCommandString ();
1686 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1687 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001688 }
1689 else
1690 {
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001691 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton5521f992011-10-28 21:38:01 +00001692 if (cmd_obj)
1693 {
1694 actual_cmd_name_len += next_word.length();
1695 revised_command_line.Printf ("%s", next_word.c_str());
1696 wants_raw_input = cmd_obj->WantsRawCommandString ();
1697 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001698 else
Greg Clayton5521f992011-10-28 21:38:01 +00001699 {
1700 revised_command_line.Printf ("%s", next_word.c_str());
1701 }
Caroline Tice844d2302010-12-09 22:52:49 +00001702 }
1703 }
1704 else
1705 {
Greg Clayton5521f992011-10-28 21:38:01 +00001706 if (cmd_obj->IsMultiwordObject ())
1707 {
Greg Clayton998255b2012-10-13 02:07:45 +00001708 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
Greg Clayton5521f992011-10-28 21:38:01 +00001709 if (sub_cmd_obj)
1710 {
1711 actual_cmd_name_len += next_word.length() + 1;
1712 revised_command_line.Printf (" %s", next_word.c_str());
1713 cmd_obj = sub_cmd_obj;
1714 wants_raw_input = cmd_obj->WantsRawCommandString ();
1715 }
1716 else
1717 {
1718 if (quote_char)
1719 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1720 else
1721 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1722 done = true;
1723 }
1724 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001725 else
Greg Clayton5521f992011-10-28 21:38:01 +00001726 {
1727 if (quote_char)
1728 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1729 else
1730 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1731 done = true;
1732 }
Caroline Tice844d2302010-12-09 22:52:49 +00001733 }
1734
Ed Masted78c9572014-04-20 00:31:37 +00001735 if (cmd_obj == nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001736 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001737 const size_t num_matches = matches.GetSize();
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001738 if (matches.GetSize() > 1) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001739 StreamString error_msg;
1740 error_msg.Printf ("Ambiguous command '%s'. Possible matches:\n", next_word.c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001741
1742 for (uint32_t i = 0; i < num_matches; ++i) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001743 error_msg.Printf ("\t%s\n", matches.GetStringAtIndex(i));
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001744 }
Greg Claytonc7bece562013-01-25 18:06:21 +00001745 result.AppendRawError (error_msg.GetString().c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001746 } else {
1747 // We didn't have only one match, otherwise we wouldn't get here.
1748 assert(num_matches == 0);
1749 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1750 }
Caroline Tice844d2302010-12-09 22:52:49 +00001751 result.SetStatus (eReturnStatusFailed);
1752 return false;
1753 }
1754
Greg Clayton5521f992011-10-28 21:38:01 +00001755 if (cmd_obj->IsMultiwordObject ())
1756 {
1757 if (!suffix.empty())
1758 {
1759
Enrico Granataaded51d2013-06-12 00:44:43 +00001760 result.AppendErrorWithFormat ("command '%s' did not recognize '%s%s%s' as valid (subcommand might be invalid).\n",
1761 cmd_obj->GetCommandName(),
1762 next_word.empty() ? "" : next_word.c_str(),
1763 next_word.empty() ? " -- " : " ",
Greg Clayton5521f992011-10-28 21:38:01 +00001764 suffix.c_str());
1765 result.SetStatus (eReturnStatusFailed);
1766 return false;
1767 }
1768 }
1769 else
1770 {
1771 // If we found a normal command, we are done
1772 done = true;
1773 if (!suffix.empty())
1774 {
1775 switch (suffix[0])
1776 {
1777 case '/':
1778 // GDB format suffixes
Greg Clayton52ec56c2011-10-29 00:57:28 +00001779 {
1780 Options *command_options = cmd_obj->GetOptions();
1781 if (command_options && command_options->SupportsLongOption("gdb-format"))
1782 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001783 std::string gdb_format_option ("--gdb-format=");
1784 gdb_format_option += (suffix.c_str() + 1);
1785
1786 bool inserted = false;
1787 std::string &cmd = revised_command_line.GetString();
1788 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1789 if (arg_terminator_idx != std::string::npos)
1790 {
1791 // Insert the gdb format option before the "--" that terminates options
1792 gdb_format_option.append(1,' ');
1793 cmd.insert(arg_terminator_idx, gdb_format_option);
1794 inserted = true;
1795 }
1796
1797 if (!inserted)
1798 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1799
1800 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1801 revised_command_line.PutCString (" --");
Greg Clayton52ec56c2011-10-29 00:57:28 +00001802 }
1803 else
1804 {
1805 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1806 cmd_obj->GetCommandName());
1807 result.SetStatus (eReturnStatusFailed);
1808 return false;
1809 }
1810 }
Greg Clayton5521f992011-10-28 21:38:01 +00001811 break;
Johnny Chen8e9383d2011-10-31 22:22:06 +00001812
1813 default:
1814 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1815 suffix.c_str());
1816 result.SetStatus (eReturnStatusFailed);
1817 return false;
1818
Greg Clayton5521f992011-10-28 21:38:01 +00001819 }
1820 }
1821 }
Caroline Tice844d2302010-12-09 22:52:49 +00001822 if (command_string.length() == 0)
1823 done = true;
1824
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001825 }
Caroline Tice844d2302010-12-09 22:52:49 +00001826
Greg Clayton5521f992011-10-28 21:38:01 +00001827 if (!command_string.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001828 revised_command_line.Printf (" %s", command_string.c_str());
1829
1830 // End of Phase 1.
1831 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1832 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1833 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1834 // wants_raw_input specifies whether the Execute method expects raw input or not.
1835
1836
1837 if (log)
1838 {
1839 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1840 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1841 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1842 }
1843
1844 // Phase 2.
1845 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1846 // CommandObject, with the appropriate arguments.
1847
Ed Masted78c9572014-04-20 00:31:37 +00001848 if (cmd_obj != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001849 {
1850 if (add_to_history)
1851 {
1852 Args command_args (revised_command_line.GetData());
1853 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
Ed Masted78c9572014-04-20 00:31:37 +00001854 if (repeat_command != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001855 m_repeat_command.assign(repeat_command);
1856 else
Jim Inghama5a97eb2011-07-12 03:12:18 +00001857 m_repeat_command.assign(original_command_string.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001858
Enrico Granata7594f142013-06-17 22:51:50 +00001859 m_command_history.AppendString (original_command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001860 }
1861
1862 command_string = revised_command_line.GetData();
1863 std::string command_name (cmd_obj->GetCommandName());
Caroline Tice01274c02010-12-11 08:16:56 +00001864 std::string remainder;
1865 if (actual_cmd_name_len < command_string.length())
1866 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1867 // than cmd_obj->GetCommandName(), because name completion
1868 // allows users to enter short versions of the names,
1869 // e.g. 'br s' for 'breakpoint set'.
Caroline Tice844d2302010-12-09 22:52:49 +00001870
1871 // Remove any initial spaces
1872 std::string white_space (" \t\v");
1873 size_t pos = remainder.find_first_not_of (white_space);
1874 if (pos != 0 && pos != std::string::npos)
Greg Claytona3482592011-04-22 20:58:45 +00001875 remainder.erase(0, pos);
Caroline Tice844d2302010-12-09 22:52:49 +00001876
1877 if (log)
Jason Molendabfb36ff2011-08-25 00:20:04 +00001878 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001879
Jim Ingham5a988412012-06-08 21:56:10 +00001880 cmd_obj->Execute (remainder.c_str(), result);
Caroline Tice844d2302010-12-09 22:52:49 +00001881 }
1882 else
1883 {
1884 // We didn't find the first command object, so complete the first argument.
1885 Args command_args (revised_command_line.GetData());
1886 StringList matches;
1887 int num_matches;
1888 int cursor_index = 0;
1889 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1890 bool word_complete;
1891 num_matches = HandleCompletionMatches (command_args,
1892 cursor_index,
1893 cursor_char_position,
1894 0,
1895 -1,
1896 word_complete,
1897 matches);
1898
1899 if (num_matches > 0)
1900 {
1901 std::string error_msg;
1902 error_msg.assign ("ambiguous command '");
1903 error_msg.append(command_args.GetArgumentAtIndex(0));
1904 error_msg.append ("'.");
1905
1906 error_msg.append (" Possible completions:");
1907 for (int i = 0; i < num_matches; i++)
1908 {
1909 error_msg.append ("\n\t");
1910 error_msg.append (matches.GetStringAtIndex (i));
1911 }
1912 error_msg.append ("\n");
Greg Claytonc7bece562013-01-25 18:06:21 +00001913 result.AppendRawError (error_msg.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001914 }
1915 else
1916 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1917
1918 result.SetStatus (eReturnStatusFailed);
1919 }
1920
Jason Molendabfb36ff2011-08-25 00:20:04 +00001921 if (log)
1922 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1923
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001924 return result.Succeeded();
1925}
1926
1927int
1928CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1929 int &cursor_index,
1930 int &cursor_char_position,
1931 int match_start_point,
1932 int max_return_elements,
Jim Ingham558ce122010-06-30 05:02:46 +00001933 bool &word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001934 StringList &matches)
1935{
1936 int num_command_matches = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001937 bool look_for_subcommand = false;
Jim Ingham558ce122010-06-30 05:02:46 +00001938
1939 // For any of the command completions a unique match will be a complete word.
1940 word_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001941
1942 if (cursor_index == -1)
1943 {
1944 // We got nothing on the command line, so return the list of commands
Jim Ingham279a6c22010-07-06 22:46:59 +00001945 bool include_aliases = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001946 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1947 }
1948 else if (cursor_index == 0)
1949 {
1950 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Ingham279a6c22010-07-06 22:46:59 +00001951 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001952 num_command_matches = matches.GetSize();
1953
1954 if (num_command_matches == 1
1955 && cmd_obj && cmd_obj->IsMultiwordObject()
Ed Masted78c9572014-04-20 00:31:37 +00001956 && matches.GetStringAtIndex(0) != nullptr
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001957 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1958 {
Greg Clayton765d2e22013-12-10 19:14:04 +00001959 if (parsed_line.GetArgumentCount() == 1)
1960 {
1961 word_complete = true;
1962 }
1963 else
1964 {
1965 look_for_subcommand = true;
1966 num_command_matches = 0;
1967 matches.DeleteStringAtIndex(0);
1968 parsed_line.AppendArgument ("");
1969 cursor_index++;
1970 cursor_char_position = 0;
1971 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001972 }
1973 }
1974
1975 if (cursor_index > 0 || look_for_subcommand)
1976 {
1977 // We are completing further on into a commands arguments, so find the command and tell it
1978 // to complete the command.
1979 // First see if there is a matching initial command:
Jim Ingham279a6c22010-07-06 22:46:59 +00001980 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Ed Masted78c9572014-04-20 00:31:37 +00001981 if (command_object == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001982 {
1983 return 0;
1984 }
1985 else
1986 {
1987 parsed_line.Shift();
1988 cursor_index--;
Greg Claytona7015092010-09-18 01:14:36 +00001989 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton66111032010-06-23 01:19:29 +00001990 cursor_index,
1991 cursor_char_position,
1992 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001993 max_return_elements,
1994 word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001995 matches);
1996 }
1997 }
1998
1999 return num_command_matches;
2000
2001}
2002
2003int
2004CommandInterpreter::HandleCompletion (const char *current_line,
2005 const char *cursor,
2006 const char *last_char,
2007 int match_start_point,
2008 int max_return_elements,
2009 StringList &matches)
2010{
2011 // We parse the argument up to the cursor, so the last argument in parsed_line is
2012 // the one containing the cursor, and the cursor is after the last character.
2013
2014 Args parsed_line(current_line, last_char - current_line);
2015 Args partial_parsed_line(current_line, cursor - current_line);
2016
Jim Inghama5a97eb2011-07-12 03:12:18 +00002017 // Don't complete comments, and if the line we are completing is just the history repeat character,
2018 // substitute the appropriate history line.
2019 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
2020 if (first_arg)
2021 {
2022 if (first_arg[0] == m_comment_char)
2023 return 0;
Enrico Granata7594f142013-06-17 22:51:50 +00002024 else if (first_arg[0] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002025 {
Enrico Granata7594f142013-06-17 22:51:50 +00002026 const char *history_string = m_command_history.FindString (first_arg);
Ed Masted78c9572014-04-20 00:31:37 +00002027 if (history_string != nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002028 {
2029 matches.Clear();
2030 matches.InsertStringAtIndex(0, history_string);
2031 return -2;
2032 }
2033 else
2034 return 0;
2035
2036 }
2037 }
2038
2039
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002040 int num_args = partial_parsed_line.GetArgumentCount();
2041 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
2042 int cursor_char_position;
2043
2044 if (cursor_index == -1)
2045 cursor_char_position = 0;
2046 else
2047 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamfe0c4252010-12-14 19:56:01 +00002048
2049 if (cursor > current_line && cursor[-1] == ' ')
2050 {
2051 // We are just after a space. If we are in an argument, then we will continue
2052 // parsing, but if we are between arguments, then we have to complete whatever the next
2053 // element would be.
2054 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
2055 // protected by a quote) then the space will also be in the parsed argument...
2056
2057 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
2058 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
2059 {
Greg Clayton765d2e22013-12-10 19:14:04 +00002060 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '\0');
Jim Inghamfe0c4252010-12-14 19:56:01 +00002061 cursor_index++;
2062 cursor_char_position = 0;
2063 }
2064 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002065
2066 int num_command_matches;
2067
2068 matches.Clear();
2069
2070 // Only max_return_elements == -1 is supported at present:
2071 assert (max_return_elements == -1);
Jim Ingham558ce122010-06-30 05:02:46 +00002072 bool word_complete;
Greg Clayton66111032010-06-23 01:19:29 +00002073 num_command_matches = HandleCompletionMatches (parsed_line,
2074 cursor_index,
2075 cursor_char_position,
2076 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00002077 max_return_elements,
2078 word_complete,
Greg Clayton66111032010-06-23 01:19:29 +00002079 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002080
2081 if (num_command_matches <= 0)
2082 return num_command_matches;
2083
2084 if (num_args == 0)
2085 {
2086 // If we got an empty string, insert nothing.
2087 matches.InsertStringAtIndex(0, "");
2088 }
2089 else
2090 {
2091 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
2092 // put an empty string in element 0.
2093 std::string command_partial_str;
2094 if (cursor_index >= 0)
Jim Ingham49e80a12010-10-22 18:47:16 +00002095 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
2096 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002097
2098 std::string common_prefix;
2099 matches.LongestCommonPrefix (common_prefix);
Greg Claytonc7bece562013-01-25 18:06:21 +00002100 const size_t partial_name_len = command_partial_str.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002101
2102 // If we matched a unique single command, add a space...
Jim Ingham558ce122010-06-30 05:02:46 +00002103 // Only do this if the completer told us this was a complete word, however...
2104 if (num_command_matches == 1 && word_complete)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002105 {
2106 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
2107 if (quote_char != '\0')
2108 common_prefix.push_back(quote_char);
2109
2110 common_prefix.push_back(' ');
2111 }
2112 common_prefix.erase (0, partial_name_len);
2113 matches.InsertStringAtIndex(0, common_prefix.c_str());
2114 }
2115 return num_command_matches;
2116}
2117
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002118
2119CommandInterpreter::~CommandInterpreter ()
2120{
2121}
2122
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002123void
Greg Clayton44d93782014-01-27 23:43:24 +00002124CommandInterpreter::UpdatePrompt (const char *new_prompt)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002125{
Greg Clayton44d93782014-01-27 23:43:24 +00002126 EventSP prompt_change_event_sp (new Event(eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));;
2127 BroadcastEvent (prompt_change_event_sp);
2128 if (m_command_io_handler_sp)
2129 m_command_io_handler_sp->SetPrompt(new_prompt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002130}
2131
Jim Ingham97a6dc72010-10-04 19:49:29 +00002132
2133bool
2134CommandInterpreter::Confirm (const char *message, bool default_answer)
2135{
Jim Ingham3bcdb292010-10-04 22:44:14 +00002136 // Check AutoConfirm first:
2137 if (m_debugger.GetAutoConfirm())
2138 return default_answer;
Greg Clayton44d93782014-01-27 23:43:24 +00002139
2140 IOHandlerConfirm *confirm = new IOHandlerConfirm(m_debugger,
2141 message,
2142 default_answer);
2143 IOHandlerSP io_handler_sp (confirm);
2144 m_debugger.RunIOHandler (io_handler_sp);
2145 return confirm->GetResponse();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002146}
2147
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002148OptionArgVectorSP
2149CommandInterpreter::GetAliasOptions (const char *alias_name)
2150{
2151 OptionArgMap::iterator pos;
2152 OptionArgVectorSP ret_val;
2153
2154 std::string alias (alias_name);
2155
2156 if (HasAliasOptions())
2157 {
2158 pos = m_alias_options.find (alias);
2159 if (pos != m_alias_options.end())
2160 ret_val = pos->second;
2161 }
2162
2163 return ret_val;
2164}
2165
2166void
2167CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2168{
2169 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2170 if (pos != m_alias_options.end())
2171 {
2172 m_alias_options.erase (pos);
2173 }
2174}
2175
2176void
2177CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2178{
2179 m_alias_options[alias_name] = option_arg_vector_sp;
2180}
2181
2182bool
2183CommandInterpreter::HasCommands ()
2184{
2185 return (!m_command_dict.empty());
2186}
2187
2188bool
2189CommandInterpreter::HasAliases ()
2190{
2191 return (!m_alias_dict.empty());
2192}
2193
2194bool
2195CommandInterpreter::HasUserCommands ()
2196{
2197 return (!m_user_dict.empty());
2198}
2199
2200bool
2201CommandInterpreter::HasAliasOptions ()
2202{
2203 return (!m_alias_options.empty());
2204}
2205
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002206void
Caroline Tice4ab31c92010-10-12 21:57:09 +00002207CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2208 const char *alias_name,
2209 Args &cmd_args,
Caroline Ticed9d63362010-12-07 19:58:26 +00002210 std::string &raw_input_string,
Caroline Tice4ab31c92010-10-12 21:57:09 +00002211 CommandReturnObject &result)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002212{
2213 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Ticed9d63362010-12-07 19:58:26 +00002214
2215 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002216
Caroline Ticed9d63362010-12-07 19:58:26 +00002217 // Make sure that the alias name is the 0th element in cmd_args
2218 std::string alias_name_str = alias_name;
2219 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2220 cmd_args.Unshift (alias_name);
2221
2222 Args new_args (alias_cmd_obj->GetCommandName());
2223 if (new_args.GetArgumentCount() == 2)
2224 new_args.Shift();
2225
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002226 if (option_arg_vector_sp.get())
2227 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002228 if (wants_raw_input)
2229 {
2230 // We have a command that both has command options and takes raw input. Make *sure* it has a
2231 // " -- " in the right place in the raw_input_string.
2232 size_t pos = raw_input_string.find(" -- ");
2233 if (pos == std::string::npos)
2234 {
2235 // None found; assume it goes at the beginning of the raw input string
2236 raw_input_string.insert (0, " -- ");
2237 }
2238 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002239
2240 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Greg Claytonc7bece562013-01-25 18:06:21 +00002241 const size_t old_size = cmd_args.GetArgumentCount();
Caroline Tice4ab31c92010-10-12 21:57:09 +00002242 std::vector<bool> used (old_size + 1, false);
2243
2244 used[0] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002245
Andy Gibbsa297a972013-06-19 19:04:53 +00002246 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002247 {
2248 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Ticed9d63362010-12-07 19:58:26 +00002249 OptionArgValue value_pair = option_pair.second;
2250 int value_type = value_pair.first;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002251 std::string option = option_pair.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00002252 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002253 if (option.compare ("<argument>") == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002254 {
2255 if (!wants_raw_input
2256 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2257 new_args.AppendArgument (value.c_str());
2258 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002259 else
2260 {
Virgile Belloe2607b52013-09-05 16:42:23 +00002261 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002262 new_args.AppendArgument (option.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002263 if (value.compare ("<no-argument>") != 0)
2264 {
2265 int index = GetOptionArgumentPosition (value.c_str());
2266 if (index == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002267 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002268 // value was NOT a positional argument; must be a real value
Virgile Belloe2607b52013-09-05 16:42:23 +00002269 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002270 new_args.AppendArgument (value.c_str());
2271 else
2272 {
2273 char buffer[255];
2274 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2275 new_args.AppendArgument (buffer);
2276 }
2277
2278 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002279 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002280 {
2281 result.AppendErrorWithFormat
2282 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2283 index);
2284 result.SetStatus (eReturnStatusFailed);
2285 return;
2286 }
2287 else
2288 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002289 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2290 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2291 if (strpos != std::string::npos)
2292 {
2293 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2294 }
2295
Virgile Belloe2607b52013-09-05 16:42:23 +00002296 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002297 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2298 else
2299 {
2300 char buffer[255];
2301 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2302 cmd_args.GetArgumentAtIndex (index));
2303 new_args.AppendArgument (buffer);
2304 }
Caroline Tice4ab31c92010-10-12 21:57:09 +00002305 used[index] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002306 }
2307 }
2308 }
2309 }
2310
Andy Gibbsa297a972013-06-19 19:04:53 +00002311 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002312 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002313 if (!used[j] && !wants_raw_input)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002314 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2315 }
2316
2317 cmd_args.Clear();
2318 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2319 }
2320 else
2321 {
2322 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Ticed9d63362010-12-07 19:58:26 +00002323 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2324 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2325 // input string.
2326 if (wants_raw_input)
2327 {
2328 cmd_args.Clear();
2329 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2330 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002331 return;
2332 }
2333
2334 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2335 return;
2336}
2337
2338
2339int
2340CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2341{
2342 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2343 // of zero.
2344
2345 char *cptr = (char *) in_string;
2346
2347 // Does it start with '%'
2348 if (cptr[0] == '%')
2349 {
2350 ++cptr;
2351
2352 // Is the rest of it entirely digits?
2353 if (isdigit (cptr[0]))
2354 {
2355 const char *start = cptr;
2356 while (isdigit (cptr[0]))
2357 ++cptr;
2358
2359 // We've gotten to the end of the digits; are we at the end of the string?
2360 if (cptr[0] == '\0')
2361 position = atoi (start);
2362 }
2363 }
2364
2365 return position;
2366}
2367
2368void
2369CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2370{
Jim Ingham16e0c682011-08-12 23:34:31 +00002371 FileSpec init_file;
Greg Clayton14a35512011-09-11 00:01:44 +00002372 if (in_cwd)
Jim Ingham16e0c682011-08-12 23:34:31 +00002373 {
Greg Clayton14a35512011-09-11 00:01:44 +00002374 // In the current working directory we don't load any program specific
2375 // .lldbinit files, we only look for a "./.lldbinit" file.
2376 if (m_skip_lldbinit_files)
2377 return;
2378
2379 init_file.SetFile ("./.lldbinit", true);
Jim Ingham16e0c682011-08-12 23:34:31 +00002380 }
Greg Clayton14a35512011-09-11 00:01:44 +00002381 else
Jim Ingham16e0c682011-08-12 23:34:31 +00002382 {
Greg Clayton14a35512011-09-11 00:01:44 +00002383 // If we aren't looking in the current working directory we are looking
2384 // in the home directory. We will first see if there is an application
2385 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2386 // "-" and the name of the program. If this file doesn't exist, we fall
2387 // back to just the "~/.lldbinit" file. We also obey any requests to not
2388 // load the init files.
Zachary Turnera21fee02014-08-21 21:49:24 +00002389 llvm::SmallString<64> home_dir_path;
2390 llvm::sys::path::home_directory(home_dir_path);
2391 FileSpec profilePath(home_dir_path.c_str(), false);
Zachary Turner9e757b72014-07-28 16:45:05 +00002392 profilePath.AppendPathComponent(".lldbinit");
2393 std::string init_file_path = profilePath.GetPath();
Greg Clayton14a35512011-09-11 00:01:44 +00002394
2395 if (m_skip_app_init_files == false)
2396 {
Zachary Turnera21fee02014-08-21 21:49:24 +00002397 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
Greg Clayton14a35512011-09-11 00:01:44 +00002398 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham16e0c682011-08-12 23:34:31 +00002399
Greg Clayton14a35512011-09-11 00:01:44 +00002400 if (program_name)
2401 {
2402 char program_init_file_name[PATH_MAX];
Zachary Turner9e757b72014-07-28 16:45:05 +00002403 ::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 +00002404 init_file.SetFile (program_init_file_name, true);
2405 if (!init_file.Exists())
2406 init_file.Clear();
2407 }
2408 }
2409
2410 if (!init_file && !m_skip_lldbinit_files)
Zachary Turner9e757b72014-07-28 16:45:05 +00002411 init_file.SetFile (init_file_path.c_str(), false);
Greg Clayton14a35512011-09-11 00:01:44 +00002412 }
2413
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002414 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2415 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2416
2417 if (init_file.Exists())
2418 {
Greg Clayton44d93782014-01-27 23:43:24 +00002419 const bool saved_batch = SetBatchCommandMode (true);
Greg Clayton340b0302014-02-05 17:57:57 +00002420 HandleCommandsFromFile (init_file,
Ed Masted78c9572014-04-20 00:31:37 +00002421 nullptr, // Execution context
Greg Clayton340b0302014-02-05 17:57:57 +00002422 eLazyBoolYes, // Stop on continue
2423 eLazyBoolNo, // Stop on error
2424 eLazyBoolNo, // Don't echo commands
2425 eLazyBoolNo, // Don't print command output
2426 eLazyBoolNo, // Don't add the commands that are sourced into the history buffer
2427 result);
Greg Clayton44d93782014-01-27 23:43:24 +00002428 SetBatchCommandMode (saved_batch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429 }
2430 else
2431 {
2432 // nothing to be done if the file doesn't exist
2433 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2434 }
2435}
2436
Greg Clayton8b82f082011-04-12 05:54:46 +00002437PlatformSP
2438CommandInterpreter::GetPlatform (bool prefer_target_platform)
2439{
2440 PlatformSP platform_sp;
Greg Claytonc14ee322011-09-22 04:58:26 +00002441 if (prefer_target_platform)
2442 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002443 ExecutionContext exe_ctx(GetExecutionContext());
2444 Target *target = exe_ctx.GetTargetPtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002445 if (target)
2446 platform_sp = target->GetPlatform();
2447 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002448
2449 if (!platform_sp)
2450 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2451 return platform_sp;
2452}
2453
Jim Inghame16c50a2011-02-18 00:54:25 +00002454void
Jim Inghambad87fe2011-03-11 01:51:49 +00002455CommandInterpreter::HandleCommands (const StringList &commands,
Jim Inghame16c50a2011-02-18 00:54:25 +00002456 ExecutionContext *override_context,
2457 bool stop_on_continue,
2458 bool stop_on_error,
2459 bool echo_commands,
2460 bool print_results,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002461 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002462 CommandReturnObject &result)
2463{
2464 size_t num_lines = commands.GetSize();
Jim Inghame16c50a2011-02-18 00:54:25 +00002465
2466 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2467 // Make sure you reset this value anywhere you return from the function.
2468
2469 bool old_async_execution = m_debugger.GetAsyncExecution();
2470
2471 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2472 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2473
Ed Masted78c9572014-04-20 00:31:37 +00002474 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00002475 UpdateExecutionContext (override_context);
Jim Inghame16c50a2011-02-18 00:54:25 +00002476
2477 if (!stop_on_continue)
2478 {
2479 m_debugger.SetAsyncExecution (false);
2480 }
2481
Andy Gibbsa297a972013-06-19 19:04:53 +00002482 for (size_t idx = 0; idx < num_lines; idx++)
Jim Inghame16c50a2011-02-18 00:54:25 +00002483 {
2484 const char *cmd = commands.GetStringAtIndex(idx);
2485 if (cmd[0] == '\0')
2486 continue;
2487
Jim Inghame16c50a2011-02-18 00:54:25 +00002488 if (echo_commands)
2489 {
2490 result.AppendMessageWithFormat ("%s %s\n",
Greg Clayton44d93782014-01-27 23:43:24 +00002491 m_debugger.GetPrompt(),
2492 cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002493 }
2494
Greg Clayton9d0402b2011-02-20 02:15:07 +00002495 CommandReturnObject tmp_result;
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002496 // If override_context is not NULL, pass no_context_switching = true for
2497 // HandleCommand() since we updated our context already.
Jim Ingham076b7fc2013-05-02 23:15:37 +00002498
2499 // We might call into a regex or alias command, in which case the add_to_history will get lost. This
2500 // m_command_source_depth dingus is the way we turn off adding to the history in that case, so set it up here.
2501 if (!add_to_history)
2502 m_command_source_depth++;
Enrico Granata5f5ab602012-05-31 01:09:06 +00002503 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Ed Masted78c9572014-04-20 00:31:37 +00002504 nullptr, /* override_context */
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002505 true, /* repeat_on_empty_command */
Ed Masted78c9572014-04-20 00:31:37 +00002506 override_context != nullptr /* no_context_switching */);
Jim Ingham076b7fc2013-05-02 23:15:37 +00002507 if (!add_to_history)
2508 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002509
2510 if (print_results)
2511 {
2512 if (tmp_result.Succeeded())
Jim Ingham85e8b812011-02-19 02:53:09 +00002513 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Inghame16c50a2011-02-18 00:54:25 +00002514 }
2515
2516 if (!success || !tmp_result.Succeeded())
2517 {
Jim Inghama5038812012-04-24 02:25:07 +00002518 const char *error_msg = tmp_result.GetErrorData();
Ed Masted78c9572014-04-20 00:31:37 +00002519 if (error_msg == nullptr || error_msg[0] == '\0')
Jim Inghama5038812012-04-24 02:25:07 +00002520 error_msg = "<unknown error>.\n";
Jim Inghame16c50a2011-02-18 00:54:25 +00002521 if (stop_on_error)
2522 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002523 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' failed with %s",
2524 (uint64_t)idx, cmd, error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002525 result.SetStatus (eReturnStatusFailed);
2526 m_debugger.SetAsyncExecution (old_async_execution);
2527 return;
2528 }
2529 else if (print_results)
2530 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002531 result.AppendMessageWithFormat ("Command #%" PRIu64 " '%s' failed with %s",
2532 (uint64_t)idx + 1,
Jim Inghame16c50a2011-02-18 00:54:25 +00002533 cmd,
Jim Inghama5038812012-04-24 02:25:07 +00002534 error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002535 }
2536 }
2537
Caroline Tice969ed3d2011-05-02 20:41:46 +00002538 if (result.GetImmediateOutputStream())
2539 result.GetImmediateOutputStream()->Flush();
2540
2541 if (result.GetImmediateErrorStream())
2542 result.GetImmediateErrorStream()->Flush();
2543
Jim Inghame16c50a2011-02-18 00:54:25 +00002544 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2545 // could be running (for instance in Breakpoint Commands.
2546 // So we check the return value to see if it is has running in it.
2547 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2548 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2549 {
2550 if (stop_on_continue)
2551 {
2552 // If we caused the target to proceed, and we're going to stop in that case, set the
2553 // status in our real result before returning. This is an error if the continue was not the
2554 // last command in the set of commands to be run.
2555 if (idx != num_lines - 1)
Deepak Panickal99fbc072014-03-03 15:39:47 +00002556 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' continued the target.\n",
2557 (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002558 else
Deepak Panickal99fbc072014-03-03 15:39:47 +00002559 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' continued the target.\n", (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002560
2561 result.SetStatus(tmp_result.GetStatus());
2562 m_debugger.SetAsyncExecution (old_async_execution);
2563
2564 return;
2565 }
2566 }
2567
2568 }
2569
2570 result.SetStatus (eReturnStatusSuccessFinishResult);
2571 m_debugger.SetAsyncExecution (old_async_execution);
2572
2573 return;
2574}
2575
Greg Clayton340b0302014-02-05 17:57:57 +00002576// Make flags that we can pass into the IOHandler so our delegates can do the right thing
2577enum {
2578 eHandleCommandFlagStopOnContinue = (1u << 0),
2579 eHandleCommandFlagStopOnError = (1u << 1),
2580 eHandleCommandFlagEchoCommand = (1u << 2),
2581 eHandleCommandFlagPrintResult = (1u << 3)
2582};
2583
Jim Inghame16c50a2011-02-18 00:54:25 +00002584void
2585CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2586 ExecutionContext *context,
Greg Clayton340b0302014-02-05 17:57:57 +00002587 LazyBool stop_on_continue,
2588 LazyBool stop_on_error,
2589 LazyBool echo_command,
2590 LazyBool print_result,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002591 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002592 CommandReturnObject &result)
2593{
2594 if (cmd_file.Exists())
2595 {
Greg Clayton44d93782014-01-27 23:43:24 +00002596 StreamFileSP input_file_sp (new StreamFile());
2597
2598 std::string cmd_file_path = cmd_file.GetPath();
2599 Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), File::eOpenOptionRead);
2600
2601 if (error.Success())
2602 {
2603 Debugger &debugger = GetDebugger();
2604
Greg Clayton340b0302014-02-05 17:57:57 +00002605 uint32_t flags = 0;
2606
2607 if (stop_on_continue == eLazyBoolCalculate)
2608 {
2609 if (m_command_source_flags.empty())
2610 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002611 // Stop on continue by default
Greg Clayton340b0302014-02-05 17:57:57 +00002612 flags |= eHandleCommandFlagStopOnContinue;
2613 }
2614 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnContinue)
2615 {
2616 flags |= eHandleCommandFlagStopOnContinue;
2617 }
2618 }
2619 else if (stop_on_continue == eLazyBoolYes)
2620 {
2621 flags |= eHandleCommandFlagStopOnContinue;
2622 }
2623
2624 if (stop_on_error == eLazyBoolCalculate)
2625 {
2626 if (m_command_source_flags.empty())
2627 {
2628 if (GetStopCmdSourceOnError())
2629 flags |= eHandleCommandFlagStopOnError;
2630 }
2631 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError)
2632 {
2633 flags |= eHandleCommandFlagStopOnError;
2634 }
2635 }
2636 else if (stop_on_error == eLazyBoolYes)
2637 {
2638 flags |= eHandleCommandFlagStopOnError;
2639 }
2640
2641 if (echo_command == eLazyBoolCalculate)
2642 {
2643 if (m_command_source_flags.empty())
2644 {
2645 // Echo command by default
2646 flags |= eHandleCommandFlagEchoCommand;
2647 }
2648 else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand)
2649 {
2650 flags |= eHandleCommandFlagEchoCommand;
2651 }
2652 }
2653 else if (echo_command == eLazyBoolYes)
2654 {
2655 flags |= eHandleCommandFlagEchoCommand;
2656 }
2657
2658 if (print_result == eLazyBoolCalculate)
2659 {
2660 if (m_command_source_flags.empty())
2661 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002662 // Print output by default
2663 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002664 }
Greg Claytone4e462c2014-02-05 21:03:22 +00002665 else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult)
Greg Clayton340b0302014-02-05 17:57:57 +00002666 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002667 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002668 }
2669 }
2670 else if (print_result == eLazyBoolYes)
2671 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002672 flags |= eHandleCommandFlagPrintResult;
2673 }
2674
2675 if (flags & eHandleCommandFlagPrintResult)
2676 {
Greg Clayton8ee67312014-02-05 21:46:20 +00002677 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", cmd_file_path.c_str());
Greg Clayton340b0302014-02-05 17:57:57 +00002678 }
2679
2680 // Used for inheriting the right settings when "command source" might have
2681 // nested "command source" commands
Greg Claytone4e462c2014-02-05 21:03:22 +00002682 lldb::StreamFileSP empty_stream_sp;
Greg Clayton340b0302014-02-05 17:57:57 +00002683 m_command_source_flags.push_back(flags);
Greg Clayton44d93782014-01-27 23:43:24 +00002684 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
2685 input_file_sp,
Greg Claytone4e462c2014-02-05 21:03:22 +00002686 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader output stream
2687 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader error stream
Greg Clayton340b0302014-02-05 17:57:57 +00002688 flags,
Ed Masted78c9572014-04-20 00:31:37 +00002689 nullptr, // Pass in NULL for "editline_name" so no history is saved, or written
Greg Clayton8ee67312014-02-05 21:46:20 +00002690 debugger.GetPrompt(),
Greg Clayton44d93782014-01-27 23:43:24 +00002691 false, // Not multi-line
Greg Claytonf6913cd2014-03-07 00:53:24 +00002692 0,
Greg Clayton44d93782014-01-27 23:43:24 +00002693 *this));
Greg Clayton8ee67312014-02-05 21:46:20 +00002694 const bool old_async_execution = debugger.GetAsyncExecution();
2695
2696 // Set synchronous execution if we not stopping when we continue
2697 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2698 debugger.SetAsyncExecution (false);
2699
Greg Clayton340b0302014-02-05 17:57:57 +00002700 m_command_source_depth++;
Greg Clayton8ee67312014-02-05 21:46:20 +00002701
2702 debugger.RunIOHandler(io_handler_sp);
Greg Clayton340b0302014-02-05 17:57:57 +00002703 if (!m_command_source_flags.empty())
2704 m_command_source_flags.pop_back();
2705 m_command_source_depth--;
Greg Clayton44d93782014-01-27 23:43:24 +00002706 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Greg Clayton8ee67312014-02-05 21:46:20 +00002707 debugger.SetAsyncExecution (old_async_execution);
Greg Clayton44d93782014-01-27 23:43:24 +00002708 }
2709 else
2710 {
2711 result.AppendErrorWithFormat ("error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(), error.AsCString());
2712 result.SetStatus (eReturnStatusFailed);
2713 }
Greg Clayton8ee67312014-02-05 21:46:20 +00002714
2715
Jim Inghame16c50a2011-02-18 00:54:25 +00002716 }
2717 else
2718 {
2719 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2720 cmd_file.GetFilename().AsCString());
2721 result.SetStatus (eReturnStatusFailed);
2722 return;
2723 }
2724}
2725
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002726ScriptInterpreter *
Enrico Granatab5887262012-10-29 21:18:03 +00002727CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002728{
Ed Masted78c9572014-04-20 00:31:37 +00002729 if (m_script_interpreter_ap.get() != nullptr)
Enrico Granatab5887262012-10-29 21:18:03 +00002730 return m_script_interpreter_ap.get();
2731
2732 if (!can_create)
Ed Masted78c9572014-04-20 00:31:37 +00002733 return nullptr;
Enrico Granatab5887262012-10-29 21:18:03 +00002734
Enrico Granataa29bdad2012-07-10 18:23:48 +00002735 // <rdar://problem/11751427>
2736 // we need to protect the initialization of the script interpreter
2737 // otherwise we could end up with two threads both trying to create
2738 // their instance of it, and for some languages (e.g. Python)
2739 // this is a bulletproof recipe for disaster!
2740 // this needs to be a function-level static because multiple Debugger instances living in the same process
2741 // still need to be isolated and not try to initialize Python concurrently
Enrico Granata8b95df22012-07-10 19:04:14 +00002742 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2743 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granataa29bdad2012-07-10 18:23:48 +00002744
Greg Clayton5160ce52013-03-27 23:08:40 +00002745 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Enrico Granatab5887262012-10-29 21:18:03 +00002746 if (log)
2747 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton66111032010-06-23 01:19:29 +00002748
Caroline Tice2f88aad2011-01-14 00:29:16 +00002749 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2750 switch (script_lang)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002751 {
Greg Claytondce502e2011-11-04 03:34:56 +00002752 case eScriptLanguagePython:
2753#ifndef LLDB_DISABLE_PYTHON
2754 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2755 break;
2756#else
2757 // Fall through to the None case when python is disabled
2758#endif
Caroline Tice2f88aad2011-01-14 00:29:16 +00002759 case eScriptLanguageNone:
2760 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2761 break;
Caroline Tice2f88aad2011-01-14 00:29:16 +00002762 };
2763
2764 return m_script_interpreter_ap.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002765}
2766
2767
2768
2769bool
2770CommandInterpreter::GetSynchronous ()
2771{
2772 return m_synchronous_execution;
2773}
2774
2775void
2776CommandInterpreter::SetSynchronous (bool value)
2777{
Johnny Chenc066ab42010-10-14 01:22:03 +00002778 m_synchronous_execution = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002779}
2780
2781void
2782CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2783 const char *word_text,
2784 const char *separator,
2785 const char *help_text,
Greg Claytonc7bece562013-01-25 18:06:21 +00002786 size_t max_word_len)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002787{
Greg Claytona7015092010-09-18 01:14:36 +00002788 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2789
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002790 int indent_size = max_word_len + strlen (separator) + 2;
2791
2792 strm.IndentMore (indent_size);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002793
2794 StreamString text_strm;
Greg Claytonc7bece562013-01-25 18:06:21 +00002795 text_strm.Printf ("%-*s %s %s", (int)max_word_len, word_text, separator, help_text);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002796
2797 size_t len = text_strm.GetSize();
2798 const char *text = text_strm.GetData();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002799 if (text[len - 1] == '\n')
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002800 {
2801 text_strm.EOL();
2802 len = text_strm.GetSize();
2803 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002804
2805 if (len < max_columns)
2806 {
2807 // Output it as a single line.
2808 strm.Printf ("%s", text);
2809 }
2810 else
2811 {
2812 // We need to break it up into multiple lines.
2813 bool first_line = true;
2814 int text_width;
Greg Claytonc7bece562013-01-25 18:06:21 +00002815 size_t start = 0;
2816 size_t end = start;
2817 const size_t final_end = strlen (text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002818
2819 while (end < final_end)
2820 {
2821 if (first_line)
2822 text_width = max_columns - 1;
2823 else
2824 text_width = max_columns - indent_size - 1;
2825
2826 // Don't start the 'text' on a space, since we're already outputting the indentation.
2827 if (!first_line)
2828 {
2829 while ((start < final_end) && (text[start] == ' '))
2830 start++;
2831 }
2832
2833 end = start + text_width;
2834 if (end > final_end)
2835 end = final_end;
2836 else
2837 {
2838 // If we're not at the end of the text, make sure we break the line on white space.
2839 while (end > start
2840 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2841 end--;
Greg Clayton67cc0632012-08-22 17:17:09 +00002842 assert (end > 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002843 }
2844
Greg Claytonc7bece562013-01-25 18:06:21 +00002845 const size_t sub_len = end - start;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002846 if (start != 0)
2847 strm.EOL();
2848 if (!first_line)
2849 strm.Indent();
2850 else
2851 first_line = false;
2852 assert (start <= final_end);
2853 assert (start + sub_len <= final_end);
2854 if (sub_len > 0)
2855 strm.Write (text + start, sub_len);
2856 start = end + 1;
2857 }
2858 }
2859 strm.EOL();
2860 strm.IndentLess(indent_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002861}
2862
2863void
Enrico Granata82a7d982011-07-07 00:38:40 +00002864CommandInterpreter::OutputHelpText (Stream &strm,
2865 const char *word_text,
2866 const char *separator,
2867 const char *help_text,
2868 uint32_t max_word_len)
2869{
2870 int indent_size = max_word_len + strlen (separator) + 2;
2871
2872 strm.IndentMore (indent_size);
2873
2874 StreamString text_strm;
2875 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2876
2877 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata82a7d982011-07-07 00:38:40 +00002878
2879 size_t len = text_strm.GetSize();
2880 const char *text = text_strm.GetData();
2881
2882 uint32_t chars_left = max_columns;
2883
2884 for (uint32_t i = 0; i < len; i++)
2885 {
2886 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2887 {
Enrico Granata82a7d982011-07-07 00:38:40 +00002888 chars_left = max_columns - indent_size;
2889 strm.EOL();
2890 strm.Indent();
2891 }
2892 else
2893 {
2894 strm.PutChar(text[i]);
2895 chars_left--;
2896 }
2897
2898 }
2899
2900 strm.EOL();
2901 strm.IndentLess(indent_size);
2902}
2903
2904void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002905CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
Jim Inghamaf3753e2013-05-17 01:30:37 +00002906 StringList &commands_help, bool search_builtin_commands, bool search_user_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002907{
2908 CommandObject::CommandMap::const_iterator pos;
2909
Jim Inghamaf3753e2013-05-17 01:30:37 +00002910 if (search_builtin_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002911 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00002912 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002913 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00002914 const char *command_name = pos->first.c_str();
2915 CommandObject *cmd_obj = pos->second.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002916
Jim Inghamaf3753e2013-05-17 01:30:37 +00002917 if (cmd_obj->HelpTextContainsWord (search_word))
2918 {
2919 commands_found.AppendString (command_name);
2920 commands_help.AppendString (cmd_obj->GetHelp());
2921 }
2922
2923 if (cmd_obj->IsMultiwordObject())
2924 cmd_obj->AproposAllSubCommands (command_name,
2925 search_word,
2926 commands_found,
2927 commands_help);
2928
2929 }
2930 }
2931
2932 if (search_user_commands)
2933 {
2934 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
2935 {
2936 const char *command_name = pos->first.c_str();
2937 CommandObject *cmd_obj = pos->second.get();
2938
2939 if (cmd_obj->HelpTextContainsWord (search_word))
2940 {
2941 commands_found.AppendString (command_name);
2942 commands_help.AppendString (cmd_obj->GetHelp());
2943 }
2944
2945 if (cmd_obj->IsMultiwordObject())
2946 cmd_obj->AproposAllSubCommands (command_name,
2947 search_word,
2948 commands_found,
2949 commands_help);
2950
2951 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002952 }
2953}
Greg Clayton8b82f082011-04-12 05:54:46 +00002954
Greg Clayton8b82f082011-04-12 05:54:46 +00002955void
2956CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2957{
Ed Masted78c9572014-04-20 00:31:37 +00002958 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00002959 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002960 m_exe_ctx_ref = *override_context;
Greg Clayton8b82f082011-04-12 05:54:46 +00002961 }
2962 else
2963 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002964 const bool adopt_selected = true;
2965 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Clayton8b82f082011-04-12 05:54:46 +00002966 }
2967}
Greg Clayton44d93782014-01-27 23:43:24 +00002968
2969
2970size_t
2971CommandInterpreter::GetProcessOutput ()
2972{
2973 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
2974 char stdio_buffer[1024];
2975 size_t len;
2976 size_t total_bytes = 0;
2977 Error error;
2978 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
2979 if (target_sp)
2980 {
2981 ProcessSP process_sp (target_sp->GetProcessSP());
2982 if (process_sp)
2983 {
2984 while ((len = process_sp->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2985 {
2986 size_t bytes_written = len;
2987 m_debugger.GetOutputFile()->Write (stdio_buffer, bytes_written);
2988 total_bytes += len;
2989 }
2990 while ((len = process_sp->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2991 {
2992 size_t bytes_written = len;
2993 m_debugger.GetErrorFile()->Write (stdio_buffer, bytes_written);
2994 total_bytes += len;
2995 }
2996 }
2997 }
2998 return total_bytes;
2999}
3000
3001void
3002CommandInterpreter::IOHandlerInputComplete (IOHandler &io_handler, std::string &line)
3003{
Greg Clayton340b0302014-02-05 17:57:57 +00003004 const bool is_interactive = io_handler.GetIsInteractive();
3005 if (is_interactive == false)
3006 {
3007 // When we are not interactive, don't execute blank lines. This will happen
3008 // sourcing a commands file. We don't want blank lines to repeat the previous
3009 // command and cause any errors to occur (like redefining an alias, get an error
3010 // and stop parsing the commands file).
3011 if (line.empty())
3012 return;
3013
3014 // When using a non-interactive file handle (like when sourcing commands from a file)
3015 // we need to echo the command out so we don't just see the command output and no
3016 // command...
3017 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
3018 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(), line.c_str());
3019 }
3020
Greg Clayton44d93782014-01-27 23:43:24 +00003021 lldb_private::CommandReturnObject result;
3022 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
3023
Greg Clayton44d93782014-01-27 23:43:24 +00003024 // Now emit the command output text from the command we just executed
Greg Clayton340b0302014-02-05 17:57:57 +00003025 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult))
3026 {
3027 // Display any STDOUT/STDERR _prior_ to emitting the command result text
3028 GetProcessOutput ();
3029
Greg Clayton8ee67312014-02-05 21:46:20 +00003030 if (!result.GetImmediateOutputStream())
3031 {
3032 const char *output = result.GetOutputData();
3033 if (output && output[0])
3034 io_handler.GetOutputStreamFile()->PutCString(output);
3035 }
Greg Clayton44d93782014-01-27 23:43:24 +00003036
Greg Clayton340b0302014-02-05 17:57:57 +00003037 // Now emit the command error text from the command we just executed
Greg Clayton8ee67312014-02-05 21:46:20 +00003038 if (!result.GetImmediateErrorStream())
3039 {
3040 const char *error = result.GetErrorData();
3041 if (error && error[0])
3042 io_handler.GetErrorStreamFile()->PutCString(error);
3043 }
Greg Clayton340b0302014-02-05 17:57:57 +00003044 }
Greg Clayton44d93782014-01-27 23:43:24 +00003045
3046 switch (result.GetStatus())
3047 {
3048 case eReturnStatusInvalid:
3049 case eReturnStatusSuccessFinishNoResult:
3050 case eReturnStatusSuccessFinishResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003051 case eReturnStatusStarted:
3052 break;
3053
Greg Clayton44d93782014-01-27 23:43:24 +00003054 case eReturnStatusSuccessContinuingNoResult:
3055 case eReturnStatusSuccessContinuingResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003056 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
3057 io_handler.SetIsDone(true);
3058 break;
3059
Greg Clayton44d93782014-01-27 23:43:24 +00003060 case eReturnStatusFailed:
Greg Clayton340b0302014-02-05 17:57:57 +00003061 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
3062 io_handler.SetIsDone(true);
Greg Clayton44d93782014-01-27 23:43:24 +00003063 break;
3064
3065 case eReturnStatusQuit:
3066 io_handler.SetIsDone(true);
3067 break;
3068 }
3069}
3070
Greg Claytonf0066ad2014-05-02 00:45:31 +00003071bool
3072CommandInterpreter::IOHandlerInterrupt (IOHandler &io_handler)
3073{
3074 ExecutionContext exe_ctx (GetExecutionContext());
3075 Process *process = exe_ctx.GetProcessPtr();
3076
3077 if (process)
3078 {
3079 StateType state = process->GetState();
3080 if (StateIsRunningState(state))
3081 {
3082 process->Halt();
3083 return true; // Don't do any updating when we are running
3084 }
3085 }
3086 return false;
3087}
3088
Greg Clayton44d93782014-01-27 23:43:24 +00003089void
3090CommandInterpreter::GetLLDBCommandsFromIOHandler (const char *prompt,
3091 IOHandlerDelegate &delegate,
3092 bool asynchronously,
3093 void *baton)
3094{
3095 Debugger &debugger = GetDebugger();
3096 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
3097 "lldb", // Name of input reader for history
3098 prompt, // Prompt
3099 true, // Get multiple lines
Greg Claytonf6913cd2014-03-07 00:53:24 +00003100 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003101 delegate)); // IOHandlerDelegate
3102
3103 if (io_handler_sp)
3104 {
3105 io_handler_sp->SetUserData (baton);
3106 if (asynchronously)
3107 debugger.PushIOHandler(io_handler_sp);
3108 else
3109 debugger.RunIOHandler(io_handler_sp);
3110 }
3111
3112}
3113
3114
3115void
3116CommandInterpreter::GetPythonCommandsFromIOHandler (const char *prompt,
3117 IOHandlerDelegate &delegate,
3118 bool asynchronously,
3119 void *baton)
3120{
3121 Debugger &debugger = GetDebugger();
3122 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
3123 "lldb-python", // Name of input reader for history
3124 prompt, // Prompt
3125 true, // Get multiple lines
Greg Claytonf6913cd2014-03-07 00:53:24 +00003126 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003127 delegate)); // IOHandlerDelegate
3128
3129 if (io_handler_sp)
3130 {
3131 io_handler_sp->SetUserData (baton);
3132 if (asynchronously)
3133 debugger.PushIOHandler(io_handler_sp);
3134 else
3135 debugger.RunIOHandler(io_handler_sp);
3136 }
3137
3138}
3139
3140bool
3141CommandInterpreter::IsActive ()
3142{
3143 return m_debugger.IsTopIOHandler (m_command_io_handler_sp);
3144}
3145
3146void
3147CommandInterpreter::RunCommandInterpreter(bool auto_handle_events,
3148 bool spawn_thread)
3149{
Greg Clayton380f3d82014-07-31 19:46:19 +00003150 // Only get one line at a time
3151 const bool multiple_lines = false;
3152
3153 // Always re-create the IOHandlerEditline in case the input
3154 // changed. The old instance might have had a non-interactive
3155 // input and now it does or vice versa.
3156 m_command_io_handler_sp.reset(new IOHandlerEditline (m_debugger,
3157 m_debugger.GetInputFile(),
3158 m_debugger.GetOutputFile(),
3159 m_debugger.GetErrorFile(),
3160 eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult,
3161 "lldb",
3162 m_debugger.GetPrompt(),
3163 multiple_lines,
3164 0, // Don't show line numbers
3165 *this));
Greg Clayton06357c92014-07-30 17:38:47 +00003166
Greg Clayton44d93782014-01-27 23:43:24 +00003167 m_debugger.PushIOHandler(m_command_io_handler_sp);
3168
3169 if (auto_handle_events)
3170 m_debugger.StartEventHandlerThread();
3171
3172 if (spawn_thread)
3173 {
3174 m_debugger.StartIOHandlerThread();
3175 }
3176 else
3177 {
3178 m_debugger.ExecuteIOHanders();
3179
3180 if (auto_handle_events)
3181 m_debugger.StopEventHandlerThread();
3182 }
3183
3184}
3185