blob: dd82da5bb65a6464bfb507f347a0f12af063eadb [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
Todd Fialacacde7d2014-09-27 16:54:22 +000052#ifndef LLDB_DISABLE_LIBEDIT
Greg Clayton44d93782014-01-27 23:43:24 +000053#include "lldb/Host/Editline.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000054#endif
Greg Clayton7fb56d02011-02-01 01:31:41 +000055#include "lldb/Host/Host.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000056#include "lldb/Host/HostInfo.h"
Enrico Granatab5887262012-10-29 21:18:03 +000057
58#include "lldb/Interpreter/Args.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000059#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000060#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000061#include "lldb/Interpreter/CommandReturnObject.h"
Enrico Granatab5887262012-10-29 21:18:03 +000062#include "lldb/Interpreter/Options.h"
63#include "lldb/Interpreter/ScriptInterpreterNone.h"
64#include "lldb/Interpreter/ScriptInterpreterPython.h"
65
66
Chris Lattner30fdc8d2010-06-08 16:52:24 +000067#include "lldb/Target/Process.h"
68#include "lldb/Target/Thread.h"
69#include "lldb/Target/TargetList.h"
70
Enrico Granatab5887262012-10-29 21:18:03 +000071#include "lldb/Utility/CleanUp.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000072
Zachary Turnera21fee02014-08-21 21:49:24 +000073#include "llvm/ADT/SmallString.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000074#include "llvm/ADT/STLExtras.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000075#include "llvm/Support/Path.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000076
Chris Lattner30fdc8d2010-06-08 16:52:24 +000077using namespace lldb;
78using namespace lldb_private;
79
Greg Clayton754a9362012-08-23 00:22:02 +000080
81static PropertyDefinition
82g_properties[] =
83{
Ed Masted78c9572014-04-20 00:31:37 +000084 { "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." },
85 { "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." },
86 { "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." },
87 { nullptr , OptionValue::eTypeInvalid, true, 0 , nullptr, nullptr, nullptr }
Greg Clayton754a9362012-08-23 00:22:02 +000088};
89
90enum
91{
Enrico Granatabcba2b22013-01-17 21:36:19 +000092 ePropertyExpandRegexAliases = 0,
Enrico Granata012d4fc2013-06-11 01:26:35 +000093 ePropertyPromptOnQuit = 1,
94 ePropertyStopCmdSourceOnError = 2
Greg Clayton754a9362012-08-23 00:22:02 +000095};
96
Jim Ingham4bddaeb2012-02-16 06:50:00 +000097ConstString &
98CommandInterpreter::GetStaticBroadcasterClass ()
99{
100 static ConstString class_name ("lldb.commandInterpreter");
101 return class_name;
102}
103
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000104CommandInterpreter::CommandInterpreter
105(
Greg Clayton66111032010-06-23 01:19:29 +0000106 Debugger &debugger,
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000107 ScriptLanguage script_language,
Greg Clayton66111032010-06-23 01:19:29 +0000108 bool synchronous_execution
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000109) :
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000110 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton754a9362012-08-23 00:22:02 +0000111 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton44d93782014-01-27 23:43:24 +0000112 IOHandlerDelegate (IOHandlerDelegate::Completion::LLDBCommand),
Greg Clayton66111032010-06-23 01:19:29 +0000113 m_debugger (debugger),
Greg Clayton6eee5aa2010-10-11 01:05:37 +0000114 m_synchronous_execution (synchronous_execution),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000115 m_skip_lldbinit_files (false),
Jim Ingham16e0c682011-08-12 23:34:31 +0000116 m_skip_app_init_files (false),
Jim Inghame16c50a2011-02-18 00:54:25 +0000117 m_script_interpreter_ap (),
Greg Clayton44d93782014-01-27 23:43:24 +0000118 m_command_io_handler_sp (),
Caroline Ticed61c10b2011-06-16 16:27:19 +0000119 m_comment_char ('#'),
Johnny Chen4ac1d9e2012-08-09 22:06:10 +0000120 m_batch_command_mode (false),
Enrico Granata5f5ab602012-05-31 01:09:06 +0000121 m_truncation_warning(eNoTruncation),
Jim Ingham26c7bf92014-10-11 00:38:27 +0000122 m_command_source_depth (0),
123 m_num_errors(0),
Jim Inghamffc9f1d2014-10-14 01:20:07 +0000124 m_quit_requested(false),
125 m_stopped_for_crash(false)
Jim Ingham26c7bf92014-10-11 00:38:27 +0000126
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000127{
Greg Clayton67cc0632012-08-22 17:17:09 +0000128 debugger.SetScriptLanguage (script_language);
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000129 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
130 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton67cc0632012-08-22 17:17:09 +0000131 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000132 CheckInWithManager ();
Greg Clayton754a9362012-08-23 00:22:02 +0000133 m_collection_sp->Initialize (g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000134}
135
Greg Clayton754a9362012-08-23 00:22:02 +0000136bool
137CommandInterpreter::GetExpandRegexAliases () const
138{
139 const uint32_t idx = ePropertyExpandRegexAliases;
Ed Masted78c9572014-04-20 00:31:37 +0000140 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000141}
142
Enrico Granatabcba2b22013-01-17 21:36:19 +0000143bool
144CommandInterpreter::GetPromptOnQuit () const
145{
146 const uint32_t idx = ePropertyPromptOnQuit;
Ed Masted78c9572014-04-20 00:31:37 +0000147 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000148}
Greg Clayton754a9362012-08-23 00:22:02 +0000149
Enrico Granata012d4fc2013-06-11 01:26:35 +0000150bool
151CommandInterpreter::GetStopCmdSourceOnError () const
152{
153 const uint32_t idx = ePropertyStopCmdSourceOnError;
Ed Masted78c9572014-04-20 00:31:37 +0000154 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000155}
156
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000157void
158CommandInterpreter::Initialize ()
159{
160 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
161
162 CommandReturnObject result;
163
164 LoadCommandDictionary ();
165
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000166 // Set up some initial aliases.
Caroline Ticeca90c472011-05-06 21:37:15 +0000167 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
168 if (cmd_obj_sp)
169 {
170 AddAlias ("q", cmd_obj_sp);
171 AddAlias ("exit", cmd_obj_sp);
172 }
Sean Callanan247e62a2012-05-04 23:15:02 +0000173
Johnny Chen6d675242012-08-24 18:15:45 +0000174 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callanan247e62a2012-05-04 23:15:02 +0000175 if (cmd_obj_sp)
176 {
177 AddAlias ("attach", cmd_obj_sp);
178 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000179
Johnny Chen6d675242012-08-24 18:15:45 +0000180 cmd_obj_sp = GetCommandSPExact ("process detach",false);
181 if (cmd_obj_sp)
182 {
183 AddAlias ("detach", cmd_obj_sp);
184 }
185
Caroline Ticeca90c472011-05-06 21:37:15 +0000186 cmd_obj_sp = GetCommandSPExact ("process continue", false);
187 if (cmd_obj_sp)
188 {
189 AddAlias ("c", cmd_obj_sp);
190 AddAlias ("continue", cmd_obj_sp);
191 }
192
193 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
194 if (cmd_obj_sp)
195 AddAlias ("b", cmd_obj_sp);
196
Jim Inghamca36cd12012-10-05 19:16:31 +0000197 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
198 if (cmd_obj_sp)
199 AddAlias ("tbreak", cmd_obj_sp);
200
Caroline Ticeca90c472011-05-06 21:37:15 +0000201 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
202 if (cmd_obj_sp)
Jason Molendaf385f122011-10-22 00:47:41 +0000203 {
204 AddAlias ("stepi", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000205 AddAlias ("si", cmd_obj_sp);
Jason Molendaf385f122011-10-22 00:47:41 +0000206 }
207
208 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
209 if (cmd_obj_sp)
210 {
211 AddAlias ("nexti", cmd_obj_sp);
212 AddAlias ("ni", cmd_obj_sp);
213 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000214
215 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
216 if (cmd_obj_sp)
217 {
218 AddAlias ("s", cmd_obj_sp);
219 AddAlias ("step", cmd_obj_sp);
220 }
221
222 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
223 if (cmd_obj_sp)
224 {
225 AddAlias ("n", cmd_obj_sp);
226 AddAlias ("next", cmd_obj_sp);
227 }
228
229 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
230 if (cmd_obj_sp)
231 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000232 AddAlias ("finish", cmd_obj_sp);
233 }
234
Jim Ingham6d6d1072011-12-02 01:12:59 +0000235 cmd_obj_sp = GetCommandSPExact ("frame select", false);
236 if (cmd_obj_sp)
237 {
238 AddAlias ("f", cmd_obj_sp);
239 }
240
Jim Inghamca36cd12012-10-05 19:16:31 +0000241 cmd_obj_sp = GetCommandSPExact ("thread select", false);
242 if (cmd_obj_sp)
243 {
244 AddAlias ("t", cmd_obj_sp);
245 }
246
Richard Mittonf86248d2013-09-12 02:20:34 +0000247 cmd_obj_sp = GetCommandSPExact ("_regexp-jump",false);
248 if (cmd_obj_sp)
249 {
250 AddAlias ("j", cmd_obj_sp);
251 AddAlias ("jump", cmd_obj_sp);
252 }
253
Greg Clayton6bade322013-02-01 23:33:03 +0000254 cmd_obj_sp = GetCommandSPExact ("_regexp-list", false);
Caroline Ticeca90c472011-05-06 21:37:15 +0000255 if (cmd_obj_sp)
256 {
257 AddAlias ("l", cmd_obj_sp);
258 AddAlias ("list", cmd_obj_sp);
259 }
260
Greg Claytonef5651d2013-02-12 18:52:24 +0000261 cmd_obj_sp = GetCommandSPExact ("_regexp-env", false);
262 if (cmd_obj_sp)
263 {
264 AddAlias ("env", cmd_obj_sp);
265 }
266
Caroline Ticeca90c472011-05-06 21:37:15 +0000267 cmd_obj_sp = GetCommandSPExact ("memory read", false);
268 if (cmd_obj_sp)
269 AddAlias ("x", cmd_obj_sp);
270
271 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
272 if (cmd_obj_sp)
273 AddAlias ("up", cmd_obj_sp);
274
275 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
276 if (cmd_obj_sp)
277 AddAlias ("down", cmd_obj_sp);
278
Jason Molenda0c8e0062011-10-25 02:11:20 +0000279 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000280 if (cmd_obj_sp)
281 AddAlias ("display", cmd_obj_sp);
Jim Ingham7e18e422011-10-24 18:37:00 +0000282
283 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
284 if (cmd_obj_sp)
285 AddAlias ("dis", cmd_obj_sp);
286
287 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
288 if (cmd_obj_sp)
289 AddAlias ("di", cmd_obj_sp);
290
291
Jason Molendabc7748b2011-10-22 01:30:52 +0000292
Jason Molenda0c8e0062011-10-25 02:11:20 +0000293 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000294 if (cmd_obj_sp)
295 AddAlias ("undisplay", cmd_obj_sp);
296
Jim Ingham71bf2992012-10-10 16:51:31 +0000297 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
298 if (cmd_obj_sp)
299 AddAlias ("bt", cmd_obj_sp);
300
Caroline Ticeca90c472011-05-06 21:37:15 +0000301 cmd_obj_sp = GetCommandSPExact ("target create", false);
302 if (cmd_obj_sp)
303 AddAlias ("file", cmd_obj_sp);
304
305 cmd_obj_sp = GetCommandSPExact ("target modules", false);
306 if (cmd_obj_sp)
307 AddAlias ("image", cmd_obj_sp);
308
309
310 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghamffba2292011-03-22 02:29:32 +0000311
Caroline Ticeca90c472011-05-06 21:37:15 +0000312 cmd_obj_sp = GetCommandSPExact ("expression", false);
313 if (cmd_obj_sp)
Sean Callanan90e579f2013-04-17 17:23:58 +0000314 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000315 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
316 AddAlias ("p", cmd_obj_sp);
317 AddAlias ("print", cmd_obj_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000318 AddAlias ("call", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000319 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
320 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000321 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000322
323 alias_arguments_vector_sp.reset (new OptionArgVector);
Greg Clayton9e57dcd2013-05-15 01:03:08 +0000324 ProcessAliasOptionsArgs (cmd_obj_sp, "-O -- ", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000325 AddAlias ("po", cmd_obj_sp);
326 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
327 }
328
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000329 cmd_obj_sp = GetCommandSPExact ("process kill", false);
330 if (cmd_obj_sp)
Greg Claytone86fd742012-09-27 00:02:27 +0000331 {
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000332 AddAlias ("kill", cmd_obj_sp);
Greg Claytone86fd742012-09-27 00:02:27 +0000333 }
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000334
Caroline Ticeca90c472011-05-06 21:37:15 +0000335 cmd_obj_sp = GetCommandSPExact ("process launch", false);
336 if (cmd_obj_sp)
337 {
338 alias_arguments_vector_sp.reset (new OptionArgVector);
Todd Fiala013434e2014-07-09 01:29:05 +0000339#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Jason Molenda85da3122012-07-06 02:46:23 +0000340 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
341#else
Zachary Turner10687b02014-10-20 17:46:43 +0000342 std::string shell_option;
343 shell_option.append("--shell=");
344 shell_option.append(HostInfo::GetDefaultShell().GetPath());
345 shell_option.append(" --");
346 ProcessAliasOptionsArgs (cmd_obj_sp, shell_option.c_str(), alias_arguments_vector_sp);
Jason Molenda85da3122012-07-06 02:46:23 +0000347#endif
Caroline Ticeca90c472011-05-06 21:37:15 +0000348 AddAlias ("r", cmd_obj_sp);
349 AddAlias ("run", cmd_obj_sp);
350 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
351 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
352 }
Greg Clayton843d62d2012-03-29 21:47:51 +0000353
354 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
355 if (cmd_obj_sp)
356 {
357 AddAlias ("add-dsym", cmd_obj_sp);
358 }
Sean Callananfc732752012-05-21 18:25:19 +0000359
360 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
361 if (cmd_obj_sp)
362 {
363 alias_arguments_vector_sp.reset (new OptionArgVector);
364 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
Jim Ingham06d282d2012-10-18 23:24:12 +0000365 AddAlias ("rbreak", cmd_obj_sp);
366 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
Sean Callananfc732752012-05-21 18:25:19 +0000367 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000368}
369
Greg Clayton0c4129f2014-04-25 00:35:14 +0000370void
371CommandInterpreter::Clear()
372{
373 m_command_io_handler_sp.reset();
Greg Claytoned6499f2014-04-25 23:55:12 +0000374
375 if (m_script_interpreter_ap)
376 m_script_interpreter_ap->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000377}
378
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000379const char *
380CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
381{
382 // This function has not yet been implemented.
383
384 // Look for any embedded script command
385 // If found,
386 // get interpreter object from the command dictionary,
387 // call execute_one_command on it,
388 // get the results as a string,
389 // substitute that string for current stuff.
390
391 return arg;
392}
393
394
395void
396CommandInterpreter::LoadCommandDictionary ()
397{
398 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
399
Caroline Ticedaccaa92010-09-20 20:44:43 +0000400 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000401
Greg Claytona7015092010-09-18 01:14:36 +0000402 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000403 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Johnny Chenb89982d2011-04-21 00:39:18 +0000404 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000405 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
406 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000407 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton44d93782014-01-27 23:43:24 +0000408 m_command_dict["gui"] = CommandObjectSP (new CommandObjectGUI (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000409 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000410 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
411 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonded470d2011-03-19 01:12:21 +0000412 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata21dfcd92012-09-28 23:57:51 +0000413 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000414 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000415 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000416 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000417 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000418 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Inghamebc09c32010-07-07 03:36:20 +0000419 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000420 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
421 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata223383e2011-08-16 23:24:13 +0000422 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen31c39da2010-12-23 20:21:44 +0000423 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chenf04ee932011-09-22 18:04:58 +0000424 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000425
Jim Inghamca36cd12012-10-05 19:16:31 +0000426 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
Greg Claytond90ac932014-12-01 22:34:03 +0000427 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000428 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
Greg Clayton722e8852013-02-08 02:54:24 +0000429 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
Greg Clayton1b3815c2013-01-30 00:18:29 +0000430 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000431 {"^(-.*)$", "breakpoint set %1"},
432 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
Greg Clayton722e8852013-02-08 02:54:24 +0000433 {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"},
Greg Clayton2d4b5122014-08-14 17:58:33 +0000434 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"}};
Jim Inghamca36cd12012-10-05 19:16:31 +0000435
Saleem Abdulrasool28606952014-06-27 05:17:41 +0000436 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000437
Greg Clayton7b0992d2013-04-18 22:45:39 +0000438 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytona7015092010-09-18 01:14:36 +0000439 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000440 "_regexp-break",
Johnny Chenb417dcd2012-08-23 00:32:22 +0000441 "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 +0000442 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
443 2,
444 CommandCompletions::eSymbolCompletion |
Greg Claytonb5472782015-01-09 19:08:20 +0000445 CommandCompletions::eSourceFileCompletion,
446 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000447
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000448 if (break_regex_cmd_ap.get())
449 {
Jim Inghamca36cd12012-10-05 19:16:31 +0000450 bool success = true;
451 for (size_t i = 0; i < num_regexes; i++)
452 {
453 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
454 if (!success)
455 break;
456 }
457 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
458
459 if (success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000460 {
461 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
462 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
463 }
464 }
Jim Inghamffba2292011-03-22 02:29:32 +0000465
Greg Clayton7b0992d2013-04-18 22:45:39 +0000466 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamca36cd12012-10-05 19:16:31 +0000467 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
468 "_regexp-tbreak",
469 "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 +0000470 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
471 2,
472 CommandCompletions::eSymbolCompletion |
Greg Claytonb5472782015-01-09 19:08:20 +0000473 CommandCompletions::eSourceFileCompletion,
474 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000475
476 if (tbreak_regex_cmd_ap.get())
477 {
478 bool success = true;
479 for (size_t i = 0; i < num_regexes; i++)
480 {
481 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
482 char buffer[1024];
483 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
484 assert (num_printed < 1024);
Eric Christopher5c91d5c12014-09-09 19:26:45 +0000485 // Quiet unused variable warning for release builds.
Eric Christopher9ad83942014-09-09 08:57:33 +0000486 (void) num_printed;
Jim Inghamca36cd12012-10-05 19:16:31 +0000487 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
488 if (!success)
489 break;
490 }
491 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
492
493 if (success)
494 {
495 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
496 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
497 }
498 }
499
Greg Clayton7b0992d2013-04-18 22:45:39 +0000500 std::unique_ptr<CommandObjectRegexCommand>
Johnny Chen6d675242012-08-24 18:15:45 +0000501 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
502 "_regexp-attach",
503 "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 +0000504 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]",
Greg Claytonb5472782015-01-09 19:08:20 +0000505 2,
506 0,
507 false));
Johnny Chen6d675242012-08-24 18:15:45 +0000508 if (attach_regex_cmd_ap.get())
509 {
Greg Clayton3cb4c7d2012-12-15 01:19:07 +0000510 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
511 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
512 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
513 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
Johnny Chen6d675242012-08-24 18:15:45 +0000514 {
515 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
516 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_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 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000522 "_regexp-down",
523 "Go down \"n\" frames in the stack (1 frame by default).",
Greg Claytonb5472782015-01-09 19:08:20 +0000524 "_regexp-down [n]",
525 2,
526 0,
527 false));
Jim Inghamffba2292011-03-22 02:29:32 +0000528 if (down_regex_cmd_ap.get())
529 {
530 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
531 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
532 {
533 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
534 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
535 }
536 }
537
Greg Clayton7b0992d2013-04-18 22:45:39 +0000538 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000539 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000540 "_regexp-up",
541 "Go up \"n\" frames in the stack (1 frame by default).",
Greg Claytonb5472782015-01-09 19:08:20 +0000542 "_regexp-up [n]",
543 2,
544 0,
545 false));
Jim Inghamffba2292011-03-22 02:29:32 +0000546 if (up_regex_cmd_ap.get())
547 {
548 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
549 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
550 {
551 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
552 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
553 }
554 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000555
Greg Clayton7b0992d2013-04-18 22:45:39 +0000556 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000557 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000558 "_regexp-display",
559 "Add an expression evaluation stop-hook.",
Greg Claytonb5472782015-01-09 19:08:20 +0000560 "_regexp-display expression",
561 2,
562 0,
563 false));
Jason Molendabc7748b2011-10-22 01:30:52 +0000564 if (display_regex_cmd_ap.get())
565 {
566 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
567 {
568 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
569 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
570 }
571 }
572
Greg Clayton7b0992d2013-04-18 22:45:39 +0000573 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000574 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000575 "_regexp-undisplay",
576 "Remove an expression evaluation stop-hook.",
Greg Claytonb5472782015-01-09 19:08:20 +0000577 "_regexp-undisplay stop-hook-number",
578 2,
579 0,
580 false));
Jason Molendabc7748b2011-10-22 01:30:52 +0000581 if (undisplay_regex_cmd_ap.get())
582 {
583 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
584 {
585 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
586 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
587 }
588 }
589
Greg Clayton7b0992d2013-04-18 22:45:39 +0000590 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000591 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000592 "gdb-remote",
593 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
Greg Claytonb5472782015-01-09 19:08:20 +0000594 "gdb-remote [<hostname>:]<portnum>",
595 2,
596 0,
597 false));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000598 if (connect_gdb_remote_cmd_ap.get())
599 {
600 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
601 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
602 {
603 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
604 m_command_dict[command_sp->GetCommandName ()] = command_sp;
605 }
606 }
607
Greg Clayton7b0992d2013-04-18 22:45:39 +0000608 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000609 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
610 "kdp-remote",
Jason Molendaa7dcb332012-10-23 03:05:16 +0000611 "Connect to a remote KDP server. udp port 41139 is the default port number.",
Greg Claytonb5472782015-01-09 19:08:20 +0000612 "kdp-remote <hostname>[:<portnum>]",
613 2,
614 0,
615 false));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000616 if (connect_kdp_remote_cmd_ap.get())
617 {
618 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molendac36b1842012-09-27 02:47:55 +0000619 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000620 {
621 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
622 m_command_dict[command_sp->GetCommandName ()] = command_sp;
623 }
624 }
625
Greg Clayton7b0992d2013-04-18 22:45:39 +0000626 std::unique_ptr<CommandObjectRegexCommand>
Jason Molenda4cddfed2012-10-05 05:29:32 +0000627 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb5472782015-01-09 19:08:20 +0000628 "_regexp-bt",
629 "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.",
630 "bt [<digit>|all]",
631 2,
632 0,
633 false));
Jason Molenda4cddfed2012-10-05 05:29:32 +0000634 if (bt_regex_cmd_ap.get())
635 {
636 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
637 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
638 // so now "bt 3" is the preferred form, in line with gdb.
639 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
640 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
641 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
642 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
643 {
644 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
645 m_command_dict[command_sp->GetCommandName ()] = command_sp;
646 }
647 }
648
Greg Clayton7b0992d2013-04-18 22:45:39 +0000649 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton6bade322013-02-01 23:33:03 +0000650 list_regex_cmd_ap(new CommandObjectRegexCommand (*this,
651 "_regexp-list",
652 "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 +0000653 "_regexp-list [<line>]\n_regexp-list [<file>:<line>]\n_regexp-list [<file>:<line>]",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000654 2,
Greg Claytonb5472782015-01-09 19:08:20 +0000655 CommandCompletions::eSourceFileCompletion,
656 false));
Greg Clayton6bade322013-02-01 23:33:03 +0000657 if (list_regex_cmd_ap.get())
658 {
659 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") &&
660 list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") &&
661 list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") &&
Greg Claytond9010962013-02-12 18:42:05 +0000662 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") &&
Greg Claytone4ca5152013-03-13 18:25:49 +0000663 list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") &&
Greg Clayton6bade322013-02-01 23:33:03 +0000664 list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") &&
665 list_regex_cmd_ap->AddRegexCommand("^$", "source list"))
666 {
667 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
668 m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp;
669 }
670 }
671
Greg Clayton7b0992d2013-04-18 22:45:39 +0000672 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytonef5651d2013-02-12 18:52:24 +0000673 env_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000674 "_regexp-env",
675 "Implements a shortcut to viewing and setting environment variables.",
Greg Claytonb5472782015-01-09 19:08:20 +0000676 "_regexp-env\n_regexp-env FOO=BAR",
677 2,
678 0,
679 false));
Greg Claytonef5651d2013-02-12 18:52:24 +0000680 if (env_regex_cmd_ap.get())
681 {
682 if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") &&
683 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1"))
684 {
685 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
686 m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp;
687 }
688 }
689
Richard Mittonf86248d2013-09-12 02:20:34 +0000690 std::unique_ptr<CommandObjectRegexCommand>
691 jump_regex_cmd_ap(new CommandObjectRegexCommand (*this,
692 "_regexp-jump",
693 "Sets the program counter to a new address.",
694 "_regexp-jump [<line>]\n"
695 "_regexp-jump [<+-lineoffset>]\n"
696 "_regexp-jump [<file>:<line>]\n"
Greg Claytonb5472782015-01-09 19:08:20 +0000697 "_regexp-jump [*<addr>]\n",
698 2,
699 0,
700 false));
Richard Mittonf86248d2013-09-12 02:20:34 +0000701 if (jump_regex_cmd_ap.get())
702 {
703 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") &&
704 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") &&
705 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") &&
706 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1"))
707 {
708 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
709 m_command_dict[jump_regex_cmd_sp->GetCommandName ()] = jump_regex_cmd_sp;
710 }
711 }
712
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000713}
714
715int
716CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
717 StringList &matches)
718{
719 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
720
721 if (include_aliases)
722 {
723 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
724 }
725
726 return matches.GetSize();
727}
728
729CommandObjectSP
730CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
731{
732 CommandObject::CommandMap::iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +0000733 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000734
735 std::string cmd(cmd_cstr);
736
737 if (HasCommands())
738 {
739 pos = m_command_dict.find(cmd);
740 if (pos != m_command_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000741 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742 }
743
744 if (include_aliases && HasAliases())
745 {
746 pos = m_alias_dict.find(cmd);
747 if (pos != m_alias_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000748 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000749 }
750
751 if (HasUserCommands())
752 {
753 pos = m_user_dict.find(cmd);
754 if (pos != m_user_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000755 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000756 }
757
Greg Claytonc7bece562013-01-25 18:06:21 +0000758 if (!exact && !command_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000759 {
Jim Ingham279a6c22010-07-06 22:46:59 +0000760 // We will only get into here if we didn't find any exact matches.
761
762 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
763
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000764 StringList local_matches;
Ed Masted78c9572014-04-20 00:31:37 +0000765 if (matches == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000766 matches = &local_matches;
767
Jim Ingham279a6c22010-07-06 22:46:59 +0000768 unsigned int num_cmd_matches = 0;
769 unsigned int num_alias_matches = 0;
770 unsigned int num_user_matches = 0;
771
772 // Look through the command dictionaries one by one, and if we get only one match from any of
773 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
774
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000775 if (HasCommands())
776 {
777 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
778 }
779
780 if (num_cmd_matches == 1)
781 {
782 cmd.assign(matches->GetStringAtIndex(0));
783 pos = m_command_dict.find(cmd);
784 if (pos != m_command_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000785 real_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000786 }
787
Jim Ingham490ac552010-06-24 20:28:42 +0000788 if (include_aliases && HasAliases())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000789 {
790 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
791
792 }
793
Jim Ingham279a6c22010-07-06 22:46:59 +0000794 if (num_alias_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795 {
796 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
797 pos = m_alias_dict.find(cmd);
798 if (pos != m_alias_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000799 alias_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000800 }
801
Jim Ingham490ac552010-06-24 20:28:42 +0000802 if (HasUserCommands())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000803 {
804 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
805 }
806
Jim Ingham279a6c22010-07-06 22:46:59 +0000807 if (num_user_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000808 {
809 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
810
811 pos = m_user_dict.find (cmd);
812 if (pos != m_user_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000813 user_match_sp = pos->second;
814 }
815
816 // If we got exactly one match, return that, otherwise return the match list.
817
818 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
819 {
820 if (num_cmd_matches)
821 return real_match_sp;
822 else if (num_alias_matches)
823 return alias_match_sp;
824 else
825 return user_match_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000826 }
827 }
Greg Claytonc7bece562013-01-25 18:06:21 +0000828 else if (matches && command_sp)
Jim Ingham279a6c22010-07-06 22:46:59 +0000829 {
830 matches->AppendString (cmd_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000831 }
832
833
Greg Claytonc7bece562013-01-25 18:06:21 +0000834 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000835}
836
Greg Claytonde164aa2011-04-20 16:37:46 +0000837bool
838CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
839{
840 if (name && name[0])
841 {
842 std::string name_sstr(name);
Enrico Granatae00af802012-10-01 17:19:37 +0000843 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
844 if (found && !can_replace)
845 return false;
846 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata21dfcd92012-09-28 23:57:51 +0000847 return false;
Greg Claytonde164aa2011-04-20 16:37:46 +0000848 m_command_dict[name_sstr] = cmd_sp;
849 return true;
850 }
851 return false;
852}
853
Enrico Granata223383e2011-08-16 23:24:13 +0000854bool
Enrico Granata0a305db2011-11-07 22:57:04 +0000855CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata223383e2011-08-16 23:24:13 +0000856 const lldb::CommandObjectSP &cmd_sp,
857 bool can_replace)
858{
Enrico Granata0a305db2011-11-07 22:57:04 +0000859 if (!name.empty())
Enrico Granata223383e2011-08-16 23:24:13 +0000860 {
Enrico Granata0a305db2011-11-07 22:57:04 +0000861
862 const char* name_cstr = name.c_str();
863
864 // do not allow replacement of internal commands
865 if (CommandExists(name_cstr))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000866 {
867 if (can_replace == false)
868 return false;
869 if (m_command_dict[name]->IsRemovable() == false)
870 return false;
871 }
Enrico Granata0a305db2011-11-07 22:57:04 +0000872
Enrico Granata21dfcd92012-09-28 23:57:51 +0000873 if (UserCommandExists(name_cstr))
874 {
875 if (can_replace == false)
876 return false;
877 if (m_user_dict[name]->IsRemovable() == false)
878 return false;
879 }
880
Enrico Granata0a305db2011-11-07 22:57:04 +0000881 m_user_dict[name] = cmd_sp;
Enrico Granata223383e2011-08-16 23:24:13 +0000882 return true;
883 }
884 return false;
885}
Greg Claytonde164aa2011-04-20 16:37:46 +0000886
Jim Ingham279a6c22010-07-06 22:46:59 +0000887CommandObjectSP
888CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000889{
Caroline Tice472362e2010-12-14 18:51:39 +0000890 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
891 CommandObjectSP ret_val; // Possibly empty return value.
892
Ed Masted78c9572014-04-20 00:31:37 +0000893 if (cmd_cstr == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000894 return ret_val;
895
896 if (cmd_words.GetArgumentCount() == 1)
Ed Masted78c9572014-04-20 00:31:37 +0000897 return GetCommandSP(cmd_cstr, include_aliases, true, nullptr);
Caroline Tice472362e2010-12-14 18:51:39 +0000898 else
899 {
900 // We have a multi-word command (seemingly), so we need to do more work.
901 // First, get the cmd_obj_sp for the first word in the command.
Ed Masted78c9572014-04-20 00:31:37 +0000902 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, nullptr);
903 if (cmd_obj_sp.get() != nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000904 {
905 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
906 // command name), and find the appropriate sub-command SP for each command word....
907 size_t end = cmd_words.GetArgumentCount();
908 for (size_t j= 1; j < end; ++j)
909 {
910 if (cmd_obj_sp->IsMultiwordObject())
911 {
Greg Clayton998255b2012-10-13 02:07:45 +0000912 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Ed Masted78c9572014-04-20 00:31:37 +0000913 if (cmd_obj_sp.get() == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000914 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
915 return ret_val;
916 }
917 else
918 // We have more words in the command name, but we don't have a multiword object. Fail and return
919 // empty 'ret_val'.
920 return ret_val;
921 }
922 // We successfully looped through all the command words and got valid command objects for them. Assign the
923 // last object retrieved to 'ret_val'.
924 ret_val = cmd_obj_sp;
925 }
926 }
927 return ret_val;
Jim Ingham279a6c22010-07-06 22:46:59 +0000928}
929
930CommandObject *
931CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
932{
933 return GetCommandSPExact (cmd_cstr, include_aliases).get();
934}
935
936CommandObject *
937CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
938{
939 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
940
941 // If we didn't find an exact match to the command string in the commands, look in
942 // the aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000943
944 if (command_obj)
945 return command_obj;
Jim Ingham279a6c22010-07-06 22:46:59 +0000946
Enrico Granata5342c442013-06-18 18:01:08 +0000947 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
Jim Ingham279a6c22010-07-06 22:46:59 +0000948
Enrico Granata5342c442013-06-18 18:01:08 +0000949 if (command_obj)
950 return command_obj;
951
952 // If there wasn't an exact match then look for an inexact one in just the commands
Ed Masted78c9572014-04-20 00:31:37 +0000953 command_obj = GetCommandSP(cmd_cstr, false, false, nullptr).get();
Matt Kopec038ff812013-04-23 16:17:32 +0000954
955 // Finally, if there wasn't an inexact match among the commands, look for an inexact
956 // match in both the commands and aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000957
958 if (command_obj)
959 {
960 if (matches)
961 matches->AppendString(command_obj->GetCommandName());
962 return command_obj;
963 }
964
965 return GetCommandSP(cmd_cstr, true, false, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000966}
967
968bool
969CommandInterpreter::CommandExists (const char *cmd)
970{
971 return m_command_dict.find(cmd) != m_command_dict.end();
972}
973
974bool
Caroline Ticeca90c472011-05-06 21:37:15 +0000975CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
976 const char *options_args,
977 OptionArgVectorSP &option_arg_vector_sp)
978{
979 bool success = true;
980 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
981
982 if (!options_args || (strlen (options_args) < 1))
983 return true;
984
985 std::string options_string (options_args);
986 Args args (options_args);
987 CommandReturnObject result;
988 // Check to see if the command being aliased can take any command options.
989 Options *options = cmd_obj_sp->GetOptions ();
990 if (options)
991 {
992 // See if any options were specified as part of the alias; if so, handle them appropriately.
993 options->NotifyOptionParsingStarting ();
994 args.Unshift ("dummy_arg");
995 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
996 args.Shift ();
997 if (result.Succeeded())
998 options->VerifyPartialOptions (result);
999 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
1000 {
1001 result.AppendError ("Unable to create requested alias.\n");
1002 return false;
1003 }
1004 }
1005
Greg Clayton5521f992011-10-28 21:38:01 +00001006 if (!options_string.empty())
Caroline Ticeca90c472011-05-06 21:37:15 +00001007 {
1008 if (cmd_obj_sp->WantsRawCommandString ())
1009 option_arg_vector->push_back (OptionArgPair ("<argument>",
1010 OptionArgValue (-1,
1011 options_string)));
1012 else
1013 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001014 const size_t argc = args.GetArgumentCount();
Caroline Ticeca90c472011-05-06 21:37:15 +00001015 for (size_t i = 0; i < argc; ++i)
1016 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
1017 option_arg_vector->push_back
1018 (OptionArgPair ("<argument>",
1019 OptionArgValue (-1,
1020 std::string (args.GetArgumentAtIndex (i)))));
1021 }
1022 }
1023
1024 return success;
1025}
1026
1027bool
Jim Ingham298f3782013-04-03 00:25:49 +00001028CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name)
1029{
1030 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1031 if (exact_match)
1032 {
1033 full_name.assign(cmd);
1034 return exact_match;
1035 }
1036 else
1037 {
1038 StringList matches;
1039 size_t num_alias_matches;
1040 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches);
1041 if (num_alias_matches == 1)
1042 {
1043 // Make sure this isn't shadowing a command in the regular command space:
1044 StringList regular_matches;
1045 const bool include_aliases = false;
1046 const bool exact = false;
1047 CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, &regular_matches));
1048 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1049 return false;
1050 else
1051 {
1052 full_name.assign (matches.GetStringAtIndex(0));
1053 return true;
1054 }
1055 }
1056 else
1057 return false;
1058 }
1059}
1060
1061bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001062CommandInterpreter::AliasExists (const char *cmd)
1063{
1064 return m_alias_dict.find(cmd) != m_alias_dict.end();
1065}
1066
1067bool
1068CommandInterpreter::UserCommandExists (const char *cmd)
1069{
1070 return m_user_dict.find(cmd) != m_user_dict.end();
1071}
1072
1073void
1074CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
1075{
Jim Ingham279a6c22010-07-06 22:46:59 +00001076 command_obj_sp->SetIsAlias (true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001077 m_alias_dict[alias_name] = command_obj_sp;
1078}
1079
1080bool
1081CommandInterpreter::RemoveAlias (const char *alias_name)
1082{
1083 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
1084 if (pos != m_alias_dict.end())
1085 {
1086 m_alias_dict.erase(pos);
1087 return true;
1088 }
1089 return false;
1090}
Greg Claytonb5472782015-01-09 19:08:20 +00001091
1092bool
1093CommandInterpreter::RemoveCommand (const char *cmd)
1094{
1095 auto pos = m_command_dict.find(cmd);
1096 if (pos != m_command_dict.end())
1097 {
1098 if (pos->second->IsRemovable())
1099 {
1100 // Only regular expression objects or python commands are removable
1101 m_command_dict.erase(pos);
1102 return true;
1103 }
1104 }
1105 return false;
1106}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001107bool
1108CommandInterpreter::RemoveUser (const char *alias_name)
1109{
1110 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1111 if (pos != m_user_dict.end())
1112 {
1113 m_user_dict.erase(pos);
1114 return true;
1115 }
1116 return false;
1117}
1118
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001119void
1120CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
1121{
1122 help_string.Printf ("'%s", command_name);
1123 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1124
Sean Callanan9a028512012-08-09 00:50:26 +00001125 if (option_arg_vector_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001126 {
1127 OptionArgVector *options = option_arg_vector_sp.get();
Andy Gibbsa297a972013-06-19 19:04:53 +00001128 for (size_t i = 0; i < options->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001129 {
1130 OptionArgPair cur_option = (*options)[i];
1131 std::string opt = cur_option.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00001132 OptionArgValue value_pair = cur_option.second;
1133 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134 if (opt.compare("<argument>") == 0)
1135 {
1136 help_string.Printf (" %s", value.c_str());
1137 }
1138 else
1139 {
1140 help_string.Printf (" %s", opt.c_str());
1141 if ((value.compare ("<no-argument>") != 0)
1142 && (value.compare ("<need-argument") != 0))
1143 {
1144 help_string.Printf (" %s", value.c_str());
1145 }
1146 }
1147 }
1148 }
1149
1150 help_string.Printf ("'");
1151}
1152
Greg Clayton12fc3e02010-08-26 22:05:43 +00001153size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001154CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
1155{
1156 CommandObject::CommandMap::const_iterator pos;
Greg Clayton12fc3e02010-08-26 22:05:43 +00001157 CommandObject::CommandMap::const_iterator end = dict.end();
1158 size_t max_len = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001159
Greg Clayton12fc3e02010-08-26 22:05:43 +00001160 for (pos = dict.begin(); pos != end; ++pos)
1161 {
1162 size_t len = pos->first.size();
1163 if (max_len < len)
1164 max_len = len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001165 }
Greg Clayton12fc3e02010-08-26 22:05:43 +00001166 return max_len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001167}
1168
1169void
Enrico Granata223383e2011-08-16 23:24:13 +00001170CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata08633ee2011-09-09 17:49:36 +00001171 uint32_t cmd_types)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001172{
Kate Stonea487aa42015-01-15 00:52:41 +00001173 const char * help_prologue = GetDebugger().GetIOHandlerHelpPrologue();
1174 if (help_prologue != NULL)
1175 {
1176 OutputFormattedHelpText(result.GetOutputStream(), NULL, help_prologue);
1177 }
1178
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001179 CommandObject::CommandMap::const_iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +00001180 size_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata223383e2011-08-16 23:24:13 +00001181
1182 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001183 {
Kate Stonea487aa42015-01-15 00:52:41 +00001184 result.AppendMessage("Debugger commands:");
Enrico Granata223383e2011-08-16 23:24:13 +00001185 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001186
Enrico Granata223383e2011-08-16 23:24:13 +00001187 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1188 {
Kate Stonea487aa42015-01-15 00:52:41 +00001189 if (!(cmd_types & eCommandTypesHidden) && (pos->first.compare(0, 1, "_") == 0))
1190 continue;
1191
Enrico Granata223383e2011-08-16 23:24:13 +00001192 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1193 max_len);
1194 }
1195 result.AppendMessage("");
1196
1197 }
1198
Greg Clayton5521f992011-10-28 21:38:01 +00001199 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001200 {
Kate Stonea487aa42015-01-15 00:52:41 +00001201 result.AppendMessageWithFormat("Current command abbreviations "
1202 "(type '%shelp command alias' for more info):\n",
1203 GetCommandPrefix());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001204 result.AppendMessage("");
Greg Clayton12fc3e02010-08-26 22:05:43 +00001205 max_len = FindLongestCommandWord (m_alias_dict);
1206
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001207 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1208 {
1209 StreamString sstr;
1210 StreamString translation_and_help;
1211 std::string entry_name = pos->first;
1212 std::string second_entry = pos->second.get()->GetCommandName();
1213 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1214
1215 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1216 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1217 translation_and_help.GetData(), max_len);
1218 }
1219 result.AppendMessage("");
1220 }
1221
Greg Clayton5521f992011-10-28 21:38:01 +00001222 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001223 {
Kate Stonea487aa42015-01-15 00:52:41 +00001224 result.AppendMessage ("Current user-defined commands:");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001225 result.AppendMessage("");
Enrico Granata223383e2011-08-16 23:24:13 +00001226 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001227 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1228 {
Enrico Granata223383e2011-08-16 23:24:13 +00001229 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1230 max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001231 }
1232 result.AppendMessage("");
1233 }
1234
Kate Stonea487aa42015-01-15 00:52:41 +00001235 result.AppendMessageWithFormat("For more information on any command, type '%shelp <command-name>'.\n",
1236 GetCommandPrefix());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001237}
1238
Caroline Tice844d2302010-12-09 22:52:49 +00001239CommandObject *
1240CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001241{
Caroline Tice844d2302010-12-09 22:52:49 +00001242 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1243 // eventually be invoked by the given command line.
1244
Ed Masted78c9572014-04-20 00:31:37 +00001245 CommandObject *cmd_obj = nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001246 std::string white_space (" \t\v");
1247 size_t start = command_string.find_first_not_of (white_space);
1248 size_t end = 0;
1249 bool done = false;
1250 while (!done)
1251 {
1252 if (start != std::string::npos)
1253 {
1254 // Get the next word from command_string.
1255 end = command_string.find_first_of (white_space, start);
1256 if (end == std::string::npos)
1257 end = command_string.size();
1258 std::string cmd_word = command_string.substr (start, end - start);
1259
Ed Masted78c9572014-04-20 00:31:37 +00001260 if (cmd_obj == nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001261 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1262 // command or alias.
1263 cmd_obj = GetCommandObject (cmd_word.c_str());
1264 else if (cmd_obj->IsMultiwordObject ())
1265 {
1266 // 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 +00001267 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001268 if (sub_cmd_obj)
1269 cmd_obj = sub_cmd_obj;
1270 else // cmd_word was not a valid sub-command word, so we are donee
1271 done = true;
1272 }
1273 else
1274 // We have a cmd_obj and it is not a multi-word object, so we are done.
1275 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001276
Caroline Tice844d2302010-12-09 22:52:49 +00001277 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1278 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1279 // next word.
1280
1281 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1282 done = true;
1283 else
1284 start = command_string.find_first_not_of (white_space, end);
1285 }
1286 else
1287 // Unable to find any more words.
1288 done = true;
1289 }
1290
1291 if (end == command_string.size())
1292 command_string.clear();
1293 else
1294 command_string = command_string.substr(end);
1295
1296 return cmd_obj;
1297}
1298
Greg Clayton51964162011-10-25 00:36:27 +00001299static const char *k_white_space = " \t\v";
Greg Clayton5521f992011-10-28 21:38:01 +00001300static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton51964162011-10-25 00:36:27 +00001301static void
1302StripLeadingSpaces (std::string &s)
Caroline Tice844d2302010-12-09 22:52:49 +00001303{
Greg Clayton51964162011-10-25 00:36:27 +00001304 if (!s.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001305 {
Greg Clayton51964162011-10-25 00:36:27 +00001306 size_t pos = s.find_first_not_of (k_white_space);
1307 if (pos == std::string::npos)
1308 s.clear();
1309 else if (pos == 0)
1310 return;
1311 s.erase (0, pos);
1312 }
1313}
1314
Greg Clayton93c62e62011-11-09 23:25:03 +00001315static size_t
1316FindArgumentTerminator (const std::string &s)
1317{
Greg Clayton93c62e62011-11-09 23:25:03 +00001318 const size_t s_len = s.size();
1319 size_t offset = 0;
1320 while (offset < s_len)
1321 {
1322 size_t pos = s.find ("--", offset);
1323 if (pos == std::string::npos)
1324 break;
1325 if (pos > 0)
1326 {
1327 if (isspace(s[pos-1]))
1328 {
1329 // Check if the string ends "\s--" (where \s is a space character)
1330 // or if we have "\s--\s".
1331 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1332 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001333 return pos;
1334 }
1335 }
1336 }
1337 offset = pos + 2;
1338 }
Greg Clayton93c62e62011-11-09 23:25:03 +00001339 return std::string::npos;
1340}
1341
Greg Clayton51964162011-10-25 00:36:27 +00001342static bool
Greg Clayton5521f992011-10-28 21:38:01 +00001343ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton51964162011-10-25 00:36:27 +00001344{
Greg Clayton5521f992011-10-28 21:38:01 +00001345 command.clear();
1346 suffix.clear();
Greg Clayton51964162011-10-25 00:36:27 +00001347 StripLeadingSpaces (command_string);
1348
1349 bool result = false;
1350 quote_char = '\0';
1351
1352 if (!command_string.empty())
1353 {
1354 const char first_char = command_string[0];
1355 if (first_char == '\'' || first_char == '"')
Caroline Tice844d2302010-12-09 22:52:49 +00001356 {
Greg Clayton51964162011-10-25 00:36:27 +00001357 quote_char = first_char;
1358 const size_t end_quote_pos = command_string.find (quote_char, 1);
1359 if (end_quote_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001360 {
Greg Clayton5521f992011-10-28 21:38:01 +00001361 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001362 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001363 }
1364 else
1365 {
Greg Clayton5521f992011-10-28 21:38:01 +00001366 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton51964162011-10-25 00:36:27 +00001367 if (end_quote_pos + 1 < command_string.size())
1368 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1369 else
1370 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001371 }
Caroline Tice844d2302010-12-09 22:52:49 +00001372 }
1373 else
1374 {
Greg Clayton51964162011-10-25 00:36:27 +00001375 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1376 if (first_space_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001377 {
Greg Clayton5521f992011-10-28 21:38:01 +00001378 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001379 command_string.erase();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001380 }
1381 else
1382 {
Greg Clayton5521f992011-10-28 21:38:01 +00001383 command.assign (command_string, 0, first_space_pos);
1384 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice2b5e8502011-05-11 16:07:06 +00001385 }
Caroline Tice844d2302010-12-09 22:52:49 +00001386 }
Greg Clayton51964162011-10-25 00:36:27 +00001387 result = true;
Caroline Tice844d2302010-12-09 22:52:49 +00001388 }
Greg Clayton5521f992011-10-28 21:38:01 +00001389
1390
1391 if (!command.empty())
1392 {
1393 // actual commands can't start with '-' or '_'
1394 if (command[0] != '-' && command[0] != '_')
1395 {
1396 size_t pos = command.find_first_not_of(k_valid_command_chars);
1397 if (pos > 0 && pos != std::string::npos)
1398 {
1399 suffix.assign (command.begin() + pos, command.end());
1400 command.erase (pos);
1401 }
1402 }
1403 }
Greg Clayton51964162011-10-25 00:36:27 +00001404
1405 return result;
Caroline Tice844d2302010-12-09 22:52:49 +00001406}
1407
Greg Clayton5521f992011-10-28 21:38:01 +00001408CommandObject *
1409CommandInterpreter::BuildAliasResult (const char *alias_name,
1410 std::string &raw_input_string,
1411 std::string &alias_result,
1412 CommandReturnObject &result)
Caroline Tice844d2302010-12-09 22:52:49 +00001413{
Ed Masted78c9572014-04-20 00:31:37 +00001414 CommandObject *alias_cmd_obj = nullptr;
Pavel Labath00b7f952015-03-02 12:46:22 +00001415 Args cmd_args (raw_input_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001416 alias_cmd_obj = GetCommandObject (alias_name);
1417 StreamString result_str;
1418
1419 if (alias_cmd_obj)
1420 {
1421 std::string alias_name_str = alias_name;
1422 if ((cmd_args.GetArgumentCount() == 0)
1423 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1424 cmd_args.Unshift (alias_name);
1425
1426 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1427 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1428
1429 if (option_arg_vector_sp.get())
1430 {
1431 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1432
Andy Gibbsa297a972013-06-19 19:04:53 +00001433 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Caroline Tice844d2302010-12-09 22:52:49 +00001434 {
1435 OptionArgPair option_pair = (*option_arg_vector)[i];
1436 OptionArgValue value_pair = option_pair.second;
1437 int value_type = value_pair.first;
1438 std::string option = option_pair.first;
1439 std::string value = value_pair.second;
1440 if (option.compare ("<argument>") == 0)
1441 result_str.Printf (" %s", value.c_str());
1442 else
1443 {
1444 result_str.Printf (" %s", option.c_str());
Virgile Belloe2607b52013-09-05 16:42:23 +00001445 if (value_type != OptionParser::eOptionalArgument)
Caroline Tice844d2302010-12-09 22:52:49 +00001446 result_str.Printf (" ");
Virgile Belloe2607b52013-09-05 16:42:23 +00001447 if (value.compare ("<OptionParser::eNoArgument>") != 0)
Caroline Tice844d2302010-12-09 22:52:49 +00001448 {
1449 int index = GetOptionArgumentPosition (value.c_str());
1450 if (index == 0)
1451 result_str.Printf ("%s", value.c_str());
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001452 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Caroline Tice844d2302010-12-09 22:52:49 +00001453 {
1454
1455 result.AppendErrorWithFormat
1456 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1457 index);
1458 result.SetStatus (eReturnStatusFailed);
Greg Clayton5521f992011-10-28 21:38:01 +00001459 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001460 }
1461 else
1462 {
1463 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1464 if (strpos != std::string::npos)
1465 raw_input_string = raw_input_string.erase (strpos,
1466 strlen (cmd_args.GetArgumentAtIndex (index)));
1467 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1468 }
1469 }
1470 }
1471 }
1472 }
1473
1474 alias_result = result_str.GetData();
1475 }
Greg Clayton5521f992011-10-28 21:38:01 +00001476 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001477}
1478
Greg Clayton5a314712011-10-14 07:41:33 +00001479Error
1480CommandInterpreter::PreprocessCommand (std::string &command)
1481{
1482 // The command preprocessor needs to do things to the command
1483 // line before any parsing of arguments or anything else is done.
1484 // The only current stuff that gets proprocessed is anyting enclosed
1485 // in backtick ('`') characters is evaluated as an expression and
1486 // the result of the expression must be a scalar that can be substituted
1487 // into the command. An example would be:
1488 // (lldb) memory read `$rsp + 20`
1489 Error error; // Error for any expressions that might not evaluate
1490 size_t start_backtick;
1491 size_t pos = 0;
1492 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1493 {
1494 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1495 {
1496 // The backtick was preceeded by a '\' character, remove the slash
1497 // and don't treat the backtick as the start of an expression
1498 command.erase(start_backtick-1, 1);
1499 // No need to add one to start_backtick since we just deleted a char
1500 pos = start_backtick;
1501 }
1502 else
1503 {
1504 const size_t expr_content_start = start_backtick + 1;
1505 const size_t end_backtick = command.find ('`', expr_content_start);
1506 if (end_backtick == std::string::npos)
1507 return error;
1508 else if (end_backtick == expr_content_start)
1509 {
1510 // Empty expression (two backticks in a row)
1511 command.erase (start_backtick, 2);
1512 }
1513 else
1514 {
1515 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1516
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00001517 ExecutionContext exe_ctx(GetExecutionContext());
1518 Target *target = exe_ctx.GetTargetPtr();
Johnny Chen51ea0ad2011-10-29 00:21:50 +00001519 // Get a dummy target to allow for calculator mode while processing backticks.
1520 // This also helps break the infinite loop caused when target is null.
1521 if (!target)
Jim Ingham893c9322014-11-22 01:42:44 +00001522 target = m_debugger.GetDummyTarget();
Greg Clayton5a314712011-10-14 07:41:33 +00001523 if (target)
1524 {
Greg Clayton5a314712011-10-14 07:41:33 +00001525 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001526
Jim Ingham35e1bda2012-10-16 21:41:58 +00001527 EvaluateExpressionOptions options;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00001528 options.SetCoerceToId(false);
1529 options.SetUnwindOnError(true);
1530 options.SetIgnoreBreakpoints(true);
1531 options.SetKeepInMemory(false);
1532 options.SetTryAllThreads(true);
1533 options.SetTimeoutUsec(0);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001534
Jim Ingham1624a2d2014-05-05 02:26:40 +00001535 ExpressionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granataca0e5ad2014-10-09 23:09:40 +00001536 exe_ctx.GetFramePtr(),
1537 expr_result_valobj_sp,
1538 options);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001539
Jim Ingham8646d3c2014-05-05 02:47:44 +00001540 if (expr_result == eExpressionCompleted)
Greg Clayton5a314712011-10-14 07:41:33 +00001541 {
1542 Scalar scalar;
Enrico Granataca0e5ad2014-10-09 23:09:40 +00001543 if (expr_result_valobj_sp)
1544 expr_result_valobj_sp = expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(expr_result_valobj_sp->GetDynamicValueType(), true);
Greg Clayton5a314712011-10-14 07:41:33 +00001545 if (expr_result_valobj_sp->ResolveValue (scalar))
1546 {
1547 command.erase (start_backtick, end_backtick - start_backtick + 1);
1548 StreamString value_strm;
1549 const bool show_type = false;
1550 scalar.GetValue (&value_strm, show_type);
1551 size_t value_string_size = value_strm.GetSize();
1552 if (value_string_size)
1553 {
1554 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1555 pos = start_backtick + value_string_size;
1556 continue;
1557 }
1558 else
1559 {
1560 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1561 }
1562 }
1563 else
1564 {
1565 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1566 }
1567 }
1568 else
1569 {
1570 if (expr_result_valobj_sp)
1571 error = expr_result_valobj_sp->GetError();
1572 if (error.Success())
1573 {
1574
1575 switch (expr_result)
1576 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00001577 case eExpressionSetupError:
Greg Clayton5a314712011-10-14 07:41:33 +00001578 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1579 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001580 case eExpressionParseError:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001581 error.SetErrorStringWithFormat ("expression parse error for the expression '%s'", expr_str.c_str());
1582 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001583 case eExpressionResultUnavailable:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001584 error.SetErrorStringWithFormat ("expression error fetching result for the expression '%s'", expr_str.c_str());
Jim Ingham8646d3c2014-05-05 02:47:44 +00001585 case eExpressionCompleted:
Greg Clayton5a314712011-10-14 07:41:33 +00001586 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001587 case eExpressionDiscarded:
Greg Clayton5a314712011-10-14 07:41:33 +00001588 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1589 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001590 case eExpressionInterrupted:
Greg Clayton5a314712011-10-14 07:41:33 +00001591 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1592 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001593 case eExpressionHitBreakpoint:
Jim Ingham184e9812013-01-15 02:47:48 +00001594 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1595 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001596 case eExpressionTimedOut:
Greg Clayton5a314712011-10-14 07:41:33 +00001597 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1598 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001599 case eExpressionStoppedForDebug:
Greg Claytonc28ce782013-11-08 23:38:26 +00001600 error.SetErrorStringWithFormat("expression stop at entry point for debugging for the expression '%s'", expr_str.c_str());
1601 break;
Greg Clayton5a314712011-10-14 07:41:33 +00001602 }
1603 }
1604 }
1605 }
1606 }
1607 if (error.Fail())
1608 break;
1609 }
1610 }
1611 return error;
1612}
1613
1614
Caroline Tice844d2302010-12-09 22:52:49 +00001615bool
1616CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata5f5ab602012-05-31 01:09:06 +00001617 LazyBool lazy_add_to_history,
Caroline Tice844d2302010-12-09 22:52:49 +00001618 CommandReturnObject &result,
Jim Inghame16c50a2011-02-18 00:54:25 +00001619 ExecutionContext *override_context,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001620 bool repeat_on_empty_command,
1621 bool no_context_switching)
Jim Inghame16c50a2011-02-18 00:54:25 +00001622
Caroline Tice844d2302010-12-09 22:52:49 +00001623{
Jim Inghame16c50a2011-02-18 00:54:25 +00001624
Caroline Tice844d2302010-12-09 22:52:49 +00001625 bool done = false;
Ed Masted78c9572014-04-20 00:31:37 +00001626 CommandObject *cmd_obj = nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001627 bool wants_raw_input = false;
1628 std::string command_string (command_line);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001629 std::string original_command_string (command_line);
Caroline Tice844d2302010-12-09 22:52:49 +00001630
Greg Clayton5160ce52013-03-27 23:08:40 +00001631 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001632 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1633
1634 // Make a scoped cleanup object that will clear the crash description string
1635 // on exit of this function.
Ed Masted78c9572014-04-20 00:31:37 +00001636 lldb_utility::CleanUp <const char *> crash_description_cleanup(nullptr, Host::SetCrashDescription);
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001637
Caroline Tice844d2302010-12-09 22:52:49 +00001638 if (log)
1639 log->Printf ("Processing command: %s", command_line);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001640
Jim Ingham30244832010-11-04 23:08:45 +00001641 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1642
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001643 if (!no_context_switching)
1644 UpdateExecutionContext (override_context);
Enrico Granata5f5ab602012-05-31 01:09:06 +00001645
Enrico Granata5f5ab602012-05-31 01:09:06 +00001646 bool add_to_history;
1647 if (lazy_add_to_history == eLazyBoolCalculate)
1648 add_to_history = (m_command_source_depth == 0);
1649 else
1650 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1651
Jim Inghame16c50a2011-02-18 00:54:25 +00001652 bool empty_command = false;
1653 bool comment_command = false;
1654 if (command_string.empty())
1655 empty_command = true;
1656 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001657 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001658 const char *k_space_characters = "\t\n\v\f\r ";
1659
1660 size_t non_space = command_string.find_first_not_of (k_space_characters);
1661 // Check for empty line or comment line (lines whose first
1662 // non-space character is the comment character for this interpreter)
1663 if (non_space == std::string::npos)
1664 empty_command = true;
1665 else if (command_string[non_space] == m_comment_char)
1666 comment_command = true;
Enrico Granata7594f142013-06-17 22:51:50 +00001667 else if (command_string[non_space] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001668 {
Enrico Granata7594f142013-06-17 22:51:50 +00001669 const char *history_string = m_command_history.FindString(command_string.c_str() + non_space);
Ed Masted78c9572014-04-20 00:31:37 +00001670 if (history_string == nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001671 {
1672 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1673 result.SetStatus(eReturnStatusFailed);
1674 return false;
1675 }
1676 add_to_history = false;
1677 command_string = history_string;
1678 original_command_string = history_string;
1679 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001680 }
1681
1682 if (empty_command)
1683 {
1684 if (repeat_on_empty_command)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001685 {
Enrico Granata7594f142013-06-17 22:51:50 +00001686 if (m_command_history.IsEmpty())
Jim Inghame16c50a2011-02-18 00:54:25 +00001687 {
1688 result.AppendError ("empty command");
1689 result.SetStatus(eReturnStatusFailed);
1690 return false;
1691 }
1692 else
1693 {
1694 command_line = m_repeat_command.c_str();
1695 command_string = command_line;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001696 original_command_string = command_line;
Jim Inghame16c50a2011-02-18 00:54:25 +00001697 if (m_repeat_command.empty())
1698 {
1699 result.AppendErrorWithFormat("No auto repeat.\n");
1700 result.SetStatus (eReturnStatusFailed);
1701 return false;
1702 }
1703 }
1704 add_to_history = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001705 }
1706 else
1707 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001708 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1709 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001710 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001711 }
1712 else if (comment_command)
1713 {
1714 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1715 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001716 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001717
Greg Clayton5a314712011-10-14 07:41:33 +00001718
1719 Error error (PreprocessCommand (command_string));
1720
1721 if (error.Fail())
1722 {
1723 result.AppendError (error.AsCString());
1724 result.SetStatus(eReturnStatusFailed);
1725 return false;
1726 }
Caroline Tice844d2302010-12-09 22:52:49 +00001727 // Phase 1.
1728
1729 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1730 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1731 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1732 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1733 // 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 +00001734 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Tice844d2302010-12-09 22:52:49 +00001735 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Ticed9d63362010-12-07 19:58:26 +00001736
Caroline Tice844d2302010-12-09 22:52:49 +00001737 StreamString revised_command_line;
Caroline Tice01274c02010-12-11 08:16:56 +00001738 size_t actual_cmd_name_len = 0;
Greg Clayton5521f992011-10-28 21:38:01 +00001739 std::string next_word;
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001740 StringList matches;
Caroline Tice844d2302010-12-09 22:52:49 +00001741 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001742 {
Caroline Tice2b5e8502011-05-11 16:07:06 +00001743 char quote_char = '\0';
Greg Clayton5521f992011-10-28 21:38:01 +00001744 std::string suffix;
1745 ExtractCommand (command_string, next_word, suffix, quote_char);
Ed Masted78c9572014-04-20 00:31:37 +00001746 if (cmd_obj == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001747 {
Jim Ingham298f3782013-04-03 00:25:49 +00001748 std::string full_name;
1749 if (GetAliasFullName(next_word.c_str(), full_name))
Caroline Tice472362e2010-12-14 18:51:39 +00001750 {
Greg Clayton5521f992011-10-28 21:38:01 +00001751 std::string alias_result;
Jim Ingham298f3782013-04-03 00:25:49 +00001752 cmd_obj = BuildAliasResult (full_name.c_str(), command_string, alias_result, result);
Greg Clayton5521f992011-10-28 21:38:01 +00001753 revised_command_line.Printf ("%s", alias_result.c_str());
1754 if (cmd_obj)
1755 {
1756 wants_raw_input = cmd_obj->WantsRawCommandString ();
1757 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1758 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001759 }
1760 else
1761 {
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001762 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton5521f992011-10-28 21:38:01 +00001763 if (cmd_obj)
1764 {
1765 actual_cmd_name_len += next_word.length();
1766 revised_command_line.Printf ("%s", next_word.c_str());
1767 wants_raw_input = cmd_obj->WantsRawCommandString ();
1768 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001769 else
Greg Clayton5521f992011-10-28 21:38:01 +00001770 {
1771 revised_command_line.Printf ("%s", next_word.c_str());
1772 }
Caroline Tice844d2302010-12-09 22:52:49 +00001773 }
1774 }
1775 else
1776 {
Greg Clayton5521f992011-10-28 21:38:01 +00001777 if (cmd_obj->IsMultiwordObject ())
1778 {
Greg Clayton998255b2012-10-13 02:07:45 +00001779 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
Greg Clayton5521f992011-10-28 21:38:01 +00001780 if (sub_cmd_obj)
1781 {
1782 actual_cmd_name_len += next_word.length() + 1;
1783 revised_command_line.Printf (" %s", next_word.c_str());
1784 cmd_obj = sub_cmd_obj;
1785 wants_raw_input = cmd_obj->WantsRawCommandString ();
1786 }
1787 else
1788 {
1789 if (quote_char)
1790 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1791 else
1792 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1793 done = true;
1794 }
1795 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001796 else
Greg Clayton5521f992011-10-28 21:38:01 +00001797 {
1798 if (quote_char)
1799 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1800 else
1801 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1802 done = true;
1803 }
Caroline Tice844d2302010-12-09 22:52:49 +00001804 }
1805
Ed Masted78c9572014-04-20 00:31:37 +00001806 if (cmd_obj == nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001807 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001808 const size_t num_matches = matches.GetSize();
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001809 if (matches.GetSize() > 1) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001810 StreamString error_msg;
1811 error_msg.Printf ("Ambiguous command '%s'. Possible matches:\n", next_word.c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001812
1813 for (uint32_t i = 0; i < num_matches; ++i) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001814 error_msg.Printf ("\t%s\n", matches.GetStringAtIndex(i));
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001815 }
Greg Claytonc7bece562013-01-25 18:06:21 +00001816 result.AppendRawError (error_msg.GetString().c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001817 } else {
1818 // We didn't have only one match, otherwise we wouldn't get here.
1819 assert(num_matches == 0);
1820 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1821 }
Caroline Tice844d2302010-12-09 22:52:49 +00001822 result.SetStatus (eReturnStatusFailed);
1823 return false;
1824 }
1825
Greg Clayton5521f992011-10-28 21:38:01 +00001826 if (cmd_obj->IsMultiwordObject ())
1827 {
1828 if (!suffix.empty())
1829 {
1830
Enrico Granataaded51d2013-06-12 00:44:43 +00001831 result.AppendErrorWithFormat ("command '%s' did not recognize '%s%s%s' as valid (subcommand might be invalid).\n",
1832 cmd_obj->GetCommandName(),
1833 next_word.empty() ? "" : next_word.c_str(),
1834 next_word.empty() ? " -- " : " ",
Greg Clayton5521f992011-10-28 21:38:01 +00001835 suffix.c_str());
1836 result.SetStatus (eReturnStatusFailed);
1837 return false;
1838 }
1839 }
1840 else
1841 {
1842 // If we found a normal command, we are done
1843 done = true;
1844 if (!suffix.empty())
1845 {
1846 switch (suffix[0])
1847 {
1848 case '/':
1849 // GDB format suffixes
Greg Clayton52ec56c2011-10-29 00:57:28 +00001850 {
1851 Options *command_options = cmd_obj->GetOptions();
1852 if (command_options && command_options->SupportsLongOption("gdb-format"))
1853 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001854 std::string gdb_format_option ("--gdb-format=");
1855 gdb_format_option += (suffix.c_str() + 1);
1856
1857 bool inserted = false;
1858 std::string &cmd = revised_command_line.GetString();
1859 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1860 if (arg_terminator_idx != std::string::npos)
1861 {
1862 // Insert the gdb format option before the "--" that terminates options
1863 gdb_format_option.append(1,' ');
1864 cmd.insert(arg_terminator_idx, gdb_format_option);
1865 inserted = true;
1866 }
1867
1868 if (!inserted)
1869 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1870
1871 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1872 revised_command_line.PutCString (" --");
Greg Clayton52ec56c2011-10-29 00:57:28 +00001873 }
1874 else
1875 {
1876 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1877 cmd_obj->GetCommandName());
1878 result.SetStatus (eReturnStatusFailed);
1879 return false;
1880 }
1881 }
Greg Clayton5521f992011-10-28 21:38:01 +00001882 break;
Johnny Chen8e9383d2011-10-31 22:22:06 +00001883
1884 default:
1885 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1886 suffix.c_str());
1887 result.SetStatus (eReturnStatusFailed);
1888 return false;
1889
Greg Clayton5521f992011-10-28 21:38:01 +00001890 }
1891 }
1892 }
Caroline Tice844d2302010-12-09 22:52:49 +00001893 if (command_string.length() == 0)
1894 done = true;
1895
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001896 }
Caroline Tice844d2302010-12-09 22:52:49 +00001897
Greg Clayton5521f992011-10-28 21:38:01 +00001898 if (!command_string.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001899 revised_command_line.Printf (" %s", command_string.c_str());
1900
1901 // End of Phase 1.
1902 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1903 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1904 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1905 // wants_raw_input specifies whether the Execute method expects raw input or not.
1906
1907
1908 if (log)
1909 {
1910 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1911 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1912 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1913 }
1914
1915 // Phase 2.
1916 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1917 // CommandObject, with the appropriate arguments.
1918
Ed Masted78c9572014-04-20 00:31:37 +00001919 if (cmd_obj != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001920 {
1921 if (add_to_history)
1922 {
1923 Args command_args (revised_command_line.GetData());
1924 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
Ed Masted78c9572014-04-20 00:31:37 +00001925 if (repeat_command != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001926 m_repeat_command.assign(repeat_command);
1927 else
Jim Inghama5a97eb2011-07-12 03:12:18 +00001928 m_repeat_command.assign(original_command_string.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001929
Enrico Granata7594f142013-06-17 22:51:50 +00001930 m_command_history.AppendString (original_command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001931 }
1932
1933 command_string = revised_command_line.GetData();
1934 std::string command_name (cmd_obj->GetCommandName());
Caroline Tice01274c02010-12-11 08:16:56 +00001935 std::string remainder;
1936 if (actual_cmd_name_len < command_string.length())
1937 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1938 // than cmd_obj->GetCommandName(), because name completion
1939 // allows users to enter short versions of the names,
1940 // e.g. 'br s' for 'breakpoint set'.
Caroline Tice844d2302010-12-09 22:52:49 +00001941
1942 // Remove any initial spaces
1943 std::string white_space (" \t\v");
1944 size_t pos = remainder.find_first_not_of (white_space);
1945 if (pos != 0 && pos != std::string::npos)
Greg Claytona3482592011-04-22 20:58:45 +00001946 remainder.erase(0, pos);
Caroline Tice844d2302010-12-09 22:52:49 +00001947
1948 if (log)
Jason Molendabfb36ff2011-08-25 00:20:04 +00001949 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001950
Jim Ingham5a988412012-06-08 21:56:10 +00001951 cmd_obj->Execute (remainder.c_str(), result);
Caroline Tice844d2302010-12-09 22:52:49 +00001952 }
1953 else
1954 {
1955 // We didn't find the first command object, so complete the first argument.
1956 Args command_args (revised_command_line.GetData());
1957 StringList matches;
1958 int num_matches;
1959 int cursor_index = 0;
1960 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1961 bool word_complete;
1962 num_matches = HandleCompletionMatches (command_args,
1963 cursor_index,
1964 cursor_char_position,
1965 0,
1966 -1,
1967 word_complete,
1968 matches);
1969
1970 if (num_matches > 0)
1971 {
1972 std::string error_msg;
1973 error_msg.assign ("ambiguous command '");
1974 error_msg.append(command_args.GetArgumentAtIndex(0));
1975 error_msg.append ("'.");
1976
1977 error_msg.append (" Possible completions:");
1978 for (int i = 0; i < num_matches; i++)
1979 {
1980 error_msg.append ("\n\t");
1981 error_msg.append (matches.GetStringAtIndex (i));
1982 }
1983 error_msg.append ("\n");
Greg Claytonc7bece562013-01-25 18:06:21 +00001984 result.AppendRawError (error_msg.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001985 }
1986 else
1987 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1988
1989 result.SetStatus (eReturnStatusFailed);
1990 }
1991
Jason Molendabfb36ff2011-08-25 00:20:04 +00001992 if (log)
1993 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1994
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001995 return result.Succeeded();
1996}
1997
1998int
1999CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
2000 int &cursor_index,
2001 int &cursor_char_position,
2002 int match_start_point,
2003 int max_return_elements,
Jim Ingham558ce122010-06-30 05:02:46 +00002004 bool &word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002005 StringList &matches)
2006{
2007 int num_command_matches = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002008 bool look_for_subcommand = false;
Jim Ingham558ce122010-06-30 05:02:46 +00002009
2010 // For any of the command completions a unique match will be a complete word.
2011 word_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002012
2013 if (cursor_index == -1)
2014 {
2015 // We got nothing on the command line, so return the list of commands
Jim Ingham279a6c22010-07-06 22:46:59 +00002016 bool include_aliases = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002017 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
2018 }
2019 else if (cursor_index == 0)
2020 {
2021 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Ingham279a6c22010-07-06 22:46:59 +00002022 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002023 num_command_matches = matches.GetSize();
2024
2025 if (num_command_matches == 1
2026 && cmd_obj && cmd_obj->IsMultiwordObject()
Ed Masted78c9572014-04-20 00:31:37 +00002027 && matches.GetStringAtIndex(0) != nullptr
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002028 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
2029 {
Greg Clayton765d2e22013-12-10 19:14:04 +00002030 if (parsed_line.GetArgumentCount() == 1)
2031 {
2032 word_complete = true;
2033 }
2034 else
2035 {
2036 look_for_subcommand = true;
2037 num_command_matches = 0;
2038 matches.DeleteStringAtIndex(0);
2039 parsed_line.AppendArgument ("");
2040 cursor_index++;
2041 cursor_char_position = 0;
2042 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002043 }
2044 }
2045
2046 if (cursor_index > 0 || look_for_subcommand)
2047 {
2048 // We are completing further on into a commands arguments, so find the command and tell it
2049 // to complete the command.
2050 // First see if there is a matching initial command:
Jim Ingham279a6c22010-07-06 22:46:59 +00002051 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Ed Masted78c9572014-04-20 00:31:37 +00002052 if (command_object == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002053 {
2054 return 0;
2055 }
2056 else
2057 {
2058 parsed_line.Shift();
2059 cursor_index--;
Greg Claytona7015092010-09-18 01:14:36 +00002060 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton66111032010-06-23 01:19:29 +00002061 cursor_index,
2062 cursor_char_position,
2063 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00002064 max_return_elements,
2065 word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002066 matches);
2067 }
2068 }
2069
2070 return num_command_matches;
2071
2072}
2073
2074int
2075CommandInterpreter::HandleCompletion (const char *current_line,
2076 const char *cursor,
2077 const char *last_char,
2078 int match_start_point,
2079 int max_return_elements,
2080 StringList &matches)
2081{
2082 // We parse the argument up to the cursor, so the last argument in parsed_line is
2083 // the one containing the cursor, and the cursor is after the last character.
2084
Pavel Labath00b7f952015-03-02 12:46:22 +00002085 Args parsed_line(llvm::StringRef(current_line, last_char - current_line));
2086 Args partial_parsed_line(llvm::StringRef(current_line, cursor - current_line));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002087
Jim Inghama5a97eb2011-07-12 03:12:18 +00002088 // Don't complete comments, and if the line we are completing is just the history repeat character,
2089 // substitute the appropriate history line.
2090 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
2091 if (first_arg)
2092 {
2093 if (first_arg[0] == m_comment_char)
2094 return 0;
Enrico Granata7594f142013-06-17 22:51:50 +00002095 else if (first_arg[0] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002096 {
Enrico Granata7594f142013-06-17 22:51:50 +00002097 const char *history_string = m_command_history.FindString (first_arg);
Ed Masted78c9572014-04-20 00:31:37 +00002098 if (history_string != nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002099 {
2100 matches.Clear();
2101 matches.InsertStringAtIndex(0, history_string);
2102 return -2;
2103 }
2104 else
2105 return 0;
2106
2107 }
2108 }
2109
2110
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002111 int num_args = partial_parsed_line.GetArgumentCount();
2112 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
2113 int cursor_char_position;
2114
2115 if (cursor_index == -1)
2116 cursor_char_position = 0;
2117 else
2118 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamfe0c4252010-12-14 19:56:01 +00002119
2120 if (cursor > current_line && cursor[-1] == ' ')
2121 {
2122 // We are just after a space. If we are in an argument, then we will continue
2123 // parsing, but if we are between arguments, then we have to complete whatever the next
2124 // element would be.
2125 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
2126 // protected by a quote) then the space will also be in the parsed argument...
2127
2128 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
2129 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
2130 {
Greg Clayton765d2e22013-12-10 19:14:04 +00002131 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '\0');
Jim Inghamfe0c4252010-12-14 19:56:01 +00002132 cursor_index++;
2133 cursor_char_position = 0;
2134 }
2135 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002136
2137 int num_command_matches;
2138
2139 matches.Clear();
2140
2141 // Only max_return_elements == -1 is supported at present:
2142 assert (max_return_elements == -1);
Jim Ingham558ce122010-06-30 05:02:46 +00002143 bool word_complete;
Greg Clayton66111032010-06-23 01:19:29 +00002144 num_command_matches = HandleCompletionMatches (parsed_line,
2145 cursor_index,
2146 cursor_char_position,
2147 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00002148 max_return_elements,
2149 word_complete,
Greg Clayton66111032010-06-23 01:19:29 +00002150 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002151
2152 if (num_command_matches <= 0)
2153 return num_command_matches;
2154
2155 if (num_args == 0)
2156 {
2157 // If we got an empty string, insert nothing.
2158 matches.InsertStringAtIndex(0, "");
2159 }
2160 else
2161 {
2162 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
2163 // put an empty string in element 0.
2164 std::string command_partial_str;
2165 if (cursor_index >= 0)
Jim Ingham49e80a12010-10-22 18:47:16 +00002166 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
2167 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002168
2169 std::string common_prefix;
2170 matches.LongestCommonPrefix (common_prefix);
Greg Claytonc7bece562013-01-25 18:06:21 +00002171 const size_t partial_name_len = command_partial_str.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002172
2173 // If we matched a unique single command, add a space...
Jim Ingham558ce122010-06-30 05:02:46 +00002174 // Only do this if the completer told us this was a complete word, however...
2175 if (num_command_matches == 1 && word_complete)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002176 {
2177 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
2178 if (quote_char != '\0')
2179 common_prefix.push_back(quote_char);
2180
2181 common_prefix.push_back(' ');
2182 }
2183 common_prefix.erase (0, partial_name_len);
2184 matches.InsertStringAtIndex(0, common_prefix.c_str());
2185 }
2186 return num_command_matches;
2187}
2188
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002189
2190CommandInterpreter::~CommandInterpreter ()
2191{
2192}
2193
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002194void
Greg Clayton44d93782014-01-27 23:43:24 +00002195CommandInterpreter::UpdatePrompt (const char *new_prompt)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002196{
Greg Clayton44d93782014-01-27 23:43:24 +00002197 EventSP prompt_change_event_sp (new Event(eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));;
2198 BroadcastEvent (prompt_change_event_sp);
2199 if (m_command_io_handler_sp)
2200 m_command_io_handler_sp->SetPrompt(new_prompt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002201}
2202
Jim Ingham97a6dc72010-10-04 19:49:29 +00002203
2204bool
2205CommandInterpreter::Confirm (const char *message, bool default_answer)
2206{
Jim Ingham3bcdb292010-10-04 22:44:14 +00002207 // Check AutoConfirm first:
2208 if (m_debugger.GetAutoConfirm())
2209 return default_answer;
Greg Clayton44d93782014-01-27 23:43:24 +00002210
2211 IOHandlerConfirm *confirm = new IOHandlerConfirm(m_debugger,
2212 message,
2213 default_answer);
2214 IOHandlerSP io_handler_sp (confirm);
2215 m_debugger.RunIOHandler (io_handler_sp);
2216 return confirm->GetResponse();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002217}
2218
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002219OptionArgVectorSP
2220CommandInterpreter::GetAliasOptions (const char *alias_name)
2221{
2222 OptionArgMap::iterator pos;
2223 OptionArgVectorSP ret_val;
2224
2225 std::string alias (alias_name);
2226
2227 if (HasAliasOptions())
2228 {
2229 pos = m_alias_options.find (alias);
2230 if (pos != m_alias_options.end())
2231 ret_val = pos->second;
2232 }
2233
2234 return ret_val;
2235}
2236
2237void
2238CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2239{
2240 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2241 if (pos != m_alias_options.end())
2242 {
2243 m_alias_options.erase (pos);
2244 }
2245}
2246
2247void
2248CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2249{
2250 m_alias_options[alias_name] = option_arg_vector_sp;
2251}
2252
2253bool
2254CommandInterpreter::HasCommands ()
2255{
2256 return (!m_command_dict.empty());
2257}
2258
2259bool
2260CommandInterpreter::HasAliases ()
2261{
2262 return (!m_alias_dict.empty());
2263}
2264
2265bool
2266CommandInterpreter::HasUserCommands ()
2267{
2268 return (!m_user_dict.empty());
2269}
2270
2271bool
2272CommandInterpreter::HasAliasOptions ()
2273{
2274 return (!m_alias_options.empty());
2275}
2276
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002277void
Caroline Tice4ab31c92010-10-12 21:57:09 +00002278CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2279 const char *alias_name,
2280 Args &cmd_args,
Caroline Ticed9d63362010-12-07 19:58:26 +00002281 std::string &raw_input_string,
Caroline Tice4ab31c92010-10-12 21:57:09 +00002282 CommandReturnObject &result)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002283{
2284 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Ticed9d63362010-12-07 19:58:26 +00002285
2286 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002287
Caroline Ticed9d63362010-12-07 19:58:26 +00002288 // Make sure that the alias name is the 0th element in cmd_args
2289 std::string alias_name_str = alias_name;
2290 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2291 cmd_args.Unshift (alias_name);
2292
2293 Args new_args (alias_cmd_obj->GetCommandName());
2294 if (new_args.GetArgumentCount() == 2)
2295 new_args.Shift();
2296
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002297 if (option_arg_vector_sp.get())
2298 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002299 if (wants_raw_input)
2300 {
2301 // We have a command that both has command options and takes raw input. Make *sure* it has a
2302 // " -- " in the right place in the raw_input_string.
2303 size_t pos = raw_input_string.find(" -- ");
2304 if (pos == std::string::npos)
2305 {
2306 // None found; assume it goes at the beginning of the raw input string
2307 raw_input_string.insert (0, " -- ");
2308 }
2309 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002310
2311 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Greg Claytonc7bece562013-01-25 18:06:21 +00002312 const size_t old_size = cmd_args.GetArgumentCount();
Caroline Tice4ab31c92010-10-12 21:57:09 +00002313 std::vector<bool> used (old_size + 1, false);
2314
2315 used[0] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002316
Andy Gibbsa297a972013-06-19 19:04:53 +00002317 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002318 {
2319 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Ticed9d63362010-12-07 19:58:26 +00002320 OptionArgValue value_pair = option_pair.second;
2321 int value_type = value_pair.first;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002322 std::string option = option_pair.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00002323 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002324 if (option.compare ("<argument>") == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002325 {
2326 if (!wants_raw_input
2327 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2328 new_args.AppendArgument (value.c_str());
2329 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002330 else
2331 {
Virgile Belloe2607b52013-09-05 16:42:23 +00002332 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002333 new_args.AppendArgument (option.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002334 if (value.compare ("<no-argument>") != 0)
2335 {
2336 int index = GetOptionArgumentPosition (value.c_str());
2337 if (index == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002338 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002339 // value was NOT a positional argument; must be a real value
Virgile Belloe2607b52013-09-05 16:42:23 +00002340 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002341 new_args.AppendArgument (value.c_str());
2342 else
2343 {
2344 char buffer[255];
2345 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2346 new_args.AppendArgument (buffer);
2347 }
2348
2349 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002350 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002351 {
2352 result.AppendErrorWithFormat
2353 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2354 index);
2355 result.SetStatus (eReturnStatusFailed);
2356 return;
2357 }
2358 else
2359 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002360 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2361 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2362 if (strpos != std::string::npos)
2363 {
2364 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2365 }
2366
Virgile Belloe2607b52013-09-05 16:42:23 +00002367 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002368 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2369 else
2370 {
2371 char buffer[255];
2372 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2373 cmd_args.GetArgumentAtIndex (index));
2374 new_args.AppendArgument (buffer);
2375 }
Caroline Tice4ab31c92010-10-12 21:57:09 +00002376 used[index] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002377 }
2378 }
2379 }
2380 }
2381
Andy Gibbsa297a972013-06-19 19:04:53 +00002382 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002383 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002384 if (!used[j] && !wants_raw_input)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002385 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2386 }
2387
2388 cmd_args.Clear();
2389 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2390 }
2391 else
2392 {
2393 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Ticed9d63362010-12-07 19:58:26 +00002394 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2395 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2396 // input string.
2397 if (wants_raw_input)
2398 {
2399 cmd_args.Clear();
2400 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2401 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002402 return;
2403 }
2404
2405 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2406 return;
2407}
2408
2409
2410int
2411CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2412{
2413 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2414 // of zero.
2415
2416 char *cptr = (char *) in_string;
2417
2418 // Does it start with '%'
2419 if (cptr[0] == '%')
2420 {
2421 ++cptr;
2422
2423 // Is the rest of it entirely digits?
2424 if (isdigit (cptr[0]))
2425 {
2426 const char *start = cptr;
2427 while (isdigit (cptr[0]))
2428 ++cptr;
2429
2430 // We've gotten to the end of the digits; are we at the end of the string?
2431 if (cptr[0] == '\0')
2432 position = atoi (start);
2433 }
2434 }
2435
2436 return position;
2437}
2438
2439void
2440CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2441{
Jim Ingham16e0c682011-08-12 23:34:31 +00002442 FileSpec init_file;
Greg Clayton14a35512011-09-11 00:01:44 +00002443 if (in_cwd)
Jim Ingham16e0c682011-08-12 23:34:31 +00002444 {
Greg Clayton14a35512011-09-11 00:01:44 +00002445 // In the current working directory we don't load any program specific
2446 // .lldbinit files, we only look for a "./.lldbinit" file.
2447 if (m_skip_lldbinit_files)
2448 return;
2449
2450 init_file.SetFile ("./.lldbinit", true);
Jim Ingham16e0c682011-08-12 23:34:31 +00002451 }
Greg Clayton14a35512011-09-11 00:01:44 +00002452 else
Jim Ingham16e0c682011-08-12 23:34:31 +00002453 {
Greg Clayton14a35512011-09-11 00:01:44 +00002454 // If we aren't looking in the current working directory we are looking
2455 // in the home directory. We will first see if there is an application
2456 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2457 // "-" and the name of the program. If this file doesn't exist, we fall
2458 // back to just the "~/.lldbinit" file. We also obey any requests to not
2459 // load the init files.
Zachary Turnera21fee02014-08-21 21:49:24 +00002460 llvm::SmallString<64> home_dir_path;
2461 llvm::sys::path::home_directory(home_dir_path);
2462 FileSpec profilePath(home_dir_path.c_str(), false);
Zachary Turner9e757b72014-07-28 16:45:05 +00002463 profilePath.AppendPathComponent(".lldbinit");
2464 std::string init_file_path = profilePath.GetPath();
Greg Clayton14a35512011-09-11 00:01:44 +00002465
2466 if (m_skip_app_init_files == false)
2467 {
Zachary Turnera21fee02014-08-21 21:49:24 +00002468 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
Greg Clayton14a35512011-09-11 00:01:44 +00002469 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham16e0c682011-08-12 23:34:31 +00002470
Greg Clayton14a35512011-09-11 00:01:44 +00002471 if (program_name)
2472 {
2473 char program_init_file_name[PATH_MAX];
Zachary Turner9e757b72014-07-28 16:45:05 +00002474 ::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 +00002475 init_file.SetFile (program_init_file_name, true);
2476 if (!init_file.Exists())
2477 init_file.Clear();
2478 }
2479 }
2480
2481 if (!init_file && !m_skip_lldbinit_files)
Zachary Turner9e757b72014-07-28 16:45:05 +00002482 init_file.SetFile (init_file_path.c_str(), false);
Greg Clayton14a35512011-09-11 00:01:44 +00002483 }
2484
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002485 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2486 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2487
2488 if (init_file.Exists())
2489 {
Greg Clayton44d93782014-01-27 23:43:24 +00002490 const bool saved_batch = SetBatchCommandMode (true);
Jim Ingham26c7bf92014-10-11 00:38:27 +00002491 CommandInterpreterRunOptions options;
2492 options.SetSilent (true);
2493 options.SetStopOnError (false);
2494 options.SetStopOnContinue (true);
2495
Greg Clayton340b0302014-02-05 17:57:57 +00002496 HandleCommandsFromFile (init_file,
Ed Masted78c9572014-04-20 00:31:37 +00002497 nullptr, // Execution context
Jim Ingham26c7bf92014-10-11 00:38:27 +00002498 options,
Greg Clayton340b0302014-02-05 17:57:57 +00002499 result);
Greg Clayton44d93782014-01-27 23:43:24 +00002500 SetBatchCommandMode (saved_batch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002501 }
2502 else
2503 {
2504 // nothing to be done if the file doesn't exist
2505 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2506 }
2507}
2508
Kate Stonea487aa42015-01-15 00:52:41 +00002509const char *
2510CommandInterpreter::GetCommandPrefix()
2511{
2512 const char * prefix = GetDebugger().GetIOHandlerCommandPrefix();
2513 return prefix == NULL ? "" : prefix;
2514}
2515
Greg Clayton8b82f082011-04-12 05:54:46 +00002516PlatformSP
2517CommandInterpreter::GetPlatform (bool prefer_target_platform)
2518{
2519 PlatformSP platform_sp;
Greg Claytonc14ee322011-09-22 04:58:26 +00002520 if (prefer_target_platform)
2521 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002522 ExecutionContext exe_ctx(GetExecutionContext());
2523 Target *target = exe_ctx.GetTargetPtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002524 if (target)
2525 platform_sp = target->GetPlatform();
2526 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002527
2528 if (!platform_sp)
2529 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2530 return platform_sp;
2531}
2532
Jim Inghame16c50a2011-02-18 00:54:25 +00002533void
Jim Inghambad87fe2011-03-11 01:51:49 +00002534CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham26c7bf92014-10-11 00:38:27 +00002535 ExecutionContext *override_context,
2536 CommandInterpreterRunOptions &options,
Jim Inghame16c50a2011-02-18 00:54:25 +00002537 CommandReturnObject &result)
2538{
2539 size_t num_lines = commands.GetSize();
Jim Inghame16c50a2011-02-18 00:54:25 +00002540
2541 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2542 // Make sure you reset this value anywhere you return from the function.
2543
2544 bool old_async_execution = m_debugger.GetAsyncExecution();
2545
2546 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2547 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2548
Ed Masted78c9572014-04-20 00:31:37 +00002549 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00002550 UpdateExecutionContext (override_context);
Jim Inghame16c50a2011-02-18 00:54:25 +00002551
Jim Ingham26c7bf92014-10-11 00:38:27 +00002552 if (!options.GetStopOnContinue())
Jim Inghame16c50a2011-02-18 00:54:25 +00002553 {
2554 m_debugger.SetAsyncExecution (false);
2555 }
2556
Andy Gibbsa297a972013-06-19 19:04:53 +00002557 for (size_t idx = 0; idx < num_lines; idx++)
Jim Inghame16c50a2011-02-18 00:54:25 +00002558 {
2559 const char *cmd = commands.GetStringAtIndex(idx);
2560 if (cmd[0] == '\0')
2561 continue;
2562
Jim Ingham26c7bf92014-10-11 00:38:27 +00002563 if (options.GetEchoCommands())
Jim Inghame16c50a2011-02-18 00:54:25 +00002564 {
2565 result.AppendMessageWithFormat ("%s %s\n",
Greg Clayton44d93782014-01-27 23:43:24 +00002566 m_debugger.GetPrompt(),
2567 cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002568 }
2569
Greg Clayton9d0402b2011-02-20 02:15:07 +00002570 CommandReturnObject tmp_result;
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002571 // If override_context is not NULL, pass no_context_switching = true for
2572 // HandleCommand() since we updated our context already.
Jim Ingham076b7fc2013-05-02 23:15:37 +00002573
2574 // We might call into a regex or alias command, in which case the add_to_history will get lost. This
2575 // m_command_source_depth dingus is the way we turn off adding to the history in that case, so set it up here.
Jim Ingham26c7bf92014-10-11 00:38:27 +00002576 if (!options.GetAddToHistory())
Jim Ingham076b7fc2013-05-02 23:15:37 +00002577 m_command_source_depth++;
Jim Ingham26c7bf92014-10-11 00:38:27 +00002578 bool success = HandleCommand(cmd, options.m_add_to_history, tmp_result,
Ed Masted78c9572014-04-20 00:31:37 +00002579 nullptr, /* override_context */
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002580 true, /* repeat_on_empty_command */
Ed Masted78c9572014-04-20 00:31:37 +00002581 override_context != nullptr /* no_context_switching */);
Jim Ingham26c7bf92014-10-11 00:38:27 +00002582 if (!options.GetAddToHistory())
Jim Ingham076b7fc2013-05-02 23:15:37 +00002583 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002584
Jim Ingham26c7bf92014-10-11 00:38:27 +00002585 if (options.GetPrintResults())
Jim Inghame16c50a2011-02-18 00:54:25 +00002586 {
2587 if (tmp_result.Succeeded())
Jim Ingham85e8b812011-02-19 02:53:09 +00002588 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Inghame16c50a2011-02-18 00:54:25 +00002589 }
2590
2591 if (!success || !tmp_result.Succeeded())
2592 {
Jim Inghama5038812012-04-24 02:25:07 +00002593 const char *error_msg = tmp_result.GetErrorData();
Ed Masted78c9572014-04-20 00:31:37 +00002594 if (error_msg == nullptr || error_msg[0] == '\0')
Jim Inghama5038812012-04-24 02:25:07 +00002595 error_msg = "<unknown error>.\n";
Jim Ingham26c7bf92014-10-11 00:38:27 +00002596 if (options.GetStopOnError())
Jim Inghame16c50a2011-02-18 00:54:25 +00002597 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002598 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' failed with %s",
2599 (uint64_t)idx, cmd, error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002600 result.SetStatus (eReturnStatusFailed);
2601 m_debugger.SetAsyncExecution (old_async_execution);
2602 return;
2603 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002604 else if (options.GetPrintResults())
Jim Inghame16c50a2011-02-18 00:54:25 +00002605 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002606 result.AppendMessageWithFormat ("Command #%" PRIu64 " '%s' failed with %s",
2607 (uint64_t)idx + 1,
Jim Inghame16c50a2011-02-18 00:54:25 +00002608 cmd,
Jim Inghama5038812012-04-24 02:25:07 +00002609 error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002610 }
2611 }
2612
Caroline Tice969ed3d2011-05-02 20:41:46 +00002613 if (result.GetImmediateOutputStream())
2614 result.GetImmediateOutputStream()->Flush();
2615
2616 if (result.GetImmediateErrorStream())
2617 result.GetImmediateErrorStream()->Flush();
2618
Jim Inghame16c50a2011-02-18 00:54:25 +00002619 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2620 // could be running (for instance in Breakpoint Commands.
2621 // So we check the return value to see if it is has running in it.
2622 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2623 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2624 {
Jim Ingham26c7bf92014-10-11 00:38:27 +00002625 if (options.GetStopOnContinue())
Jim Inghame16c50a2011-02-18 00:54:25 +00002626 {
2627 // If we caused the target to proceed, and we're going to stop in that case, set the
2628 // status in our real result before returning. This is an error if the continue was not the
2629 // last command in the set of commands to be run.
2630 if (idx != num_lines - 1)
Deepak Panickal99fbc072014-03-03 15:39:47 +00002631 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' continued the target.\n",
2632 (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002633 else
Deepak Panickal99fbc072014-03-03 15:39:47 +00002634 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' continued the target.\n", (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002635
2636 result.SetStatus(tmp_result.GetStatus());
2637 m_debugger.SetAsyncExecution (old_async_execution);
2638
2639 return;
2640 }
2641 }
Jim Inghamffc9f1d2014-10-14 01:20:07 +00002642
2643 // Also check for "stop on crash here:
2644 bool should_stop = false;
2645 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash())
2646 {
2647 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
2648 if (target_sp)
2649 {
2650 ProcessSP process_sp (target_sp->GetProcessSP());
2651 if (process_sp)
2652 {
2653 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads())
2654 {
2655 StopReason reason = thread_sp->GetStopReason();
2656 if (reason == eStopReasonSignal || reason == eStopReasonException || reason == eStopReasonInstrumentation)
2657 {
2658 should_stop = true;
2659 break;
2660 }
2661 }
2662 }
2663 }
2664 if (should_stop)
2665 {
2666 if (idx != num_lines - 1)
2667 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' stopped with a signal or exception.\n",
2668 (uint64_t)idx + 1, cmd);
2669 else
2670 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' stopped with a signal or exception.\n", (uint64_t)idx + 1, cmd);
2671
2672 result.SetStatus(tmp_result.GetStatus());
2673 m_debugger.SetAsyncExecution (old_async_execution);
2674
2675 return;
2676 }
2677 }
Jim Inghame16c50a2011-02-18 00:54:25 +00002678
2679 }
2680
2681 result.SetStatus (eReturnStatusSuccessFinishResult);
2682 m_debugger.SetAsyncExecution (old_async_execution);
2683
2684 return;
2685}
2686
Greg Clayton340b0302014-02-05 17:57:57 +00002687// Make flags that we can pass into the IOHandler so our delegates can do the right thing
2688enum {
2689 eHandleCommandFlagStopOnContinue = (1u << 0),
2690 eHandleCommandFlagStopOnError = (1u << 1),
2691 eHandleCommandFlagEchoCommand = (1u << 2),
Jim Ingham26c7bf92014-10-11 00:38:27 +00002692 eHandleCommandFlagPrintResult = (1u << 3),
2693 eHandleCommandFlagStopOnCrash = (1u << 4)
Greg Clayton340b0302014-02-05 17:57:57 +00002694};
2695
Jim Inghame16c50a2011-02-18 00:54:25 +00002696void
2697CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2698 ExecutionContext *context,
Jim Ingham26c7bf92014-10-11 00:38:27 +00002699 CommandInterpreterRunOptions &options,
Jim Inghame16c50a2011-02-18 00:54:25 +00002700 CommandReturnObject &result)
2701{
2702 if (cmd_file.Exists())
2703 {
Greg Clayton44d93782014-01-27 23:43:24 +00002704 StreamFileSP input_file_sp (new StreamFile());
2705
2706 std::string cmd_file_path = cmd_file.GetPath();
2707 Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), File::eOpenOptionRead);
2708
2709 if (error.Success())
2710 {
2711 Debugger &debugger = GetDebugger();
2712
Greg Clayton340b0302014-02-05 17:57:57 +00002713 uint32_t flags = 0;
2714
Jim Ingham26c7bf92014-10-11 00:38:27 +00002715 if (options.m_stop_on_continue == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002716 {
2717 if (m_command_source_flags.empty())
2718 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002719 // Stop on continue by default
Greg Clayton340b0302014-02-05 17:57:57 +00002720 flags |= eHandleCommandFlagStopOnContinue;
2721 }
2722 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnContinue)
2723 {
2724 flags |= eHandleCommandFlagStopOnContinue;
2725 }
2726 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002727 else if (options.m_stop_on_continue == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002728 {
2729 flags |= eHandleCommandFlagStopOnContinue;
2730 }
2731
Jim Ingham26c7bf92014-10-11 00:38:27 +00002732 if (options.m_stop_on_error == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002733 {
2734 if (m_command_source_flags.empty())
2735 {
2736 if (GetStopCmdSourceOnError())
2737 flags |= eHandleCommandFlagStopOnError;
2738 }
2739 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError)
2740 {
2741 flags |= eHandleCommandFlagStopOnError;
2742 }
2743 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002744 else if (options.m_stop_on_error == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002745 {
2746 flags |= eHandleCommandFlagStopOnError;
2747 }
2748
Jim Inghamffc9f1d2014-10-14 01:20:07 +00002749 if (options.GetStopOnCrash())
2750 {
2751 if (m_command_source_flags.empty())
2752 {
2753 // Echo command by default
2754 flags |= eHandleCommandFlagStopOnCrash;
2755 }
2756 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash)
2757 {
2758 flags |= eHandleCommandFlagStopOnCrash;
2759 }
2760 }
2761
Jim Ingham26c7bf92014-10-11 00:38:27 +00002762 if (options.m_echo_commands == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002763 {
2764 if (m_command_source_flags.empty())
2765 {
2766 // Echo command by default
2767 flags |= eHandleCommandFlagEchoCommand;
2768 }
2769 else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand)
2770 {
2771 flags |= eHandleCommandFlagEchoCommand;
2772 }
2773 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002774 else if (options.m_echo_commands == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002775 {
2776 flags |= eHandleCommandFlagEchoCommand;
2777 }
2778
Jim Ingham26c7bf92014-10-11 00:38:27 +00002779 if (options.m_print_results == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002780 {
2781 if (m_command_source_flags.empty())
2782 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002783 // Print output by default
2784 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002785 }
Greg Claytone4e462c2014-02-05 21:03:22 +00002786 else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult)
Greg Clayton340b0302014-02-05 17:57:57 +00002787 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002788 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002789 }
2790 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002791 else if (options.m_print_results == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002792 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002793 flags |= eHandleCommandFlagPrintResult;
2794 }
2795
2796 if (flags & eHandleCommandFlagPrintResult)
2797 {
Greg Clayton8ee67312014-02-05 21:46:20 +00002798 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", cmd_file_path.c_str());
Greg Clayton340b0302014-02-05 17:57:57 +00002799 }
2800
2801 // Used for inheriting the right settings when "command source" might have
2802 // nested "command source" commands
Greg Claytone4e462c2014-02-05 21:03:22 +00002803 lldb::StreamFileSP empty_stream_sp;
Greg Clayton340b0302014-02-05 17:57:57 +00002804 m_command_source_flags.push_back(flags);
Greg Clayton44d93782014-01-27 23:43:24 +00002805 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
Kate Stonee30f11d2014-11-17 19:06:59 +00002806 IOHandler::Type::CommandInterpreter,
Greg Clayton44d93782014-01-27 23:43:24 +00002807 input_file_sp,
Greg Claytone4e462c2014-02-05 21:03:22 +00002808 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader output stream
2809 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader error stream
Greg Clayton340b0302014-02-05 17:57:57 +00002810 flags,
Ed Masted78c9572014-04-20 00:31:37 +00002811 nullptr, // Pass in NULL for "editline_name" so no history is saved, or written
Greg Clayton8ee67312014-02-05 21:46:20 +00002812 debugger.GetPrompt(),
Kate Stonee30f11d2014-11-17 19:06:59 +00002813 NULL,
Greg Clayton44d93782014-01-27 23:43:24 +00002814 false, // Not multi-line
Kate Stonee30f11d2014-11-17 19:06:59 +00002815 debugger.GetUseColor(),
Greg Claytonf6913cd2014-03-07 00:53:24 +00002816 0,
Greg Clayton44d93782014-01-27 23:43:24 +00002817 *this));
Greg Clayton8ee67312014-02-05 21:46:20 +00002818 const bool old_async_execution = debugger.GetAsyncExecution();
2819
Jim Inghamffc9f1d2014-10-14 01:20:07 +00002820 // Set synchronous execution if we are not stopping on continue
Greg Clayton8ee67312014-02-05 21:46:20 +00002821 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2822 debugger.SetAsyncExecution (false);
2823
Greg Clayton340b0302014-02-05 17:57:57 +00002824 m_command_source_depth++;
Greg Clayton8ee67312014-02-05 21:46:20 +00002825
2826 debugger.RunIOHandler(io_handler_sp);
Greg Clayton340b0302014-02-05 17:57:57 +00002827 if (!m_command_source_flags.empty())
2828 m_command_source_flags.pop_back();
2829 m_command_source_depth--;
Greg Clayton44d93782014-01-27 23:43:24 +00002830 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Greg Clayton8ee67312014-02-05 21:46:20 +00002831 debugger.SetAsyncExecution (old_async_execution);
Greg Clayton44d93782014-01-27 23:43:24 +00002832 }
2833 else
2834 {
2835 result.AppendErrorWithFormat ("error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(), error.AsCString());
2836 result.SetStatus (eReturnStatusFailed);
2837 }
Greg Clayton8ee67312014-02-05 21:46:20 +00002838
2839
Jim Inghame16c50a2011-02-18 00:54:25 +00002840 }
2841 else
2842 {
2843 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
Jim Ingham4af59612014-12-19 19:20:44 +00002844 cmd_file.GetFilename().AsCString("<Unknown>"));
Jim Inghame16c50a2011-02-18 00:54:25 +00002845 result.SetStatus (eReturnStatusFailed);
2846 return;
2847 }
2848}
2849
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002850ScriptInterpreter *
Enrico Granatab5887262012-10-29 21:18:03 +00002851CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002852{
Ed Masted78c9572014-04-20 00:31:37 +00002853 if (m_script_interpreter_ap.get() != nullptr)
Enrico Granatab5887262012-10-29 21:18:03 +00002854 return m_script_interpreter_ap.get();
2855
2856 if (!can_create)
Ed Masted78c9572014-04-20 00:31:37 +00002857 return nullptr;
Enrico Granatab5887262012-10-29 21:18:03 +00002858
Enrico Granataa29bdad2012-07-10 18:23:48 +00002859 // <rdar://problem/11751427>
2860 // we need to protect the initialization of the script interpreter
2861 // otherwise we could end up with two threads both trying to create
2862 // their instance of it, and for some languages (e.g. Python)
2863 // this is a bulletproof recipe for disaster!
2864 // this needs to be a function-level static because multiple Debugger instances living in the same process
2865 // still need to be isolated and not try to initialize Python concurrently
Enrico Granata8b95df22012-07-10 19:04:14 +00002866 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2867 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granataa29bdad2012-07-10 18:23:48 +00002868
Greg Clayton5160ce52013-03-27 23:08:40 +00002869 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Enrico Granatab5887262012-10-29 21:18:03 +00002870 if (log)
2871 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton66111032010-06-23 01:19:29 +00002872
Caroline Tice2f88aad2011-01-14 00:29:16 +00002873 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2874 switch (script_lang)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002875 {
Greg Claytondce502e2011-11-04 03:34:56 +00002876 case eScriptLanguagePython:
2877#ifndef LLDB_DISABLE_PYTHON
2878 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2879 break;
2880#else
2881 // Fall through to the None case when python is disabled
2882#endif
Caroline Tice2f88aad2011-01-14 00:29:16 +00002883 case eScriptLanguageNone:
2884 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2885 break;
Caroline Tice2f88aad2011-01-14 00:29:16 +00002886 };
2887
2888 return m_script_interpreter_ap.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002889}
2890
2891
2892
2893bool
2894CommandInterpreter::GetSynchronous ()
2895{
2896 return m_synchronous_execution;
2897}
2898
2899void
2900CommandInterpreter::SetSynchronous (bool value)
2901{
Johnny Chenc066ab42010-10-14 01:22:03 +00002902 m_synchronous_execution = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002903}
2904
2905void
2906CommandInterpreter::OutputFormattedHelpText (Stream &strm,
Kate Stonea487aa42015-01-15 00:52:41 +00002907 const char *prefix,
2908 const char *help_text)
2909{
2910 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2911 if (prefix == NULL)
2912 prefix = "";
2913
2914 size_t prefix_width = strlen(prefix);
2915 size_t line_width_max = max_columns - prefix_width;
2916 const char *help_text_end = help_text + strlen(help_text);
2917 const char *line_start = help_text;
2918 if (line_width_max < 16)
2919 line_width_max = help_text_end - help_text + prefix_width;
2920
2921 strm.IndentMore (prefix_width);
2922 while (line_start < help_text_end)
2923 {
2924 // Break each line at the first newline or last space/tab before
2925 // the maximum number of characters that fit on a line. Lines with no
2926 // natural break are left unbroken to wrap.
2927 const char *line_end = help_text_end;
2928 const char *line_scan = line_start;
2929 const char *line_scan_end = help_text_end;
2930 while (line_scan < line_scan_end)
2931 {
2932 char next = *line_scan;
2933 if (next == '\t' || next == ' ')
2934 {
2935 line_end = line_scan;
2936 line_scan_end = line_start + line_width_max;
2937 }
2938 else if (next == '\n' || next == '\0')
2939 {
2940 line_end = line_scan;
2941 break;
2942 }
2943 ++line_scan;
2944 }
2945
2946 // Prefix the first line, indent subsequent lines to line up
2947 if (line_start == help_text)
2948 strm.Write (prefix, prefix_width);
2949 else
2950 strm.Indent();
2951 strm.Write (line_start, line_end - line_start);
2952 strm.EOL();
2953
2954 // When a line breaks at whitespace consume it before continuing
2955 line_start = line_end;
2956 char next = *line_start;
2957 if (next == '\n')
2958 ++line_start;
2959 else while (next == ' ' || next == '\t')
2960 next = *(++line_start);
2961 }
2962 strm.IndentLess (prefix_width);
2963}
2964
2965void
2966CommandInterpreter::OutputFormattedHelpText (Stream &strm,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002967 const char *word_text,
2968 const char *separator,
2969 const char *help_text,
Greg Claytonc7bece562013-01-25 18:06:21 +00002970 size_t max_word_len)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002971{
Kate Stonea487aa42015-01-15 00:52:41 +00002972 StreamString prefix_stream;
2973 prefix_stream.Printf (" %-*s %s ", (int)max_word_len, word_text, separator);
2974 OutputFormattedHelpText (strm, prefix_stream.GetData(), help_text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002975}
2976
2977void
Enrico Granata82a7d982011-07-07 00:38:40 +00002978CommandInterpreter::OutputHelpText (Stream &strm,
2979 const char *word_text,
2980 const char *separator,
2981 const char *help_text,
2982 uint32_t max_word_len)
2983{
2984 int indent_size = max_word_len + strlen (separator) + 2;
2985
2986 strm.IndentMore (indent_size);
2987
2988 StreamString text_strm;
2989 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2990
2991 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata82a7d982011-07-07 00:38:40 +00002992
2993 size_t len = text_strm.GetSize();
2994 const char *text = text_strm.GetData();
2995
2996 uint32_t chars_left = max_columns;
2997
2998 for (uint32_t i = 0; i < len; i++)
2999 {
3000 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
3001 {
Enrico Granata82a7d982011-07-07 00:38:40 +00003002 chars_left = max_columns - indent_size;
3003 strm.EOL();
3004 strm.Indent();
3005 }
3006 else
3007 {
3008 strm.PutChar(text[i]);
3009 chars_left--;
3010 }
3011
3012 }
3013
3014 strm.EOL();
3015 strm.IndentLess(indent_size);
3016}
3017
3018void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003019CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
Jim Inghamaf3753e2013-05-17 01:30:37 +00003020 StringList &commands_help, bool search_builtin_commands, bool search_user_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003021{
3022 CommandObject::CommandMap::const_iterator pos;
3023
Jim Inghamaf3753e2013-05-17 01:30:37 +00003024 if (search_builtin_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003025 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00003026 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003027 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00003028 const char *command_name = pos->first.c_str();
3029 CommandObject *cmd_obj = pos->second.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003030
Jim Inghamaf3753e2013-05-17 01:30:37 +00003031 if (cmd_obj->HelpTextContainsWord (search_word))
3032 {
3033 commands_found.AppendString (command_name);
3034 commands_help.AppendString (cmd_obj->GetHelp());
3035 }
3036
3037 if (cmd_obj->IsMultiwordObject())
3038 cmd_obj->AproposAllSubCommands (command_name,
3039 search_word,
3040 commands_found,
3041 commands_help);
3042
3043 }
3044 }
3045
3046 if (search_user_commands)
3047 {
3048 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
3049 {
3050 const char *command_name = pos->first.c_str();
3051 CommandObject *cmd_obj = pos->second.get();
3052
3053 if (cmd_obj->HelpTextContainsWord (search_word))
3054 {
3055 commands_found.AppendString (command_name);
3056 commands_help.AppendString (cmd_obj->GetHelp());
3057 }
3058
3059 if (cmd_obj->IsMultiwordObject())
3060 cmd_obj->AproposAllSubCommands (command_name,
3061 search_word,
3062 commands_found,
3063 commands_help);
3064
3065 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003066 }
3067}
Greg Clayton8b82f082011-04-12 05:54:46 +00003068
Greg Clayton8b82f082011-04-12 05:54:46 +00003069void
3070CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
3071{
Ed Masted78c9572014-04-20 00:31:37 +00003072 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00003073 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00003074 m_exe_ctx_ref = *override_context;
Greg Clayton8b82f082011-04-12 05:54:46 +00003075 }
3076 else
3077 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00003078 const bool adopt_selected = true;
3079 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Clayton8b82f082011-04-12 05:54:46 +00003080 }
3081}
Greg Clayton44d93782014-01-27 23:43:24 +00003082
3083
3084size_t
3085CommandInterpreter::GetProcessOutput ()
3086{
3087 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
3088 char stdio_buffer[1024];
3089 size_t len;
3090 size_t total_bytes = 0;
3091 Error error;
3092 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
3093 if (target_sp)
3094 {
3095 ProcessSP process_sp (target_sp->GetProcessSP());
3096 if (process_sp)
3097 {
3098 while ((len = process_sp->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
3099 {
3100 size_t bytes_written = len;
3101 m_debugger.GetOutputFile()->Write (stdio_buffer, bytes_written);
3102 total_bytes += len;
3103 }
3104 while ((len = process_sp->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
3105 {
3106 size_t bytes_written = len;
3107 m_debugger.GetErrorFile()->Write (stdio_buffer, bytes_written);
3108 total_bytes += len;
3109 }
3110 }
3111 }
3112 return total_bytes;
3113}
3114
3115void
3116CommandInterpreter::IOHandlerInputComplete (IOHandler &io_handler, std::string &line)
3117{
Greg Clayton340b0302014-02-05 17:57:57 +00003118 const bool is_interactive = io_handler.GetIsInteractive();
3119 if (is_interactive == false)
3120 {
3121 // When we are not interactive, don't execute blank lines. This will happen
3122 // sourcing a commands file. We don't want blank lines to repeat the previous
3123 // command and cause any errors to occur (like redefining an alias, get an error
3124 // and stop parsing the commands file).
3125 if (line.empty())
3126 return;
3127
3128 // When using a non-interactive file handle (like when sourcing commands from a file)
3129 // we need to echo the command out so we don't just see the command output and no
3130 // command...
3131 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
3132 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(), line.c_str());
3133 }
3134
Greg Clayton44d93782014-01-27 23:43:24 +00003135 lldb_private::CommandReturnObject result;
3136 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
3137
Greg Clayton44d93782014-01-27 23:43:24 +00003138 // Now emit the command output text from the command we just executed
Greg Clayton340b0302014-02-05 17:57:57 +00003139 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult))
3140 {
3141 // Display any STDOUT/STDERR _prior_ to emitting the command result text
3142 GetProcessOutput ();
3143
Greg Clayton8ee67312014-02-05 21:46:20 +00003144 if (!result.GetImmediateOutputStream())
3145 {
3146 const char *output = result.GetOutputData();
3147 if (output && output[0])
3148 io_handler.GetOutputStreamFile()->PutCString(output);
3149 }
Greg Clayton44d93782014-01-27 23:43:24 +00003150
Greg Clayton340b0302014-02-05 17:57:57 +00003151 // Now emit the command error text from the command we just executed
Greg Clayton8ee67312014-02-05 21:46:20 +00003152 if (!result.GetImmediateErrorStream())
3153 {
3154 const char *error = result.GetErrorData();
3155 if (error && error[0])
3156 io_handler.GetErrorStreamFile()->PutCString(error);
3157 }
Greg Clayton340b0302014-02-05 17:57:57 +00003158 }
Greg Clayton44d93782014-01-27 23:43:24 +00003159
3160 switch (result.GetStatus())
3161 {
3162 case eReturnStatusInvalid:
3163 case eReturnStatusSuccessFinishNoResult:
3164 case eReturnStatusSuccessFinishResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003165 case eReturnStatusStarted:
3166 break;
3167
Greg Clayton44d93782014-01-27 23:43:24 +00003168 case eReturnStatusSuccessContinuingNoResult:
3169 case eReturnStatusSuccessContinuingResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003170 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
3171 io_handler.SetIsDone(true);
3172 break;
3173
Greg Clayton44d93782014-01-27 23:43:24 +00003174 case eReturnStatusFailed:
Jim Ingham26c7bf92014-10-11 00:38:27 +00003175 m_num_errors++;
Greg Clayton340b0302014-02-05 17:57:57 +00003176 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
3177 io_handler.SetIsDone(true);
Greg Clayton44d93782014-01-27 23:43:24 +00003178 break;
3179
3180 case eReturnStatusQuit:
Jim Ingham26c7bf92014-10-11 00:38:27 +00003181 m_quit_requested = true;
Greg Clayton44d93782014-01-27 23:43:24 +00003182 io_handler.SetIsDone(true);
3183 break;
3184 }
Jim Inghamffc9f1d2014-10-14 01:20:07 +00003185
3186 // Finally, if we're going to stop on crash, check that here:
3187 if (!m_quit_requested
3188 && result.GetDidChangeProcessState()
3189 && io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash))
3190 {
3191 bool should_stop = false;
3192 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
3193 if (target_sp)
3194 {
3195 ProcessSP process_sp (target_sp->GetProcessSP());
3196 if (process_sp)
3197 {
3198 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads())
3199 {
3200 StopReason reason = thread_sp->GetStopReason();
3201 if (reason == eStopReasonSignal || reason == eStopReasonException || reason == eStopReasonInstrumentation)
3202 {
Jim Inghamffc9f1d2014-10-14 01:20:07 +00003203 should_stop = true;
3204 break;
3205 }
3206 }
3207 }
3208 }
3209 if (should_stop)
3210 {
3211 io_handler.SetIsDone(true);
3212 m_stopped_for_crash = true;
3213 }
3214 }
Greg Clayton44d93782014-01-27 23:43:24 +00003215}
3216
Greg Claytonf0066ad2014-05-02 00:45:31 +00003217bool
3218CommandInterpreter::IOHandlerInterrupt (IOHandler &io_handler)
3219{
3220 ExecutionContext exe_ctx (GetExecutionContext());
3221 Process *process = exe_ctx.GetProcessPtr();
3222
3223 if (process)
3224 {
3225 StateType state = process->GetState();
3226 if (StateIsRunningState(state))
3227 {
3228 process->Halt();
3229 return true; // Don't do any updating when we are running
3230 }
3231 }
Greg Claytone507bce2015-01-27 01:58:22 +00003232
3233 ScriptInterpreter *script_interpreter = GetScriptInterpreter (false);
3234 if (script_interpreter)
3235 {
3236 if (script_interpreter->Interrupt())
3237 return true;
3238 }
Greg Claytonf0066ad2014-05-02 00:45:31 +00003239 return false;
3240}
3241
Greg Clayton44d93782014-01-27 23:43:24 +00003242void
3243CommandInterpreter::GetLLDBCommandsFromIOHandler (const char *prompt,
3244 IOHandlerDelegate &delegate,
3245 bool asynchronously,
3246 void *baton)
3247{
3248 Debugger &debugger = GetDebugger();
3249 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
Kate Stonee30f11d2014-11-17 19:06:59 +00003250 IOHandler::Type::CommandList,
Greg Clayton44d93782014-01-27 23:43:24 +00003251 "lldb", // Name of input reader for history
3252 prompt, // Prompt
Kate Stonee30f11d2014-11-17 19:06:59 +00003253 NULL, // Continuation prompt
Greg Clayton44d93782014-01-27 23:43:24 +00003254 true, // Get multiple lines
Kate Stonee30f11d2014-11-17 19:06:59 +00003255 debugger.GetUseColor(),
Greg Claytonf6913cd2014-03-07 00:53:24 +00003256 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003257 delegate)); // IOHandlerDelegate
3258
3259 if (io_handler_sp)
3260 {
3261 io_handler_sp->SetUserData (baton);
3262 if (asynchronously)
3263 debugger.PushIOHandler(io_handler_sp);
3264 else
3265 debugger.RunIOHandler(io_handler_sp);
3266 }
3267
3268}
3269
3270
3271void
3272CommandInterpreter::GetPythonCommandsFromIOHandler (const char *prompt,
3273 IOHandlerDelegate &delegate,
3274 bool asynchronously,
3275 void *baton)
3276{
3277 Debugger &debugger = GetDebugger();
3278 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
Kate Stonee30f11d2014-11-17 19:06:59 +00003279 IOHandler::Type::PythonCode,
Greg Clayton44d93782014-01-27 23:43:24 +00003280 "lldb-python", // Name of input reader for history
3281 prompt, // Prompt
Kate Stonee30f11d2014-11-17 19:06:59 +00003282 NULL, // Continuation prompt
Greg Clayton44d93782014-01-27 23:43:24 +00003283 true, // Get multiple lines
Kate Stonee30f11d2014-11-17 19:06:59 +00003284 debugger.GetUseColor(),
Greg Claytonf6913cd2014-03-07 00:53:24 +00003285 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003286 delegate)); // IOHandlerDelegate
3287
3288 if (io_handler_sp)
3289 {
3290 io_handler_sp->SetUserData (baton);
3291 if (asynchronously)
3292 debugger.PushIOHandler(io_handler_sp);
3293 else
3294 debugger.RunIOHandler(io_handler_sp);
3295 }
3296
3297}
3298
3299bool
3300CommandInterpreter::IsActive ()
3301{
3302 return m_debugger.IsTopIOHandler (m_command_io_handler_sp);
3303}
3304
Kate Stonee30f11d2014-11-17 19:06:59 +00003305lldb::IOHandlerSP
3306CommandInterpreter::GetIOHandler(bool force_create, CommandInterpreterRunOptions *options)
3307{
3308 // Always re-create the IOHandlerEditline in case the input
3309 // changed. The old instance might have had a non-interactive
3310 // input and now it does or vice versa.
3311 if (force_create || !m_command_io_handler_sp)
3312 {
3313 // Always re-create the IOHandlerEditline in case the input
3314 // changed. The old instance might have had a non-interactive
3315 // input and now it does or vice versa.
3316 uint32_t flags = 0;
3317
3318 if (options)
3319 {
3320 if (options->m_stop_on_continue == eLazyBoolYes)
3321 flags |= eHandleCommandFlagStopOnContinue;
3322 if (options->m_stop_on_error == eLazyBoolYes)
3323 flags |= eHandleCommandFlagStopOnError;
3324 if (options->m_stop_on_crash == eLazyBoolYes)
3325 flags |= eHandleCommandFlagStopOnCrash;
3326 if (options->m_echo_commands != eLazyBoolNo)
3327 flags |= eHandleCommandFlagEchoCommand;
3328 if (options->m_print_results != eLazyBoolNo)
3329 flags |= eHandleCommandFlagPrintResult;
3330 }
3331 else
3332 {
3333 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
3334 }
3335
3336 m_command_io_handler_sp.reset(new IOHandlerEditline (m_debugger,
3337 IOHandler::Type::CommandInterpreter,
3338 m_debugger.GetInputFile(),
3339 m_debugger.GetOutputFile(),
3340 m_debugger.GetErrorFile(),
3341 flags,
3342 "lldb",
3343 m_debugger.GetPrompt(),
3344 NULL, // Continuation prompt
3345 false, // Don't enable multiple line input, just single line commands
3346 m_debugger.GetUseColor(),
3347 0, // Don't show line numbers
3348 *this));
3349 }
3350 return m_command_io_handler_sp;
3351}
3352
Greg Clayton44d93782014-01-27 23:43:24 +00003353void
3354CommandInterpreter::RunCommandInterpreter(bool auto_handle_events,
Jim Ingham26c7bf92014-10-11 00:38:27 +00003355 bool spawn_thread,
3356 CommandInterpreterRunOptions &options)
Greg Clayton44d93782014-01-27 23:43:24 +00003357{
Kate Stonee30f11d2014-11-17 19:06:59 +00003358 // Always re-create the command intepreter when we run it in case
3359 // any file handles have changed.
3360 bool force_create = true;
3361 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
Jim Inghamffc9f1d2014-10-14 01:20:07 +00003362 m_stopped_for_crash = false;
Greg Clayton380f3d82014-07-31 19:46:19 +00003363
Greg Clayton44d93782014-01-27 23:43:24 +00003364 if (auto_handle_events)
3365 m_debugger.StartEventHandlerThread();
3366
3367 if (spawn_thread)
3368 {
3369 m_debugger.StartIOHandlerThread();
3370 }
3371 else
3372 {
Siva Chandra9aaab552015-02-26 19:26:36 +00003373 m_debugger.ExecuteIOHandlers();
Kate Stonee30f11d2014-11-17 19:06:59 +00003374
Greg Clayton44d93782014-01-27 23:43:24 +00003375 if (auto_handle_events)
3376 m_debugger.StopEventHandlerThread();
3377 }
Kate Stonee30f11d2014-11-17 19:06:59 +00003378
Greg Clayton44d93782014-01-27 23:43:24 +00003379}
3380