blob: 114316ab26456117a49f5b43266ae9afb2be0da2 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner30fdc8d2010-06-08 16:52:24 +00006//
7//===----------------------------------------------------------------------===//
8
Jonas Devlieghere796ac802019-02-11 23:13:08 +00009#include <memory>
Kate Stoneb9c1b512016-09-06 20:57:50 +000010#include <stdlib.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000011#include <string>
Caroline Tice4ab31c92010-10-12 21:57:09 +000012#include <vector>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013
Greg Clayton4a33d312011-06-23 17:59:56 +000014#include "CommandObjectScript.h"
Peter Collingbourne08405b62011-06-23 20:37:26 +000015#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000016
James Y Knight2ad48212018-05-22 22:53:50 +000017#include "Commands/CommandObjectApropos.h"
18#include "Commands/CommandObjectBreakpoint.h"
19#include "Commands/CommandObjectBugreport.h"
20#include "Commands/CommandObjectCommands.h"
21#include "Commands/CommandObjectDisassemble.h"
22#include "Commands/CommandObjectExpression.h"
23#include "Commands/CommandObjectFrame.h"
24#include "Commands/CommandObjectGUI.h"
25#include "Commands/CommandObjectHelp.h"
26#include "Commands/CommandObjectLanguage.h"
27#include "Commands/CommandObjectLog.h"
28#include "Commands/CommandObjectMemory.h"
29#include "Commands/CommandObjectPlatform.h"
30#include "Commands/CommandObjectPlugin.h"
31#include "Commands/CommandObjectProcess.h"
32#include "Commands/CommandObjectQuit.h"
33#include "Commands/CommandObjectRegister.h"
Jonas Devlieghere9e046f02018-11-13 19:18:16 +000034#include "Commands/CommandObjectReproducer.h"
James Y Knight2ad48212018-05-22 22:53:50 +000035#include "Commands/CommandObjectSettings.h"
36#include "Commands/CommandObjectSource.h"
37#include "Commands/CommandObjectStats.h"
38#include "Commands/CommandObjectTarget.h"
39#include "Commands/CommandObjectThread.h"
40#include "Commands/CommandObjectType.h"
41#include "Commands/CommandObjectVersion.h"
42#include "Commands/CommandObjectWatchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044#include "lldb/Core/Debugger.h"
Zachary Turner2c1f46d2015-07-30 20:28:07 +000045#include "lldb/Core/PluginManager.h"
Greg Clayton44d93782014-01-27 23:43:24 +000046#include "lldb/Core/StreamFile.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000047#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000048#include "lldb/Utility/State.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000049#include "lldb/Utility/Stream.h"
Pavel Labath38d06322017-06-29 14:32:17 +000050#include "lldb/Utility/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
Greg Clayton7d2ef162013-03-29 17:03:23 +000058#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000059#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000060#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000061#include "lldb/Interpreter/OptionValueProperties.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000062#include "lldb/Interpreter/Options.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000063#include "lldb/Interpreter/Property.h"
Pavel Labath145d95c2018-04-17 18:53:35 +000064#include "lldb/Utility/Args.h"
Enrico Granatab5887262012-10-29 21:18:03 +000065
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000067#include "lldb/Target/TargetList.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000068#include "lldb/Target/Thread.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000069
Saleem Abdulrasool28606952014-06-27 05:17:41 +000070#include "llvm/ADT/STLExtras.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000071#include "llvm/ADT/SmallString.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000072#include "llvm/Support/Path.h"
Sean Callanan237c3ed2016-12-14 21:31:31 +000073#include "llvm/Support/PrettyStackTrace.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000074
Chris Lattner30fdc8d2010-06-08 16:52:24 +000075using namespace lldb;
76using namespace lldb_private;
77
Adrian McCarthy2304b6f2015-04-23 20:00:25 +000078static const char *k_white_space = " \t\v";
Greg Clayton754a9362012-08-23 00:22:02 +000079
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +000080static constexpr const char *InitFileWarning =
81 "There is a .lldbinit file in the current directory which is not being "
82 "read.\n"
83 "To silence this warning without sourcing in the local .lldbinit,\n"
84 "add the following to the lldbinit file in your home directory:\n"
85 " settings set target.load-cwd-lldbinit false\n"
86 "To allow lldb to source .lldbinit files in the current working "
87 "directory,\n"
88 "set the value of this variable to true. Only do so if you understand "
89 "and\n"
90 "accept the security risk.";
Stefan Granitzc678ed72018-10-05 16:49:47 +000091
Jonas Devliegherea8ea5952019-07-29 16:41:30 +000092#define LLDB_PROPERTIES_interpreter
Jordan Rupprecht6a253d32019-07-29 17:22:10 +000093#include "InterpreterProperties.inc"
Kate Stoneb9c1b512016-09-06 20:57:50 +000094
95enum {
Jonas Devliegherea8ea5952019-07-29 16:41:30 +000096#define LLDB_PROPERTIES_interpreter
Jordan Rupprecht6a253d32019-07-29 17:22:10 +000097#include "InterpreterPropertiesEnum.inc"
Greg Clayton754a9362012-08-23 00:22:02 +000098};
99
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100ConstString &CommandInterpreter::GetStaticBroadcasterClass() {
101 static ConstString class_name("lldb.commandInterpreter");
102 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000103}
104
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105CommandInterpreter::CommandInterpreter(Debugger &debugger,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106 bool synchronous_execution)
107 : Broadcaster(debugger.GetBroadcasterManager(),
108 CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
109 Properties(OptionValuePropertiesSP(
110 new OptionValueProperties(ConstString("interpreter")))),
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000111 IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand),
Jonas Devlieghere70df51b2019-07-31 23:34:45 +0000112 m_debugger(debugger), m_synchronous_execution(true),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113 m_skip_lldbinit_files(false), m_skip_app_init_files(false),
Jonas Devlieghere2b29b432019-04-26 22:43:16 +0000114 m_command_io_handler_sp(), m_comment_char('#'),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000115 m_batch_command_mode(false), m_truncation_warning(eNoTruncation),
116 m_command_source_depth(0), m_num_errors(0), m_quit_requested(false),
117 m_stopped_for_crash(false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118 SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit");
119 SetEventName(eBroadcastBitResetPrompt, "reset-prompt");
120 SetEventName(eBroadcastBitQuitCommandReceived, "quit");
Jonas Devlieghere70df51b2019-07-31 23:34:45 +0000121 SetSynchronous(synchronous_execution);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000122 CheckInWithManager();
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000123 m_collection_sp->Initialize(g_interpreter_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000124}
125
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126bool CommandInterpreter::GetExpandRegexAliases() const {
127 const uint32_t idx = ePropertyExpandRegexAliases;
128 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000129 nullptr, idx, g_interpreter_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000130}
131
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132bool CommandInterpreter::GetPromptOnQuit() const {
133 const uint32_t idx = ePropertyPromptOnQuit;
134 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000135 nullptr, idx, g_interpreter_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000136}
Greg Clayton754a9362012-08-23 00:22:02 +0000137
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138void CommandInterpreter::SetPromptOnQuit(bool b) {
139 const uint32_t idx = ePropertyPromptOnQuit;
140 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ilia Kacf28be2015-03-23 22:45:13 +0000141}
142
Stefan Granitzc678ed72018-10-05 16:49:47 +0000143bool CommandInterpreter::GetEchoCommands() const {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000144 const uint32_t idx = ePropertyEchoCommands;
Stefan Granitzc678ed72018-10-05 16:49:47 +0000145 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000146 nullptr, idx, g_interpreter_properties[idx].default_uint_value != 0);
Stefan Granitzc678ed72018-10-05 16:49:47 +0000147}
148
149void CommandInterpreter::SetEchoCommands(bool b) {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000150 const uint32_t idx = ePropertyEchoCommands;
Stefan Granitzc678ed72018-10-05 16:49:47 +0000151 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
152}
153
154bool CommandInterpreter::GetEchoCommentCommands() const {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000155 const uint32_t idx = ePropertyEchoCommentCommands;
Stefan Granitzc678ed72018-10-05 16:49:47 +0000156 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000157 nullptr, idx, g_interpreter_properties[idx].default_uint_value != 0);
Stefan Granitzc678ed72018-10-05 16:49:47 +0000158}
159
160void CommandInterpreter::SetEchoCommentCommands(bool b) {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000161 const uint32_t idx = ePropertyEchoCommentCommands;
Stefan Granitzc678ed72018-10-05 16:49:47 +0000162 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
163}
164
Raphael Isemannc094d232018-07-11 17:18:01 +0000165void CommandInterpreter::AllowExitCodeOnQuit(bool allow) {
166 m_allow_exit_code = allow;
167 if (!allow)
168 m_quit_exit_code.reset();
169}
170
171bool CommandInterpreter::SetQuitExitCode(int exit_code) {
172 if (!m_allow_exit_code)
173 return false;
174 m_quit_exit_code = exit_code;
175 return true;
176}
177
178int CommandInterpreter::GetQuitExitCode(bool &exited) const {
179 exited = m_quit_exit_code.hasValue();
180 if (exited)
181 return *m_quit_exit_code;
182 return 0;
183}
184
Kate Stoneb9c1b512016-09-06 20:57:50 +0000185void CommandInterpreter::ResolveCommand(const char *command_line,
186 CommandReturnObject &result) {
187 std::string command = command_line;
188 if (ResolveCommandImpl(command, result) != nullptr) {
189 result.AppendMessageWithFormat("%s", command.c_str());
190 result.SetStatus(eReturnStatusSuccessFinishResult);
191 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000192}
193
Kate Stoneb9c1b512016-09-06 20:57:50 +0000194bool CommandInterpreter::GetStopCmdSourceOnError() const {
195 const uint32_t idx = ePropertyStopCmdSourceOnError;
196 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000197 nullptr, idx, g_interpreter_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000198}
199
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200bool CommandInterpreter::GetSpaceReplPrompts() const {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000201 const uint32_t idx = ePropertySpaceReplPrompts;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000203 nullptr, idx, g_interpreter_properties[idx].default_uint_value != 0);
Sean Callanan66810412015-10-19 23:11:07 +0000204}
205
Kate Stoneb9c1b512016-09-06 20:57:50 +0000206void CommandInterpreter::Initialize() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000207 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
208 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000209
Kate Stoneb9c1b512016-09-06 20:57:50 +0000210 CommandReturnObject result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000211
Kate Stoneb9c1b512016-09-06 20:57:50 +0000212 LoadCommandDictionary();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000213
Kate Stoneb9c1b512016-09-06 20:57:50 +0000214 // An alias arguments vector to reuse - reset it before use...
215 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
216
217 // Set up some initial aliases.
218 CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
219 if (cmd_obj_sp) {
220 AddAlias("q", cmd_obj_sp);
221 AddAlias("exit", cmd_obj_sp);
222 }
223
224 cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
225 if (cmd_obj_sp)
226 AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
227
228 cmd_obj_sp = GetCommandSPExact("process detach", false);
229 if (cmd_obj_sp) {
230 AddAlias("detach", cmd_obj_sp);
231 }
232
233 cmd_obj_sp = GetCommandSPExact("process continue", false);
234 if (cmd_obj_sp) {
235 AddAlias("c", cmd_obj_sp);
236 AddAlias("continue", cmd_obj_sp);
237 }
238
239 cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
240 if (cmd_obj_sp)
241 AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
242
243 cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
244 if (cmd_obj_sp)
245 AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
246
247 cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
248 if (cmd_obj_sp) {
249 AddAlias("stepi", cmd_obj_sp);
250 AddAlias("si", cmd_obj_sp);
251 }
252
253 cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
254 if (cmd_obj_sp) {
255 AddAlias("nexti", cmd_obj_sp);
256 AddAlias("ni", cmd_obj_sp);
257 }
258
259 cmd_obj_sp = GetCommandSPExact("thread step-in", false);
260 if (cmd_obj_sp) {
261 AddAlias("s", cmd_obj_sp);
262 AddAlias("step", cmd_obj_sp);
263 CommandAlias *sif_alias = AddAlias(
264 "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
265 if (sif_alias) {
266 sif_alias->SetHelp("Step through the current block, stopping if you step "
267 "directly into a function whose name matches the "
268 "TargetFunctionName.");
269 sif_alias->SetSyntax("sif <TargetFunctionName>");
Caroline Ticeca90c472011-05-06 21:37:15 +0000270 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000272
Kate Stoneb9c1b512016-09-06 20:57:50 +0000273 cmd_obj_sp = GetCommandSPExact("thread step-over", false);
274 if (cmd_obj_sp) {
275 AddAlias("n", cmd_obj_sp);
276 AddAlias("next", cmd_obj_sp);
277 }
278
279 cmd_obj_sp = GetCommandSPExact("thread step-out", false);
280 if (cmd_obj_sp) {
281 AddAlias("finish", cmd_obj_sp);
282 }
283
284 cmd_obj_sp = GetCommandSPExact("frame select", false);
285 if (cmd_obj_sp) {
286 AddAlias("f", cmd_obj_sp);
287 }
288
289 cmd_obj_sp = GetCommandSPExact("thread select", false);
290 if (cmd_obj_sp) {
291 AddAlias("t", cmd_obj_sp);
292 }
293
294 cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
295 if (cmd_obj_sp) {
296 AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
297 AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
298 }
299
300 cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
301 if (cmd_obj_sp) {
302 AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
303 AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
304 }
305
306 cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
307 if (cmd_obj_sp)
308 AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
309
310 cmd_obj_sp = GetCommandSPExact("memory read", false);
311 if (cmd_obj_sp)
312 AddAlias("x", cmd_obj_sp);
313
314 cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
315 if (cmd_obj_sp)
316 AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
317
318 cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
319 if (cmd_obj_sp)
320 AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
321
322 cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
323 if (cmd_obj_sp)
324 AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
325
326 cmd_obj_sp = GetCommandSPExact("disassemble", false);
327 if (cmd_obj_sp)
328 AddAlias("dis", cmd_obj_sp);
329
330 cmd_obj_sp = GetCommandSPExact("disassemble", false);
331 if (cmd_obj_sp)
332 AddAlias("di", cmd_obj_sp);
333
334 cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
335 if (cmd_obj_sp)
336 AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
337
338 cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
339 if (cmd_obj_sp)
340 AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
341
342 cmd_obj_sp = GetCommandSPExact("target create", false);
343 if (cmd_obj_sp)
344 AddAlias("file", cmd_obj_sp);
345
346 cmd_obj_sp = GetCommandSPExact("target modules", false);
347 if (cmd_obj_sp)
348 AddAlias("image", cmd_obj_sp);
349
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000350 alias_arguments_vector_sp = std::make_shared<OptionArgVector>();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351
352 cmd_obj_sp = GetCommandSPExact("expression", false);
353 if (cmd_obj_sp) {
354 AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
355 AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
356 AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
357 if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
358 po->SetHelp("Evaluate an expression on the current thread. Displays any "
359 "returned value with formatting "
360 "controlled by the type's author.");
361 po->SetHelpLong("");
Johnny Chen6d675242012-08-24 18:15:45 +0000362 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363 AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
364 AddAlias("poarray", cmd_obj_sp,
365 "--object-description --element-count %1 --")
366 ->SetHelpLong("");
367 }
Johnny Chen6d675242012-08-24 18:15:45 +0000368
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 cmd_obj_sp = GetCommandSPExact("process kill", false);
370 if (cmd_obj_sp) {
371 AddAlias("kill", cmd_obj_sp);
372 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000373
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 cmd_obj_sp = GetCommandSPExact("process launch", false);
375 if (cmd_obj_sp) {
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000376 alias_arguments_vector_sp = std::make_shared<OptionArgVector>();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
378 AddAlias("r", cmd_obj_sp, "--");
379 AddAlias("run", cmd_obj_sp, "--");
Jason Molenda85da3122012-07-06 02:46:23 +0000380#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381#if defined(__APPLE__)
382 std::string shell_option;
383 shell_option.append("--shell-expand-args");
384 shell_option.append(" true");
385 shell_option.append(" --");
386 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
387 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
388#else
389 StreamString defaultshell;
390 defaultshell.Printf("--shell=%s --",
391 HostInfo::GetDefaultShell().GetPath().c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +0000392 AddAlias("r", cmd_obj_sp, defaultshell.GetString());
393 AddAlias("run", cmd_obj_sp, defaultshell.GetString());
Jason Molenda85da3122012-07-06 02:46:23 +0000394#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395#endif
396 }
397
398 cmd_obj_sp = GetCommandSPExact("target symbols add", false);
399 if (cmd_obj_sp) {
400 AddAlias("add-dsym", cmd_obj_sp);
401 }
402
403 cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
404 if (cmd_obj_sp) {
405 AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
406 }
Jim Ingham285ae0c2018-10-10 00:51:30 +0000407
408 cmd_obj_sp = GetCommandSPExact("frame variable", false);
409 if (cmd_obj_sp) {
Jim Ingham9082c1c2018-10-12 18:46:02 +0000410 AddAlias("v", cmd_obj_sp);
Jim Ingham285ae0c2018-10-10 00:51:30 +0000411 AddAlias("var", cmd_obj_sp);
412 AddAlias("vo", cmd_obj_sp, "--object-description");
413 }
Jonas Devliegheree5f7d602019-05-03 20:37:09 +0000414
415 cmd_obj_sp = GetCommandSPExact("register", false);
416 if (cmd_obj_sp) {
417 AddAlias("re", cmd_obj_sp);
418 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000419}
420
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421void CommandInterpreter::Clear() {
422 m_command_io_handler_sp.reset();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000423}
424
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
426 // This function has not yet been implemented.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000427
Kate Stoneb9c1b512016-09-06 20:57:50 +0000428 // Look for any embedded script command
429 // If found,
430 // get interpreter object from the command dictionary,
431 // call execute_one_command on it,
432 // get the results as a string,
433 // substitute that string for current stuff.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000434
Kate Stoneb9c1b512016-09-06 20:57:50 +0000435 return arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000436}
437
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438void CommandInterpreter::LoadCommandDictionary() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000439 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
440 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000441
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000443
Kate Stoneb9c1b512016-09-06 20:57:50 +0000444 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
445 m_command_dict["breakpoint"] =
446 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
447 m_command_dict["bugreport"] =
448 CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
449 m_command_dict["command"] =
450 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
451 m_command_dict["disassemble"] =
452 CommandObjectSP(new CommandObjectDisassemble(*this));
453 m_command_dict["expression"] =
454 CommandObjectSP(new CommandObjectExpression(*this));
455 m_command_dict["frame"] =
456 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
457 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
458 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
459 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
460 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
461 m_command_dict["platform"] =
462 CommandObjectSP(new CommandObjectPlatform(*this));
463 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
464 m_command_dict["process"] =
465 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
466 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
467 m_command_dict["register"] =
468 CommandObjectSP(new CommandObjectRegister(*this));
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000469 m_command_dict["reproducer"] =
470 CommandObjectSP(new CommandObjectReproducer(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000471 m_command_dict["script"] =
472 CommandObjectSP(new CommandObjectScript(*this, script_language));
473 m_command_dict["settings"] =
474 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
475 m_command_dict["source"] =
476 CommandObjectSP(new CommandObjectMultiwordSource(*this));
Davide Italiano24fff242018-04-13 18:02:39 +0000477 m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000478 m_command_dict["target"] =
479 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
480 m_command_dict["thread"] =
481 CommandObjectSP(new CommandObjectMultiwordThread(*this));
482 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
483 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
484 m_command_dict["watchpoint"] =
485 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
486 m_command_dict["language"] =
487 CommandObjectSP(new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000488
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 const char *break_regexes[][2] = {
490 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
491 "breakpoint set --file '%1' --line %2"},
492 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
493 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
494 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
495 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
496 "breakpoint set --name '%1'"},
497 {"^(-.*)$", "breakpoint set %1"},
498 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
499 "breakpoint set --name '%2' --shlib '%1'"},
500 {"^\\&(.*[^[:space:]])[[:space:]]*$",
501 "breakpoint set --name '%1' --skip-prologue=0"},
502 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
503 "breakpoint set --name '%1'"}};
Kate Stone7428a182016-07-14 22:03:10 +0000504
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000506
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000507 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508 new CommandObjectRegexCommand(
509 *this, "_regexp-break",
Raphael Isemann129fe892018-07-30 21:41:13 +0000510 "Set a breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000511 "\n"
512 "_regexp-break <filename>:<linenum>\n"
513 " main.c:12 // Break at line 12 of "
514 "main.c\n\n"
515 "_regexp-break <linenum>\n"
516 " 12 // Break at line 12 of current "
517 "file\n\n"
518 "_regexp-break 0x<address>\n"
519 " 0x1234000 // Break at address "
520 "0x1234000\n\n"
521 "_regexp-break <name>\n"
522 " main // Break in 'main' after the "
523 "prologue\n\n"
524 "_regexp-break &<name>\n"
525 " &main // Break at first instruction "
526 "in 'main'\n\n"
527 "_regexp-break <module>`<name>\n"
528 " libc.so`malloc // Break in 'malloc' from "
529 "'libc.so'\n\n"
530 "_regexp-break /<source-regex>/\n"
531 " /break here/ // Break on source lines in "
532 "current file\n"
533 " // containing text 'break "
534 "here'.\n",
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000535 2,
536 CommandCompletions::eSymbolCompletion |
537 CommandCompletions::eSourceFileCompletion,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000539
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000540 if (break_regex_cmd_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 bool success = true;
542 for (size_t i = 0; i < num_regexes; i++) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000543 success = break_regex_cmd_up->AddRegexCommand(break_regexes[i][0],
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 break_regexes[i][1]);
545 if (!success)
546 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000547 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 success =
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000549 break_regex_cmd_up->AddRegexCommand("^$", "breakpoint list --full");
Jim Inghamffba2292011-03-22 02:29:32 +0000550
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551 if (success) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000552 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000553 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
Jim Inghamca36cd12012-10-05 19:16:31 +0000554 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 }
Jim Inghamca36cd12012-10-05 19:16:31 +0000556
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000557 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 new CommandObjectRegexCommand(
559 *this, "_regexp-tbreak",
Raphael Isemann129fe892018-07-30 21:41:13 +0000560 "Set a one-shot breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561 "\n"
562 "_regexp-break <filename>:<linenum>\n"
563 " main.c:12 // Break at line 12 of "
564 "main.c\n\n"
565 "_regexp-break <linenum>\n"
566 " 12 // Break at line 12 of current "
567 "file\n\n"
568 "_regexp-break 0x<address>\n"
569 " 0x1234000 // Break at address "
570 "0x1234000\n\n"
571 "_regexp-break <name>\n"
572 " main // Break in 'main' after the "
573 "prologue\n\n"
574 "_regexp-break &<name>\n"
575 " &main // Break at first instruction "
576 "in 'main'\n\n"
577 "_regexp-break <module>`<name>\n"
578 " libc.so`malloc // Break in 'malloc' from "
579 "'libc.so'\n\n"
580 "_regexp-break /<source-regex>/\n"
581 " /break here/ // Break on source lines in "
582 "current file\n"
583 " // containing text 'break "
584 "here'.\n",
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000585 2,
586 CommandCompletions::eSymbolCompletion |
587 CommandCompletions::eSourceFileCompletion,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000588 false));
589
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000590 if (tbreak_regex_cmd_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000591 bool success = true;
592 for (size_t i = 0; i < num_regexes; i++) {
593 // If you add a resultant command string longer than 1024 characters be
594 // sure to increase the size of this buffer.
595 char buffer[1024];
596 int num_printed =
Frederic Riss49c9d8b2018-06-18 04:34:33 +0000597 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1");
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000598 lldbassert(num_printed < 1024);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599 UNUSED_IF_ASSERT_DISABLED(num_printed);
600 success =
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000601 tbreak_regex_cmd_up->AddRegexCommand(break_regexes[i][0], buffer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000602 if (!success)
603 break;
Johnny Chen6d675242012-08-24 18:15:45 +0000604 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605 success =
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000606 tbreak_regex_cmd_up->AddRegexCommand("^$", "breakpoint list --full");
Kate Stone7428a182016-07-14 22:03:10 +0000607
Kate Stoneb9c1b512016-09-06 20:57:50 +0000608 if (success) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000609 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000610 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
611 tbreak_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000612 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613 }
Kate Stone7428a182016-07-14 22:03:10 +0000614
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000615 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000616 new CommandObjectRegexCommand(
617 *this, "_regexp-attach", "Attach to process by ID or name.",
618 "_regexp-attach <pid> | <process-name>", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000619 if (attach_regex_cmd_up) {
620 if (attach_regex_cmd_up->AddRegexCommand("^([0-9]+)[[:space:]]*$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000621 "process attach --pid %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000622 attach_regex_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
624 // specified get passed to
625 // 'process attach'
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000626 attach_regex_cmd_up->AddRegexCommand("^(.+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627 "process attach --name '%1'") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000628 attach_regex_cmd_up->AddRegexCommand("^$", "process attach")) {
629 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
631 attach_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000632 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000634
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000635 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000636 new CommandObjectRegexCommand(*this, "_regexp-down",
637 "Select a newer stack frame. Defaults to "
638 "moving one frame, a numeric argument can "
639 "specify an arbitrary number.",
640 "_regexp-down [<count>]", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000641 if (down_regex_cmd_up) {
642 if (down_regex_cmd_up->AddRegexCommand("^$", "frame select -r -1") &&
643 down_regex_cmd_up->AddRegexCommand("^([0-9]+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644 "frame select -r -%1")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000645 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000647 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000649
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000650 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000651 new CommandObjectRegexCommand(
652 *this, "_regexp-up",
653 "Select an older stack frame. Defaults to moving one "
654 "frame, a numeric argument can specify an arbitrary number.",
655 "_regexp-up [<count>]", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000656 if (up_regex_cmd_up) {
657 if (up_regex_cmd_up->AddRegexCommand("^$", "frame select -r 1") &&
658 up_regex_cmd_up->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
659 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000660 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000661 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000662 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000663
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000664 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000665 new CommandObjectRegexCommand(
666 *this, "_regexp-display",
667 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
668 "_regexp-display expression", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000669 if (display_regex_cmd_up) {
670 if (display_regex_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000671 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000672 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
674 display_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000675 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000676 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000677
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000678 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_up(
679 new CommandObjectRegexCommand(*this, "_regexp-undisplay",
680 "Stop displaying expression at every "
681 "stop (specified by stop-hook index.)",
682 "_regexp-undisplay stop-hook-number", 2, 0,
683 false));
684 if (undisplay_regex_cmd_up) {
685 if (undisplay_regex_cmd_up->AddRegexCommand("^([0-9]+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000686 "target stop-hook delete %1")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000687 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000688 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
689 undisplay_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000690 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000692
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000693 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000694 new CommandObjectRegexCommand(
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000695 *this, "gdb-remote",
696 "Connect to a process via remote GDB server. "
697 "If no host is specifed, localhost is assumed.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000699 if (connect_gdb_remote_cmd_up) {
700 if (connect_gdb_remote_cmd_up->AddRegexCommand(
Chris Bieneman51978f52017-04-27 16:13:58 +0000701 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
702 "process connect --plugin gdb-remote connect://%1:%2") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000703 connect_gdb_remote_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000704 "^([[:digit:]]+)$",
705 "process connect --plugin gdb-remote connect://localhost:%1")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000706 CommandObjectSP command_sp(connect_gdb_remote_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707 m_command_dict[command_sp->GetCommandName()] = command_sp;
Jason Molenda4cddfed2012-10-05 05:29:32 +0000708 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000709 }
Jason Molenda4cddfed2012-10-05 05:29:32 +0000710
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000711 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000712 new CommandObjectRegexCommand(
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000713 *this, "kdp-remote",
714 "Connect to a process via remote KDP server. "
715 "If no UDP port is specified, port 41139 is "
716 "assumed.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000718 if (connect_kdp_remote_cmd_up) {
719 if (connect_kdp_remote_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000720 "^([^:]+:[[:digit:]]+)$",
721 "process connect --plugin kdp-remote udp://%1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000722 connect_kdp_remote_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000723 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000724 CommandObjectSP command_sp(connect_kdp_remote_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Clayton6bade322013-02-01 23:33:03 +0000726 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727 }
Greg Clayton6bade322013-02-01 23:33:03 +0000728
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000729 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 new CommandObjectRegexCommand(
731 *this, "_regexp-bt",
732 "Show the current thread's call stack. Any numeric argument "
733 "displays at most that many "
Jim Inghame91ad7d2019-05-02 02:14:08 +0000734 "frames. The argument 'all' displays all threads. Use 'settings"
735 " set frame-format' to customize the printing of individual frames "
736 "and 'settings set thread-format' to customize the thread header.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000737 "bt [<digit> | all]", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000738 if (bt_regex_cmd_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739 // accept but don't document "bt -c <number>" -- before bt was a regex
Adrian Prantl05097242018-04-30 16:49:04 +0000740 // command if you wanted to backtrace three frames you would do "bt -c 3"
741 // but the intention is to have this emulate the gdb "bt" command and so
742 // now "bt 3" is the preferred form, in line with gdb.
Stella Stamenova5bac7062019-05-17 18:52:42 +0000743 if (bt_regex_cmd_up->AddRegexCommand("^([[:digit:]]+)[[:space:]]*$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000744 "thread backtrace -c %1") &&
Stella Stamenova5bac7062019-05-17 18:52:42 +0000745 bt_regex_cmd_up->AddRegexCommand("^-c ([[:digit:]]+)[[:space:]]*$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000746 "thread backtrace -c %1") &&
Stella Stamenova5bac7062019-05-17 18:52:42 +0000747 bt_regex_cmd_up->AddRegexCommand("^all[[:space:]]*$", "thread backtrace all") &&
748 bt_regex_cmd_up->AddRegexCommand("^[[:space:]]*$", "thread backtrace")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000749 CommandObjectSP command_sp(bt_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Claytonef5651d2013-02-12 18:52:24 +0000751 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 }
Greg Claytonef5651d2013-02-12 18:52:24 +0000753
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000754 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000755 new CommandObjectRegexCommand(
756 *this, "_regexp-list",
757 "List relevant source code using one of several shorthand formats.",
758 "\n"
759 "_regexp-list <file>:<line> // List around specific file/line\n"
760 "_regexp-list <line> // List current file around specified "
761 "line\n"
762 "_regexp-list <function-name> // List specified function\n"
763 "_regexp-list 0x<address> // List around specified address\n"
764 "_regexp-list -[<count>] // List previous <count> lines\n"
765 "_regexp-list // List subsequent lines",
766 2, CommandCompletions::eSourceFileCompletion, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000767 if (list_regex_cmd_up) {
768 if (list_regex_cmd_up->AddRegexCommand("^([0-9]+)[[:space:]]*$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000769 "source list --line %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000770 list_regex_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000771 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
772 "]*$",
773 "source list --file '%1' --line %2") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000774 list_regex_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
776 "source list --address %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000777 list_regex_cmd_up->AddRegexCommand("^-[[:space:]]*$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000778 "source list --reverse") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000779 list_regex_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000780 "^-([[:digit:]]+)[[:space:]]*$",
781 "source list --reverse --count %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000782 list_regex_cmd_up->AddRegexCommand("^(.+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783 "source list --name \"%1\"") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000784 list_regex_cmd_up->AddRegexCommand("^$", "source list")) {
785 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000786 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
Richard Mittonf86248d2013-09-12 02:20:34 +0000787 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000788 }
Richard Mittonf86248d2013-09-12 02:20:34 +0000789
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000790 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000791 new CommandObjectRegexCommand(
792 *this, "_regexp-env",
793 "Shorthand for viewing and setting environment variables.",
794 "\n"
Adrian McCarthy17c18a92019-06-25 23:13:16 +0000795 "_regexp-env // Show environment\n"
Kate Stoneb9c1b512016-09-06 20:57:50 +0000796 "_regexp-env <name>=<value> // Set an environment variable",
797 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000798 if (env_regex_cmd_up) {
799 if (env_regex_cmd_up->AddRegexCommand("^$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 "settings show target.env-vars") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000801 env_regex_cmd_up->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802 "settings set target.env-vars %1")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000803 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000804 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
805 }
806 }
807
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000808 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000809 new CommandObjectRegexCommand(
810 *this, "_regexp-jump", "Set the program counter to a new address.",
811 "\n"
812 "_regexp-jump <line>\n"
813 "_regexp-jump +<line-offset> | -<line-offset>\n"
814 "_regexp-jump <file>:<line>\n"
815 "_regexp-jump *<addr>\n",
816 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000817 if (jump_regex_cmd_up) {
818 if (jump_regex_cmd_up->AddRegexCommand("^\\*(.*)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000819 "thread jump --addr %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000820 jump_regex_cmd_up->AddRegexCommand("^([0-9]+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000821 "thread jump --line %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000822 jump_regex_cmd_up->AddRegexCommand("^([^:]+):([0-9]+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 "thread jump --file %1 --line %2") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000824 jump_regex_cmd_up->AddRegexCommand("^([+\\-][0-9]+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000825 "thread jump --by %1")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000826 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
828 }
829 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000830}
831
Kate Stoneb9c1b512016-09-06 20:57:50 +0000832int CommandInterpreter::GetCommandNamesMatchingPartialString(
Raphael Isemann7f888292018-09-13 21:26:00 +0000833 const char *cmd_str, bool include_aliases, StringList &matches,
834 StringList &descriptions) {
835 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches,
836 &descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000837
Kate Stoneb9c1b512016-09-06 20:57:50 +0000838 if (include_aliases) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000839 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches,
840 &descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000842
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843 return matches.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000844}
845
Raphael Isemann7f888292018-09-13 21:26:00 +0000846CommandObjectSP
847CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases,
848 bool exact, StringList *matches,
849 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000851
Zachary Turnera4496982016-10-05 21:14:38 +0000852 std::string cmd = cmd_str;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000853
Kate Stoneb9c1b512016-09-06 20:57:50 +0000854 if (HasCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000855 auto pos = m_command_dict.find(cmd);
Greg Claytonb5472782015-01-09 19:08:20 +0000856 if (pos != m_command_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000857 command_sp = pos->second;
858 }
859
860 if (include_aliases && HasAliases()) {
861 auto alias_pos = m_alias_dict.find(cmd);
862 if (alias_pos != m_alias_dict.end())
863 command_sp = alias_pos->second;
864 }
865
866 if (HasUserCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000867 auto pos = m_user_dict.find(cmd);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000868 if (pos != m_user_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000869 command_sp = pos->second;
870 }
871
872 if (!exact && !command_sp) {
873 // We will only get into here if we didn't find any exact matches.
874
875 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
876
877 StringList local_matches;
878 if (matches == nullptr)
879 matches = &local_matches;
880
881 unsigned int num_cmd_matches = 0;
882 unsigned int num_alias_matches = 0;
883 unsigned int num_user_matches = 0;
884
885 // Look through the command dictionaries one by one, and if we get only one
Adrian Prantl05097242018-04-30 16:49:04 +0000886 // match from any of them in toto, then return that, otherwise return an
887 // empty CommandObjectSP and the list of matches.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888
889 if (HasCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000890 num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str,
891 *matches, descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000892 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000893
894 if (num_cmd_matches == 1) {
895 cmd.assign(matches->GetStringAtIndex(0));
Zachary Turnera4496982016-10-05 21:14:38 +0000896 auto pos = m_command_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000897 if (pos != m_command_dict.end())
898 real_match_sp = pos->second;
899 }
900
901 if (include_aliases && HasAliases()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000902 num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str,
903 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904 }
905
906 if (num_alias_matches == 1) {
907 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
908 auto alias_pos = m_alias_dict.find(cmd);
909 if (alias_pos != m_alias_dict.end())
910 alias_match_sp = alias_pos->second;
911 }
912
913 if (HasUserCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000914 num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str,
915 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000916 }
917
918 if (num_user_matches == 1) {
919 cmd.assign(
920 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
921
Zachary Turnera4496982016-10-05 21:14:38 +0000922 auto pos = m_user_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000923 if (pos != m_user_dict.end())
924 user_match_sp = pos->second;
925 }
926
927 // If we got exactly one match, return that, otherwise return the match
928 // list.
929
930 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
931 if (num_cmd_matches)
932 return real_match_sp;
933 else if (num_alias_matches)
934 return alias_match_sp;
935 else
936 return user_match_sp;
937 }
938 } else if (matches && command_sp) {
Zachary Turnera4496982016-10-05 21:14:38 +0000939 matches->AppendString(cmd_str);
Raphael Isemann7f888292018-09-13 21:26:00 +0000940 if (descriptions)
941 descriptions->AppendString(command_sp->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942 }
943
944 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000945}
946
Zachary Turnera4496982016-10-05 21:14:38 +0000947bool CommandInterpreter::AddCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948 const lldb::CommandObjectSP &cmd_sp,
949 bool can_replace) {
950 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000951 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
952 "tried to add a CommandObject from a different interpreter");
Kate Stonea487aa42015-01-15 00:52:41 +0000953
Zachary Turnera4496982016-10-05 21:14:38 +0000954 if (name.empty())
955 return false;
956
957 std::string name_sstr(name);
958 auto name_iter = m_command_dict.find(name_sstr);
959 if (name_iter != m_command_dict.end()) {
960 if (!can_replace || !name_iter->second->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961 return false;
Zachary Turnera4496982016-10-05 21:14:38 +0000962 name_iter->second = cmd_sp;
963 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964 m_command_dict[name_sstr] = cmd_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000965 }
Zachary Turnera4496982016-10-05 21:14:38 +0000966 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000967}
968
Zachary Turnera483f572016-10-05 21:14:49 +0000969bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000970 const lldb::CommandObjectSP &cmd_sp,
971 bool can_replace) {
972 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000973 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
974 "tried to add a CommandObject from a different interpreter");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000975
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 if (!name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000977 // do not allow replacement of internal commands
Zachary Turnera483f572016-10-05 21:14:49 +0000978 if (CommandExists(name)) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000979 if (!can_replace)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980 return false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000981 if (!m_command_dict[name]->IsRemovable())
Greg Clayton5a314712011-10-14 07:41:33 +0000982 return false;
983 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000984
Zachary Turnera483f572016-10-05 21:14:49 +0000985 if (UserCommandExists(name)) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000986 if (!can_replace)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000987 return false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000988 if (!m_user_dict[name]->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000989 return false;
Caroline Tice844d2302010-12-09 22:52:49 +0000990 }
991
Kate Stoneb9c1b512016-09-06 20:57:50 +0000992 m_user_dict[name] = cmd_sp;
993 return true;
994 }
995 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000996}
997
Zachary Turnera4496982016-10-05 21:14:38 +0000998CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
999 bool include_aliases) const {
1000 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +00001001 // it's a multi-word command.
1002 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001003
Zachary Turnera4496982016-10-05 21:14:38 +00001004 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001005 return ret_val;
1006
1007 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +00001008 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009 else {
1010 // We have a multi-word command (seemingly), so we need to do more work.
1011 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +00001012 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001013 include_aliases, true, nullptr);
1014 if (cmd_obj_sp.get() != nullptr) {
Adrian Prantl05097242018-04-30 16:49:04 +00001015 // Loop through the rest of the words in the command (everything passed
1016 // in was supposed to be part of a command name), and find the
1017 // appropriate sub-command SP for each command word....
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 size_t end = cmd_words.GetArgumentCount();
1019 for (size_t j = 1; j < end; ++j) {
1020 if (cmd_obj_sp->IsMultiwordObject()) {
1021 cmd_obj_sp =
1022 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
1023 if (cmd_obj_sp.get() == nullptr)
1024 // The sub-command name was invalid. Fail and return the empty
1025 // 'ret_val'.
1026 return ret_val;
1027 } else
1028 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +00001029 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030 return ret_val;
1031 }
1032 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +00001033 // command objects for them. Assign the last object retrieved to
1034 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001035 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001036 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001037 }
1038 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001039}
1040
Raphael Isemann7f888292018-09-13 21:26:00 +00001041CommandObject *
1042CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
1043 StringList *matches,
1044 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 CommandObject *command_obj =
Raphael Isemann7f888292018-09-13 21:26:00 +00001046 GetCommandSP(cmd_str, false, true, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047
Kate Stoneb9c1b512016-09-06 20:57:50 +00001048 // If we didn't find an exact match to the command string in the commands,
Adrian Prantl05097242018-04-30 16:49:04 +00001049 // look in the aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001050
1051 if (command_obj)
1052 return command_obj;
1053
Raphael Isemann7f888292018-09-13 21:26:00 +00001054 command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001055
1056 if (command_obj)
1057 return command_obj;
1058
1059 // If there wasn't an exact match then look for an inexact one in just the
1060 // commands
Zachary Turnera4496982016-10-05 21:14:38 +00001061 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001062
1063 // Finally, if there wasn't an inexact match among the commands, look for an
Adrian Prantl05097242018-04-30 16:49:04 +00001064 // inexact match in both the commands and aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001065
1066 if (command_obj) {
1067 if (matches)
1068 matches->AppendString(command_obj->GetCommandName());
Raphael Isemann7f888292018-09-13 21:26:00 +00001069 if (descriptions)
1070 descriptions->AppendString(command_obj->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001071 return command_obj;
1072 }
1073
Raphael Isemann7f888292018-09-13 21:26:00 +00001074 return GetCommandSP(cmd_str, true, false, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001075}
1076
Zachary Turnera483f572016-10-05 21:14:49 +00001077bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001078 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001079}
1080
Zachary Turnera483f572016-10-05 21:14:49 +00001081bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1082 std::string &full_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001083 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1084 if (exact_match) {
1085 full_name.assign(cmd);
1086 return exact_match;
1087 } else {
1088 StringList matches;
1089 size_t num_alias_matches;
1090 num_alias_matches =
1091 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1092 if (num_alias_matches == 1) {
1093 // Make sure this isn't shadowing a command in the regular command space:
1094 StringList regular_matches;
1095 const bool include_aliases = false;
1096 const bool exact = false;
1097 CommandObjectSP cmd_obj_sp(
1098 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1099 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1100 return false;
1101 else {
1102 full_name.assign(matches.GetStringAtIndex(0));
1103 return true;
1104 }
1105 } else
1106 return false;
1107 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001108}
1109
Zachary Turnera483f572016-10-05 21:14:49 +00001110bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001111 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001112}
1113
Zachary Turnera483f572016-10-05 21:14:49 +00001114bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001115 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116}
1117
Kate Stoneb9c1b512016-09-06 20:57:50 +00001118CommandAlias *
Zachary Turnera483f572016-10-05 21:14:49 +00001119CommandInterpreter::AddAlias(llvm::StringRef alias_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001120 lldb::CommandObjectSP &command_obj_sp,
Zachary Turnera483f572016-10-05 21:14:49 +00001121 llvm::StringRef args_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122 if (command_obj_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001123 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1124 "tried to add a CommandObject from a different interpreter");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125
1126 std::unique_ptr<CommandAlias> command_alias_up(
1127 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1128
1129 if (command_alias_up && command_alias_up->IsValid()) {
1130 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1131 return command_alias_up.release();
1132 }
1133
1134 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001135}
1136
Zachary Turnera483f572016-10-05 21:14:49 +00001137bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001138 auto pos = m_alias_dict.find(alias_name);
1139 if (pos != m_alias_dict.end()) {
1140 m_alias_dict.erase(pos);
1141 return true;
1142 }
1143 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001144}
1145
Zachary Turnera483f572016-10-05 21:14:49 +00001146bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001147 auto pos = m_command_dict.find(cmd);
1148 if (pos != m_command_dict.end()) {
1149 if (pos->second->IsRemovable()) {
1150 // Only regular expression objects or python commands are removable
1151 m_command_dict.erase(pos);
1152 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001153 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001154 }
1155 return false;
1156}
Zachary Turnera483f572016-10-05 21:14:49 +00001157bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001158 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1159 if (pos != m_user_dict.end()) {
1160 m_user_dict.erase(pos);
1161 return true;
1162 }
1163 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001164}
1165
Kate Stoneb9c1b512016-09-06 20:57:50 +00001166void CommandInterpreter::GetHelp(CommandReturnObject &result,
1167 uint32_t cmd_types) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001168 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1169 if (!help_prologue.empty()) {
1170 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1171 help_prologue);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001172 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001173
Kate Stoneb9c1b512016-09-06 20:57:50 +00001174 CommandObject::CommandMap::const_iterator pos;
1175 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001176
Kate Stoneb9c1b512016-09-06 20:57:50 +00001177 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1178 result.AppendMessage("Debugger commands:");
1179 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001180
Kate Stoneb9c1b512016-09-06 20:57:50 +00001181 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1182 if (!(cmd_types & eCommandTypesHidden) &&
1183 (pos->first.compare(0, 1, "_") == 0))
1184 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001185
Zachary Turner0ac5f982016-11-08 04:12:42 +00001186 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1187 pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001188 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001189 result.AppendMessage("");
1190 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001191
Kate Stoneb9c1b512016-09-06 20:57:50 +00001192 if (!m_alias_dict.empty() &&
1193 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1194 result.AppendMessageWithFormat(
1195 "Current command abbreviations "
1196 "(type '%shelp command alias' for more info):\n",
1197 GetCommandPrefix());
1198 result.AppendMessage("");
1199 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001200
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1202 ++alias_pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001203 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001205 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001206 result.AppendMessage("");
1207 }
Greg Clayton14a35512011-09-11 00:01:44 +00001208
Kate Stoneb9c1b512016-09-06 20:57:50 +00001209 if (!m_user_dict.empty() &&
1210 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1211 result.AppendMessage("Current user-defined commands:");
1212 result.AppendMessage("");
1213 max_len = FindLongestCommandWord(m_user_dict);
1214 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001215 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1216 pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001217 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001218 result.AppendMessage("");
1219 }
Greg Clayton14a35512011-09-11 00:01:44 +00001220
Kate Stoneb9c1b512016-09-06 20:57:50 +00001221 result.AppendMessageWithFormat(
1222 "For more information on any command, type '%shelp <command-name>'.\n",
1223 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001224}
1225
Zachary Turnera01bccd2016-10-05 21:14:56 +00001226CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1227 llvm::StringRef &command_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001228 // This function finds the final, lowest-level, alias-resolved command object
Adrian Prantl05097242018-04-30 16:49:04 +00001229 // whose 'Execute' function will eventually be invoked by the given command
1230 // line.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001231
1232 CommandObject *cmd_obj = nullptr;
1233 size_t start = command_string.find_first_not_of(k_white_space);
1234 size_t end = 0;
1235 bool done = false;
1236 while (!done) {
1237 if (start != std::string::npos) {
1238 // Get the next word from command_string.
1239 end = command_string.find_first_of(k_white_space, start);
1240 if (end == std::string::npos)
1241 end = command_string.size();
1242 std::string cmd_word = command_string.substr(start, end - start);
1243
1244 if (cmd_obj == nullptr)
1245 // Since cmd_obj is NULL we are on our first time through this loop.
Zachary Turnera01bccd2016-10-05 21:14:56 +00001246 // Check to see if cmd_word is a valid command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001247 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001248 else if (cmd_obj->IsMultiwordObject()) {
1249 // Our current object is a multi-word object; see if the cmd_word is a
1250 // valid sub-command for our object.
1251 CommandObject *sub_cmd_obj =
1252 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1253 if (sub_cmd_obj)
1254 cmd_obj = sub_cmd_obj;
1255 else // cmd_word was not a valid sub-command word, so we are done
1256 done = true;
1257 } else
1258 // We have a cmd_obj and it is not a multi-word object, so we are done.
1259 done = true;
1260
1261 // If we didn't find a valid command object, or our command object is not
Zachary Turnera01bccd2016-10-05 21:14:56 +00001262 // a multi-word object, or we are at the end of the command_string, then
1263 // we are done. Otherwise, find the start of the next word.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001264
1265 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1266 end >= command_string.size())
1267 done = true;
1268 else
1269 start = command_string.find_first_not_of(k_white_space, end);
1270 } else
1271 // Unable to find any more words.
1272 done = true;
1273 }
1274
Zachary Turnera01bccd2016-10-05 21:14:56 +00001275 command_string = command_string.substr(end);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001276 return cmd_obj;
1277}
1278
1279static const char *k_valid_command_chars =
1280 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1281static void StripLeadingSpaces(std::string &s) {
1282 if (!s.empty()) {
1283 size_t pos = s.find_first_not_of(k_white_space);
1284 if (pos == std::string::npos)
1285 s.clear();
1286 else if (pos == 0)
1287 return;
1288 s.erase(0, pos);
1289 }
1290}
1291
1292static size_t FindArgumentTerminator(const std::string &s) {
1293 const size_t s_len = s.size();
1294 size_t offset = 0;
1295 while (offset < s_len) {
1296 size_t pos = s.find("--", offset);
1297 if (pos == std::string::npos)
1298 break;
1299 if (pos > 0) {
1300 if (isspace(s[pos - 1])) {
Adrian Prantl05097242018-04-30 16:49:04 +00001301 // Check if the string ends "\s--" (where \s is a space character) or
1302 // if we have "\s--\s".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001303 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1304 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001305 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001306 }
1307 }
1308 offset = pos + 2;
1309 }
1310 return std::string::npos;
1311}
1312
1313static bool ExtractCommand(std::string &command_string, std::string &command,
1314 std::string &suffix, char &quote_char) {
1315 command.clear();
1316 suffix.clear();
1317 StripLeadingSpaces(command_string);
1318
1319 bool result = false;
1320 quote_char = '\0';
1321
1322 if (!command_string.empty()) {
1323 const char first_char = command_string[0];
1324 if (first_char == '\'' || first_char == '"') {
1325 quote_char = first_char;
1326 const size_t end_quote_pos = command_string.find(quote_char, 1);
1327 if (end_quote_pos == std::string::npos) {
1328 command.swap(command_string);
1329 command_string.erase();
1330 } else {
1331 command.assign(command_string, 1, end_quote_pos - 1);
1332 if (end_quote_pos + 1 < command_string.size())
1333 command_string.erase(0, command_string.find_first_not_of(
1334 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001335 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001336 command_string.erase();
1337 }
1338 } else {
1339 const size_t first_space_pos =
1340 command_string.find_first_of(k_white_space);
1341 if (first_space_pos == std::string::npos) {
1342 command.swap(command_string);
1343 command_string.erase();
1344 } else {
1345 command.assign(command_string, 0, first_space_pos);
1346 command_string.erase(0, command_string.find_first_not_of(
1347 k_white_space, first_space_pos));
1348 }
1349 }
1350 result = true;
1351 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001352
Kate Stoneb9c1b512016-09-06 20:57:50 +00001353 if (!command.empty()) {
1354 // actual commands can't start with '-' or '_'
1355 if (command[0] != '-' && command[0] != '_') {
1356 size_t pos = command.find_first_not_of(k_valid_command_chars);
1357 if (pos > 0 && pos != std::string::npos) {
1358 suffix.assign(command.begin() + pos, command.end());
1359 command.erase(pos);
1360 }
1361 }
1362 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001363
Kate Stoneb9c1b512016-09-06 20:57:50 +00001364 return result;
1365}
1366
1367CommandObject *CommandInterpreter::BuildAliasResult(
Zachary Turnera483f572016-10-05 21:14:49 +00001368 llvm::StringRef alias_name, std::string &raw_input_string,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001369 std::string &alias_result, CommandReturnObject &result) {
1370 CommandObject *alias_cmd_obj = nullptr;
1371 Args cmd_args(raw_input_string);
1372 alias_cmd_obj = GetCommandObject(alias_name);
1373 StreamString result_str;
1374
Zachary Turner5c28c662016-10-03 23:20:36 +00001375 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1376 alias_result.clear();
1377 return alias_cmd_obj;
1378 }
1379 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1380 ((CommandAlias *)alias_cmd_obj)->Desugar();
1381 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1382 alias_cmd_obj = desugared.first.get();
1383 std::string alias_name_str = alias_name;
1384 if ((cmd_args.GetArgumentCount() == 0) ||
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001385 (alias_name_str != cmd_args.GetArgumentAtIndex(0)))
Zachary Turner5c28c662016-10-03 23:20:36 +00001386 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001387
Zachary Turnera4496982016-10-05 21:14:38 +00001388 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001389
Zachary Turner5c28c662016-10-03 23:20:36 +00001390 if (!option_arg_vector_sp.get()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001391 alias_result = result_str.GetString();
Zachary Turner5c28c662016-10-03 23:20:36 +00001392 return alias_cmd_obj;
1393 }
1394 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395
Zachary Turner5c28c662016-10-03 23:20:36 +00001396 int value_type;
1397 std::string option;
1398 std::string value;
1399 for (const auto &entry : *option_arg_vector) {
1400 std::tie(option, value_type, value) = entry;
1401 if (option == "<argument>") {
1402 result_str.Printf(" %s", value.c_str());
1403 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001404 }
1405
Zachary Turner5c28c662016-10-03 23:20:36 +00001406 result_str.Printf(" %s", option.c_str());
1407 if (value_type == OptionParser::eNoArgument)
1408 continue;
1409
1410 if (value_type != OptionParser::eOptionalArgument)
1411 result_str.Printf(" ");
1412 int index = GetOptionArgumentPosition(value.c_str());
1413 if (index == 0)
1414 result_str.Printf("%s", value.c_str());
1415 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1416
1417 result.AppendErrorWithFormat("Not enough arguments provided; you "
1418 "need at least %d arguments to use "
1419 "this alias.\n",
1420 index);
1421 result.SetStatus(eReturnStatusFailed);
1422 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001423 } else {
1424 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1425 if (strpos != std::string::npos)
1426 raw_input_string = raw_input_string.erase(
1427 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1428 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001429 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001430 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001431
Zachary Turnerc1564272016-11-16 21:15:24 +00001432 alias_result = result_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001433 return alias_cmd_obj;
1434}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001435
Zachary Turner97206d52017-05-12 04:51:55 +00001436Status CommandInterpreter::PreprocessCommand(std::string &command) {
Adrian Prantl05097242018-04-30 16:49:04 +00001437 // The command preprocessor needs to do things to the command line before any
1438 // parsing of arguments or anything else is done. The only current stuff that
1439 // gets preprocessed is anything enclosed in backtick ('`') characters is
1440 // evaluated as an expression and the result of the expression must be a
1441 // scalar that can be substituted into the command. An example would be:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001442 // (lldb) memory read `$rsp + 20`
Zachary Turner97206d52017-05-12 04:51:55 +00001443 Status error; // Status for any expressions that might not evaluate
Kate Stoneb9c1b512016-09-06 20:57:50 +00001444 size_t start_backtick;
1445 size_t pos = 0;
1446 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001447 // Stop if an error was encountered during the previous iteration.
1448 if (error.Fail())
1449 break;
1450
Kate Stoneb9c1b512016-09-06 20:57:50 +00001451 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
Adrian Prantl05097242018-04-30 16:49:04 +00001452 // The backtick was preceded by a '\' character, remove the slash and
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001453 // don't treat the backtick as the start of an expression.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001454 command.erase(start_backtick - 1, 1);
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001455 // No need to add one to start_backtick since we just deleted a char.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001456 pos = start_backtick;
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001457 continue;
1458 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001459
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001460 const size_t expr_content_start = start_backtick + 1;
1461 const size_t end_backtick = command.find('`', expr_content_start);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001462
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001463 if (end_backtick == std::string::npos) {
1464 // Stop if there's no end backtick.
1465 break;
1466 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001467
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001468 if (end_backtick == expr_content_start) {
1469 // Skip over empty expression. (two backticks in a row)
1470 command.erase(start_backtick, 2);
1471 continue;
1472 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001473
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001474 std::string expr_str(command, expr_content_start,
1475 end_backtick - expr_content_start);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001476
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001477 ExecutionContext exe_ctx(GetExecutionContext());
1478 Target *target = exe_ctx.GetTargetPtr();
1479
1480 // Get a dummy target to allow for calculator mode while processing
1481 // backticks. This also helps break the infinite loop caused when target is
1482 // null.
1483 if (!target)
1484 target = m_debugger.GetDummyTarget();
1485
1486 if (!target)
1487 continue;
1488
1489 ValueObjectSP expr_result_valobj_sp;
1490
1491 EvaluateExpressionOptions options;
1492 options.SetCoerceToId(false);
1493 options.SetUnwindOnError(true);
1494 options.SetIgnoreBreakpoints(true);
1495 options.SetKeepInMemory(false);
1496 options.SetTryAllThreads(true);
1497 options.SetTimeout(llvm::None);
1498
1499 ExpressionResults expr_result =
1500 target->EvaluateExpression(expr_str.c_str(), exe_ctx.GetFramePtr(),
1501 expr_result_valobj_sp, options);
1502
1503 if (expr_result == eExpressionCompleted) {
1504 Scalar scalar;
1505 if (expr_result_valobj_sp)
1506 expr_result_valobj_sp =
1507 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1508 expr_result_valobj_sp->GetDynamicValueType(), true);
1509 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1510 command.erase(start_backtick, end_backtick - start_backtick + 1);
1511 StreamString value_strm;
1512 const bool show_type = false;
1513 scalar.GetValue(&value_strm, show_type);
1514 size_t value_string_size = value_strm.GetSize();
1515 if (value_string_size) {
1516 command.insert(start_backtick, value_strm.GetString());
1517 pos = start_backtick + value_string_size;
1518 continue;
1519 } else {
1520 error.SetErrorStringWithFormat("expression value didn't result "
1521 "in a scalar value for the "
1522 "expression '%s'",
1523 expr_str.c_str());
1524 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001525 }
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001526 } else {
1527 error.SetErrorStringWithFormat("expression value didn't result "
1528 "in a scalar value for the "
1529 "expression '%s'",
1530 expr_str.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001531 break;
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001532 }
1533
1534 continue;
1535 }
1536
1537 if (expr_result_valobj_sp)
1538 error = expr_result_valobj_sp->GetError();
1539
1540 if (error.Success()) {
1541 switch (expr_result) {
1542 case eExpressionSetupError:
1543 error.SetErrorStringWithFormat(
1544 "expression setup error for the expression '%s'", expr_str.c_str());
1545 break;
1546 case eExpressionParseError:
1547 error.SetErrorStringWithFormat(
1548 "expression parse error for the expression '%s'", expr_str.c_str());
1549 break;
1550 case eExpressionResultUnavailable:
1551 error.SetErrorStringWithFormat(
1552 "expression error fetching result for the expression '%s'",
1553 expr_str.c_str());
1554 break;
1555 case eExpressionCompleted:
1556 break;
1557 case eExpressionDiscarded:
1558 error.SetErrorStringWithFormat(
1559 "expression discarded for the expression '%s'", expr_str.c_str());
1560 break;
1561 case eExpressionInterrupted:
1562 error.SetErrorStringWithFormat(
1563 "expression interrupted for the expression '%s'", expr_str.c_str());
1564 break;
1565 case eExpressionHitBreakpoint:
1566 error.SetErrorStringWithFormat(
1567 "expression hit breakpoint for the expression '%s'",
1568 expr_str.c_str());
1569 break;
1570 case eExpressionTimedOut:
1571 error.SetErrorStringWithFormat(
1572 "expression timed out for the expression '%s'", expr_str.c_str());
1573 break;
1574 case eExpressionStoppedForDebug:
1575 error.SetErrorStringWithFormat("expression stop at entry point "
1576 "for debugging for the "
1577 "expression '%s'",
1578 expr_str.c_str());
1579 break;
1580 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001581 }
1582 }
1583 return error;
1584}
1585
1586bool CommandInterpreter::HandleCommand(const char *command_line,
1587 LazyBool lazy_add_to_history,
1588 CommandReturnObject &result,
1589 ExecutionContext *override_context,
1590 bool repeat_on_empty_command,
1591 bool no_context_switching)
1592
1593{
1594
1595 std::string command_string(command_line);
1596 std::string original_command_string(command_line);
1597
1598 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
Jim Ingham8f7db522016-12-15 00:30:30 +00001599 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
Sean Callanan237c3ed2016-12-14 21:31:31 +00001600 command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001601
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001602 LLDB_LOGF(log, "Processing command: %s", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001603
Pavel Labathf9d16472017-05-15 13:02:37 +00001604 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1605 Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001606
1607 if (!no_context_switching)
1608 UpdateExecutionContext(override_context);
1609
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001610 if (WasInterrupted()) {
1611 result.AppendError("interrupted");
1612 result.SetStatus(eReturnStatusFailed);
1613 return false;
1614 }
1615
Kate Stoneb9c1b512016-09-06 20:57:50 +00001616 bool add_to_history;
1617 if (lazy_add_to_history == eLazyBoolCalculate)
1618 add_to_history = (m_command_source_depth == 0);
1619 else
1620 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1621
1622 bool empty_command = false;
1623 bool comment_command = false;
1624 if (command_string.empty())
1625 empty_command = true;
1626 else {
1627 const char *k_space_characters = "\t\n\v\f\r ";
1628
1629 size_t non_space = command_string.find_first_not_of(k_space_characters);
Adrian Prantl05097242018-04-30 16:49:04 +00001630 // Check for empty line or comment line (lines whose first non-space
1631 // character is the comment character for this interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001632 if (non_space == std::string::npos)
1633 empty_command = true;
1634 else if (command_string[non_space] == m_comment_char)
1635 comment_command = true;
1636 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001637 llvm::StringRef search_str(command_string);
1638 search_str = search_str.drop_front(non_space);
1639 if (auto hist_str = m_command_history.FindString(search_str)) {
1640 add_to_history = false;
1641 command_string = *hist_str;
1642 original_command_string = *hist_str;
1643 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001644 result.AppendErrorWithFormat("Could not find entry: %s in history",
1645 command_string.c_str());
1646 result.SetStatus(eReturnStatusFailed);
1647 return false;
1648 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001649 }
1650 }
1651
1652 if (empty_command) {
1653 if (repeat_on_empty_command) {
1654 if (m_command_history.IsEmpty()) {
1655 result.AppendError("empty command");
1656 result.SetStatus(eReturnStatusFailed);
1657 return false;
1658 } else {
1659 command_line = m_repeat_command.c_str();
1660 command_string = command_line;
1661 original_command_string = command_line;
1662 if (m_repeat_command.empty()) {
1663 result.AppendErrorWithFormat("No auto repeat.\n");
1664 result.SetStatus(eReturnStatusFailed);
1665 return false;
1666 }
1667 }
1668 add_to_history = false;
1669 } else {
1670 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1671 return true;
1672 }
1673 } else if (comment_command) {
1674 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1675 return true;
1676 }
1677
Zachary Turner97206d52017-05-12 04:51:55 +00001678 Status error(PreprocessCommand(command_string));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001679
1680 if (error.Fail()) {
1681 result.AppendError(error.AsCString());
1682 result.SetStatus(eReturnStatusFailed);
1683 return false;
1684 }
1685
1686 // Phase 1.
1687
1688 // Before we do ANY kind of argument processing, we need to figure out what
1689 // the real/final command object is for the specified command. This gets
1690 // complicated by the fact that the user could have specified an alias, and,
1691 // in translating the alias, there may also be command options and/or even
1692 // data (including raw text strings) that need to be found and inserted into
1693 // the command line as part of the translation. So this first step is plain
1694 // look-up and replacement, resulting in:
1695 // 1. the command object whose Execute method will actually be called
1696 // 2. a revised command string, with all substitutions and replacements
1697 // taken care of
1698 // From 1 above, we can determine whether the Execute function wants raw
1699 // input or not.
1700
1701 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1702
1703 // Although the user may have abbreviated the command, the command_string now
Adrian Prantl05097242018-04-30 16:49:04 +00001704 // has the command expanded to the full name. For example, if the input was
1705 // "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001706 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001707 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001708 LLDB_LOGF(log, "HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
1709 LLDB_LOGF(log, "HandleCommand, (revised) command_string: '%s'",
1710 command_string.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001711 const bool wants_raw_input =
Konrad Kleine248a1302019-05-23 11:14:47 +00001712 (cmd_obj != nullptr) ? cmd_obj->WantsRawCommandString() : false;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001713 LLDB_LOGF(log, "HandleCommand, wants_raw_input:'%s'",
1714 wants_raw_input ? "True" : "False");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001715 }
1716
1717 // Phase 2.
1718 // Take care of things like setting up the history command & calling the
Adrian Prantl05097242018-04-30 16:49:04 +00001719 // appropriate Execute method on the CommandObject, with the appropriate
1720 // arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001721
1722 if (cmd_obj != nullptr) {
1723 if (add_to_history) {
1724 Args command_args(command_string);
1725 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1726 if (repeat_command != nullptr)
1727 m_repeat_command.assign(repeat_command);
1728 else
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001729 m_repeat_command.assign(original_command_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730
1731 m_command_history.AppendString(original_command_string);
1732 }
1733
1734 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001735 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001736 if (actual_cmd_name_len < command_string.length())
1737 remainder = command_string.substr(actual_cmd_name_len);
1738
1739 // Remove any initial spaces
1740 size_t pos = remainder.find_first_not_of(k_white_space);
1741 if (pos != 0 && pos != std::string::npos)
1742 remainder.erase(0, pos);
1743
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001744 LLDB_LOGF(
1745 log, "HandleCommand, command line after removing command name(s): '%s'",
1746 remainder.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001747
1748 cmd_obj->Execute(remainder.c_str(), result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001749 }
1750
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001751 LLDB_LOGF(log, "HandleCommand, command %s",
1752 (result.Succeeded() ? "succeeded" : "did not succeed"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001753
1754 return result.Succeeded();
1755}
1756
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001757int CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001758 int num_command_matches = 0;
1759 bool look_for_subcommand = false;
1760
1761 // For any of the command completions a unique match will be a complete word.
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001762 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001763
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001764 if (request.GetCursorIndex() == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001765 // We got nothing on the command line, so return the list of commands
1766 bool include_aliases = true;
Raphael Isemann7f888292018-09-13 21:26:00 +00001767 StringList new_matches, descriptions;
1768 num_command_matches = GetCommandNamesMatchingPartialString(
1769 "", include_aliases, new_matches, descriptions);
1770 request.AddCompletions(new_matches, descriptions);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001771 } else if (request.GetCursorIndex() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001772 // The cursor is in the first argument, so just do a lookup in the
1773 // dictionary.
Raphael Isemann7f888292018-09-13 21:26:00 +00001774 StringList new_matches, new_descriptions;
1775 CommandObject *cmd_obj =
1776 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0),
1777 &new_matches, &new_descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001778
1779 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001780 new_matches.GetStringAtIndex(0) != nullptr &&
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001781 strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001782 new_matches.GetStringAtIndex(0)) == 0) {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001783 if (request.GetParsedLine().GetArgumentCount() == 1) {
1784 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001785 } else {
1786 look_for_subcommand = true;
1787 num_command_matches = 0;
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001788 new_matches.DeleteStringAtIndex(0);
Raphael Isemann7f888292018-09-13 21:26:00 +00001789 new_descriptions.DeleteStringAtIndex(0);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001790 request.GetParsedLine().AppendArgument(llvm::StringRef());
1791 request.SetCursorIndex(request.GetCursorIndex() + 1);
1792 request.SetCursorCharPosition(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001793 }
1794 }
Raphael Isemann7f888292018-09-13 21:26:00 +00001795 request.AddCompletions(new_matches, new_descriptions);
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001796 num_command_matches = request.GetNumberOfMatches();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001797 }
1798
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001799 if (request.GetCursorIndex() > 0 || look_for_subcommand) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001800 // We are completing further on into a commands arguments, so find the
Adrian Prantl05097242018-04-30 16:49:04 +00001801 // command and tell it to complete the command. First see if there is a
1802 // matching initial command:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001803 CommandObject *command_object =
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001804 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001805 if (command_object == nullptr) {
1806 return 0;
1807 } else {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001808 request.GetParsedLine().Shift();
1809 request.SetCursorIndex(request.GetCursorIndex() - 1);
1810 num_command_matches = command_object->HandleCompletion(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001811 }
1812 }
1813
1814 return num_command_matches;
1815}
1816
Jonas Devlieghereb22860d2019-07-31 03:48:29 +00001817int CommandInterpreter::HandleCompletion(const char *current_line,
1818 const char *cursor,
1819 const char *last_char,
1820 StringList &matches,
1821 StringList &descriptions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001822
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001823 llvm::StringRef command_line(current_line, last_char - current_line);
Raphael Isemann7f888292018-09-13 21:26:00 +00001824 CompletionResult result;
Jonas Devlieghereb22860d2019-07-31 03:48:29 +00001825 CompletionRequest request(command_line, cursor - current_line, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001826 // Don't complete comments, and if the line we are completing is just the
Adrian Prantl05097242018-04-30 16:49:04 +00001827 // history repeat character, substitute the appropriate history line.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001828 const char *first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001829 if (first_arg) {
1830 if (first_arg[0] == m_comment_char)
1831 return 0;
1832 else if (first_arg[0] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001833 if (auto hist_str = m_command_history.FindString(first_arg)) {
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001834 matches.InsertStringAtIndex(0, *hist_str);
Raphael Isemann7f888292018-09-13 21:26:00 +00001835 descriptions.InsertStringAtIndex(0, "Previous command history event");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001836 return -2;
1837 } else
1838 return 0;
1839 }
1840 }
1841
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001842 int num_command_matches = HandleCompletionMatches(request);
Raphael Isemann7f888292018-09-13 21:26:00 +00001843 result.GetMatches(matches);
1844 result.GetDescriptions(descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001845
1846 if (num_command_matches <= 0)
1847 return num_command_matches;
1848
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001849 if (request.GetParsedLine().GetArgumentCount() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001850 // If we got an empty string, insert nothing.
1851 matches.InsertStringAtIndex(0, "");
Raphael Isemann7f888292018-09-13 21:26:00 +00001852 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001853 } else {
1854 // Now figure out if there is a common substring, and if so put that in
Adrian Prantl05097242018-04-30 16:49:04 +00001855 // element 0, otherwise put an empty string in element 0.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001856 std::string command_partial_str = request.GetCursorArgumentPrefix().str();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001857
Jonas Devlieghere175f09302019-07-31 03:26:10 +00001858 std::string common_prefix = matches.LongestCommonPrefix();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001859 const size_t partial_name_len = command_partial_str.size();
1860 common_prefix.erase(0, partial_name_len);
1861
Adrian Prantl05097242018-04-30 16:49:04 +00001862 // If we matched a unique single command, add a space... Only do this if
1863 // the completer told us this was a complete word, however...
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001864 if (num_command_matches == 1 && request.GetWordComplete()) {
1865 char quote_char = request.GetParsedLine()[request.GetCursorIndex()].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001866 common_prefix =
1867 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1868 if (quote_char != '\0')
1869 common_prefix.push_back(quote_char);
1870 common_prefix.push_back(' ');
1871 }
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001872 matches.InsertStringAtIndex(0, common_prefix.c_str());
Raphael Isemann7f888292018-09-13 21:26:00 +00001873 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001874 }
1875 return num_command_matches;
1876}
1877
1878CommandInterpreter::~CommandInterpreter() {}
1879
Zachary Turner514d8cd2016-09-23 18:06:53 +00001880void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001881 EventSP prompt_change_event_sp(
1882 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1883 ;
1884 BroadcastEvent(prompt_change_event_sp);
1885 if (m_command_io_handler_sp)
1886 m_command_io_handler_sp->SetPrompt(new_prompt);
1887}
1888
Zachary Turner7a120c82016-11-13 03:05:58 +00001889bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001890 // Check AutoConfirm first:
1891 if (m_debugger.GetAutoConfirm())
1892 return default_answer;
1893
1894 IOHandlerConfirm *confirm =
1895 new IOHandlerConfirm(m_debugger, message, default_answer);
1896 IOHandlerSP io_handler_sp(confirm);
1897 m_debugger.RunIOHandler(io_handler_sp);
1898 return confirm->GetResponse();
1899}
1900
Zachary Turnera483f572016-10-05 21:14:49 +00001901const CommandAlias *
1902CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001903 OptionArgVectorSP ret_val;
1904
Zachary Turnera483f572016-10-05 21:14:49 +00001905 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001906 if (pos != m_alias_dict.end())
1907 return (CommandAlias *)pos->second.get();
1908
1909 return nullptr;
1910}
1911
Zachary Turnera4496982016-10-05 21:14:38 +00001912bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001913
Zachary Turnera4496982016-10-05 21:14:38 +00001914bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001915
Zachary Turnera4496982016-10-05 21:14:38 +00001916bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001917
Zachary Turnera4496982016-10-05 21:14:38 +00001918bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001919
1920void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1921 const char *alias_name,
1922 Args &cmd_args,
1923 std::string &raw_input_string,
1924 CommandReturnObject &result) {
1925 OptionArgVectorSP option_arg_vector_sp =
1926 GetAlias(alias_name)->GetOptionArguments();
1927
1928 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1929
1930 // Make sure that the alias name is the 0th element in cmd_args
1931 std::string alias_name_str = alias_name;
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001932 if (alias_name_str != cmd_args.GetArgumentAtIndex(0))
Zachary Turner5c725f32016-09-19 21:56:59 +00001933 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001934
1935 Args new_args(alias_cmd_obj->GetCommandName());
1936 if (new_args.GetArgumentCount() == 2)
1937 new_args.Shift();
1938
1939 if (option_arg_vector_sp.get()) {
1940 if (wants_raw_input) {
1941 // We have a command that both has command options and takes raw input.
Adrian Prantl05097242018-04-30 16:49:04 +00001942 // Make *sure* it has a " -- " in the right place in the
1943 // raw_input_string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001944 size_t pos = raw_input_string.find(" -- ");
1945 if (pos == std::string::npos) {
1946 // None found; assume it goes at the beginning of the raw input string
1947 raw_input_string.insert(0, " -- ");
1948 }
1949 }
1950
1951 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1952 const size_t old_size = cmd_args.GetArgumentCount();
1953 std::vector<bool> used(old_size + 1, false);
1954
1955 used[0] = true;
1956
Zachary Turner5c28c662016-10-03 23:20:36 +00001957 int value_type;
1958 std::string option;
1959 std::string value;
1960 for (const auto &option_entry : *option_arg_vector) {
1961 std::tie(option, value_type, value) = option_entry;
1962 if (option == "<argument>") {
1963 if (!wants_raw_input || (value != "--")) {
1964 // Since we inserted this above, make sure we don't insert it twice
1965 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001966 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001967 continue;
1968 }
1969
1970 if (value_type != OptionParser::eOptionalArgument)
1971 new_args.AppendArgument(option);
1972
1973 if (value == "<no-argument>")
1974 continue;
1975
1976 int index = GetOptionArgumentPosition(value.c_str());
1977 if (index == 0) {
1978 // value was NOT a positional argument; must be a real value
1979 if (value_type != OptionParser::eOptionalArgument)
1980 new_args.AppendArgument(value);
1981 else {
1982 char buffer[255];
1983 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1984 value.c_str());
1985 new_args.AppendArgument(llvm::StringRef(buffer));
1986 }
1987
1988 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1989 result.AppendErrorWithFormat("Not enough arguments provided; you "
1990 "need at least %d arguments to use "
1991 "this alias.\n",
1992 index);
1993 result.SetStatus(eReturnStatusFailed);
1994 return;
1995 } else {
1996 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1997 size_t strpos =
1998 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1999 if (strpos != std::string::npos) {
2000 raw_input_string = raw_input_string.erase(
2001 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2002 }
2003
2004 if (value_type != OptionParser::eOptionalArgument)
2005 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2006 else {
2007 char buffer[255];
2008 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2009 cmd_args.GetArgumentAtIndex(index));
2010 new_args.AppendArgument(buffer);
2011 }
2012 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002013 }
2014 }
2015
Zachary Turner97d2c402016-10-05 23:40:23 +00002016 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00002017 if (!used[entry.index()] && !wants_raw_input)
2018 new_args.AppendArgument(entry.value().ref);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002019 }
2020
2021 cmd_args.Clear();
2022 cmd_args.SetArguments(new_args.GetArgumentCount(),
2023 new_args.GetConstArgumentVector());
2024 } else {
2025 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2026 // This alias was not created with any options; nothing further needs to be
Adrian Prantl05097242018-04-30 16:49:04 +00002027 // done, unless it is a command that wants raw input, in which case we need
2028 // to clear the rest of the data from cmd_args, since its in the raw input
2029 // string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002030 if (wants_raw_input) {
2031 cmd_args.Clear();
2032 cmd_args.SetArguments(new_args.GetArgumentCount(),
2033 new_args.GetConstArgumentVector());
2034 }
2035 return;
2036 }
2037
2038 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2039 return;
2040}
2041
2042int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2043 int position = 0; // Any string that isn't an argument position, i.e. '%'
2044 // followed by an integer, gets a position
2045 // of zero.
2046
2047 const char *cptr = in_string;
2048
2049 // Does it start with '%'
2050 if (cptr[0] == '%') {
2051 ++cptr;
2052
2053 // Is the rest of it entirely digits?
2054 if (isdigit(cptr[0])) {
2055 const char *start = cptr;
2056 while (isdigit(cptr[0]))
2057 ++cptr;
2058
Adrian Prantl05097242018-04-30 16:49:04 +00002059 // We've gotten to the end of the digits; are we at the end of the
2060 // string?
Kate Stoneb9c1b512016-09-06 20:57:50 +00002061 if (cptr[0] == '\0')
2062 position = atoi(start);
2063 }
2064 }
2065
2066 return position;
2067}
2068
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002069static void GetHomeInitFile(llvm::SmallVectorImpl<char> &init_file,
2070 llvm::StringRef suffix = {}) {
2071 std::string init_file_name = ".lldbinit";
2072 if (!suffix.empty()) {
2073 init_file_name.append("-");
2074 init_file_name.append(suffix.str());
2075 }
2076
2077 llvm::sys::path::home_directory(init_file);
2078 llvm::sys::path::append(init_file, init_file_name);
2079
2080 FileSystem::Instance().Resolve(init_file);
2081}
2082
2083static void GetCwdInitFile(llvm::SmallVectorImpl<char> &init_file) {
2084 llvm::StringRef s = ".lldbinit";
2085 init_file.assign(s.begin(), s.end());
2086 FileSystem::Instance().Resolve(init_file);
2087}
2088
2089static LoadCWDlldbinitFile ShouldLoadCwdInitFile() {
2090 lldb::TargetPropertiesSP properties = Target::GetGlobalProperties();
2091 if (!properties)
2092 return eLoadCWDlldbinitFalse;
2093 return properties->GetLoadCWDlldbinitFile();
2094}
2095
2096void CommandInterpreter::SourceInitFile(FileSpec file,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002097 CommandReturnObject &result) {
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002098 assert(!m_skip_lldbinit_files);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002099
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002100 if (!FileSystem::Instance().Exists(file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002101 result.SetStatus(eReturnStatusSuccessFinishNoResult);
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002102 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002103 }
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002104
2105 // Use HandleCommand to 'source' the given file; this will do the actual
2106 // broadcasting of the commands back to any appropriate listener (see
2107 // CommandObjectSource::Execute for more details).
2108 const bool saved_batch = SetBatchCommandMode(true);
2109 ExecutionContext *ctx = nullptr;
2110 CommandInterpreterRunOptions options;
2111 options.SetSilent(true);
2112 options.SetPrintErrors(true);
2113 options.SetStopOnError(false);
2114 options.SetStopOnContinue(true);
2115 HandleCommandsFromFile(file, ctx, options, result);
2116 SetBatchCommandMode(saved_batch);
2117}
2118
2119void CommandInterpreter::SourceInitFileCwd(CommandReturnObject &result) {
2120 if (m_skip_lldbinit_files) {
2121 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2122 return;
2123 }
2124
2125 llvm::SmallString<128> init_file;
2126 GetCwdInitFile(init_file);
2127 if (!FileSystem::Instance().Exists(init_file)) {
2128 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2129 return;
2130 }
2131
2132 LoadCWDlldbinitFile should_load = ShouldLoadCwdInitFile();
2133
2134 switch (should_load) {
2135 case eLoadCWDlldbinitFalse:
2136 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2137 break;
2138 case eLoadCWDlldbinitTrue:
2139 SourceInitFile(FileSpec(init_file.str()), result);
2140 break;
2141 case eLoadCWDlldbinitWarn: {
2142 llvm::SmallString<128> home_init_file;
2143 GetHomeInitFile(home_init_file);
2144 if (llvm::sys::path::parent_path(init_file) ==
2145 llvm::sys::path::parent_path(home_init_file)) {
2146 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2147 } else {
2148 result.AppendErrorWithFormat(InitFileWarning);
2149 result.SetStatus(eReturnStatusFailed);
2150 }
2151 }
2152 }
2153}
2154
2155/// We will first see if there is an application specific ".lldbinit" file
2156/// whose name is "~/.lldbinit" followed by a "-" and the name of the program.
2157/// If this file doesn't exist, we fall back to just the "~/.lldbinit" file.
2158void CommandInterpreter::SourceInitFileHome(CommandReturnObject &result) {
2159 if (m_skip_lldbinit_files) {
2160 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2161 return;
2162 }
2163
2164 llvm::SmallString<128> init_file;
2165 GetHomeInitFile(init_file);
2166
2167 if (!m_skip_app_init_files) {
2168 llvm::StringRef program_name =
2169 HostInfo::GetProgramFileSpec().GetFilename().GetStringRef();
2170 llvm::SmallString<128> program_init_file;
2171 GetHomeInitFile(program_init_file, program_name);
2172 if (FileSystem::Instance().Exists(program_init_file))
2173 init_file = program_init_file;
2174 }
2175
2176 SourceInitFile(FileSpec(init_file.str()), result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002177}
2178
2179const char *CommandInterpreter::GetCommandPrefix() {
2180 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
Konrad Kleine248a1302019-05-23 11:14:47 +00002181 return prefix == nullptr ? "" : prefix;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002182}
2183
2184PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2185 PlatformSP platform_sp;
2186 if (prefer_target_platform) {
2187 ExecutionContext exe_ctx(GetExecutionContext());
2188 Target *target = exe_ctx.GetTargetPtr();
2189 if (target)
2190 platform_sp = target->GetPlatform();
2191 }
2192
2193 if (!platform_sp)
2194 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2195 return platform_sp;
2196}
2197
2198void CommandInterpreter::HandleCommands(const StringList &commands,
2199 ExecutionContext *override_context,
2200 CommandInterpreterRunOptions &options,
2201 CommandReturnObject &result) {
2202 size_t num_lines = commands.GetSize();
2203
2204 // If we are going to continue past a "continue" then we need to run the
Adrian Prantl05097242018-04-30 16:49:04 +00002205 // commands synchronously. Make sure you reset this value anywhere you return
2206 // from the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002207
2208 bool old_async_execution = m_debugger.GetAsyncExecution();
2209
2210 // If we've been given an execution context, set it at the start, but don't
Adrian Prantl05097242018-04-30 16:49:04 +00002211 // keep resetting it or we will cause series of commands that change the
2212 // context, then do an operation that relies on that context to fail.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002213
2214 if (override_context != nullptr)
2215 UpdateExecutionContext(override_context);
2216
2217 if (!options.GetStopOnContinue()) {
2218 m_debugger.SetAsyncExecution(false);
2219 }
2220
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002221 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002222 const char *cmd = commands.GetStringAtIndex(idx);
2223 if (cmd[0] == '\0')
2224 continue;
2225
2226 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002227 // TODO: Add Stream support.
2228 result.AppendMessageWithFormat("%s %s\n",
2229 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002230 }
2231
2232 CommandReturnObject tmp_result;
2233 // If override_context is not NULL, pass no_context_switching = true for
2234 // HandleCommand() since we updated our context already.
2235
2236 // We might call into a regex or alias command, in which case the
Adrian Prantl05097242018-04-30 16:49:04 +00002237 // add_to_history will get lost. This m_command_source_depth dingus is the
2238 // way we turn off adding to the history in that case, so set it up here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002239 if (!options.GetAddToHistory())
2240 m_command_source_depth++;
2241 bool success =
2242 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2243 nullptr, /* override_context */
2244 true, /* repeat_on_empty_command */
2245 override_context != nullptr /* no_context_switching */);
2246 if (!options.GetAddToHistory())
2247 m_command_source_depth--;
2248
2249 if (options.GetPrintResults()) {
2250 if (tmp_result.Succeeded())
Zachary Turner03c9f362016-11-14 23:23:31 +00002251 result.AppendMessage(tmp_result.GetOutputData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002252 }
2253
2254 if (!success || !tmp_result.Succeeded()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002255 llvm::StringRef error_msg = tmp_result.GetErrorData();
2256 if (error_msg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002257 error_msg = "<unknown error>.\n";
2258 if (options.GetStopOnError()) {
2259 result.AppendErrorWithFormat(
2260 "Aborting reading of commands after command #%" PRIu64
2261 ": '%s' failed with %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00002262 (uint64_t)idx, cmd, error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002263 result.SetStatus(eReturnStatusFailed);
2264 m_debugger.SetAsyncExecution(old_async_execution);
2265 return;
2266 } else if (options.GetPrintResults()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002267 result.AppendMessageWithFormat(
2268 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2269 error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002270 }
2271 }
2272
2273 if (result.GetImmediateOutputStream())
2274 result.GetImmediateOutputStream()->Flush();
2275
2276 if (result.GetImmediateErrorStream())
2277 result.GetImmediateErrorStream()->Flush();
2278
Adrian Prantl05097242018-04-30 16:49:04 +00002279 // N.B. Can't depend on DidChangeProcessState, because the state coming
2280 // into the command execution could be running (for instance in Breakpoint
2281 // Commands. So we check the return value to see if it is has running in
2282 // it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002283 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2284 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2285 if (options.GetStopOnContinue()) {
2286 // If we caused the target to proceed, and we're going to stop in that
Adrian Prantl05097242018-04-30 16:49:04 +00002287 // case, set the status in our real result before returning. This is
2288 // an error if the continue was not the last command in the set of
2289 // commands to be run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002290 if (idx != num_lines - 1)
2291 result.AppendErrorWithFormat(
2292 "Aborting reading of commands after command #%" PRIu64
2293 ": '%s' continued the target.\n",
2294 (uint64_t)idx + 1, cmd);
2295 else
2296 result.AppendMessageWithFormat("Command #%" PRIu64
2297 " '%s' continued the target.\n",
2298 (uint64_t)idx + 1, cmd);
2299
2300 result.SetStatus(tmp_result.GetStatus());
2301 m_debugger.SetAsyncExecution(old_async_execution);
2302
2303 return;
2304 }
2305 }
2306
2307 // Also check for "stop on crash here:
2308 bool should_stop = false;
2309 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2310 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2311 if (target_sp) {
2312 ProcessSP process_sp(target_sp->GetProcessSP());
2313 if (process_sp) {
2314 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2315 StopReason reason = thread_sp->GetStopReason();
2316 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2317 reason == eStopReasonInstrumentation) {
2318 should_stop = true;
2319 break;
2320 }
2321 }
2322 }
2323 }
2324 if (should_stop) {
2325 if (idx != num_lines - 1)
2326 result.AppendErrorWithFormat(
2327 "Aborting reading of commands after command #%" PRIu64
2328 ": '%s' stopped with a signal or exception.\n",
2329 (uint64_t)idx + 1, cmd);
2330 else
2331 result.AppendMessageWithFormat(
2332 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2333 (uint64_t)idx + 1, cmd);
2334
2335 result.SetStatus(tmp_result.GetStatus());
2336 m_debugger.SetAsyncExecution(old_async_execution);
2337
2338 return;
2339 }
2340 }
2341 }
2342
2343 result.SetStatus(eReturnStatusSuccessFinishResult);
2344 m_debugger.SetAsyncExecution(old_async_execution);
2345
2346 return;
2347}
2348
2349// Make flags that we can pass into the IOHandler so our delegates can do the
2350// right thing
2351enum {
2352 eHandleCommandFlagStopOnContinue = (1u << 0),
2353 eHandleCommandFlagStopOnError = (1u << 1),
2354 eHandleCommandFlagEchoCommand = (1u << 2),
Stefan Granitzc678ed72018-10-05 16:49:47 +00002355 eHandleCommandFlagEchoCommentCommand = (1u << 3),
2356 eHandleCommandFlagPrintResult = (1u << 4),
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002357 eHandleCommandFlagPrintErrors = (1u << 5),
2358 eHandleCommandFlagStopOnCrash = (1u << 6)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002359};
2360
2361void CommandInterpreter::HandleCommandsFromFile(
2362 FileSpec &cmd_file, ExecutionContext *context,
2363 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002364 if (!FileSystem::Instance().Exists(cmd_file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002365 result.AppendErrorWithFormat(
2366 "Error reading commands from file %s - file not found.\n",
2367 cmd_file.GetFilename().AsCString("<Unknown>"));
2368 result.SetStatus(eReturnStatusFailed);
2369 return;
2370 }
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002371
2372 StreamFileSP input_file_sp(new StreamFile());
2373 std::string cmd_file_path = cmd_file.GetPath();
2374 Status error = FileSystem::Instance().Open(input_file_sp->GetFile(), cmd_file,
2375 File::eOpenOptionRead);
2376
2377 if (error.Fail()) {
2378 result.AppendErrorWithFormat(
2379 "error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(),
2380 error.AsCString());
2381 result.SetStatus(eReturnStatusFailed);
2382 return;
2383 }
2384
2385 Debugger &debugger = GetDebugger();
2386
2387 uint32_t flags = 0;
2388
2389 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2390 if (m_command_source_flags.empty()) {
2391 // Stop on continue by default
2392 flags |= eHandleCommandFlagStopOnContinue;
2393 } else if (m_command_source_flags.back() &
2394 eHandleCommandFlagStopOnContinue) {
2395 flags |= eHandleCommandFlagStopOnContinue;
2396 }
2397 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2398 flags |= eHandleCommandFlagStopOnContinue;
2399 }
2400
2401 if (options.m_stop_on_error == eLazyBoolCalculate) {
2402 if (m_command_source_flags.empty()) {
2403 if (GetStopCmdSourceOnError())
2404 flags |= eHandleCommandFlagStopOnError;
2405 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) {
2406 flags |= eHandleCommandFlagStopOnError;
2407 }
2408 } else if (options.m_stop_on_error == eLazyBoolYes) {
2409 flags |= eHandleCommandFlagStopOnError;
2410 }
2411
2412 // stop-on-crash can only be set, if it is present in all levels of
2413 // pushed flag sets.
2414 if (options.GetStopOnCrash()) {
2415 if (m_command_source_flags.empty()) {
2416 flags |= eHandleCommandFlagStopOnCrash;
2417 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) {
2418 flags |= eHandleCommandFlagStopOnCrash;
2419 }
2420 }
2421
2422 if (options.m_echo_commands == eLazyBoolCalculate) {
2423 if (m_command_source_flags.empty()) {
2424 // Echo command by default
2425 flags |= eHandleCommandFlagEchoCommand;
2426 } else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) {
2427 flags |= eHandleCommandFlagEchoCommand;
2428 }
2429 } else if (options.m_echo_commands == eLazyBoolYes) {
2430 flags |= eHandleCommandFlagEchoCommand;
2431 }
2432
2433 // We will only ever ask for this flag, if we echo commands in general.
2434 if (options.m_echo_comment_commands == eLazyBoolCalculate) {
2435 if (m_command_source_flags.empty()) {
2436 // Echo comments by default
2437 flags |= eHandleCommandFlagEchoCommentCommand;
2438 } else if (m_command_source_flags.back() &
2439 eHandleCommandFlagEchoCommentCommand) {
2440 flags |= eHandleCommandFlagEchoCommentCommand;
2441 }
2442 } else if (options.m_echo_comment_commands == eLazyBoolYes) {
2443 flags |= eHandleCommandFlagEchoCommentCommand;
2444 }
2445
2446 if (options.m_print_results == eLazyBoolCalculate) {
2447 if (m_command_source_flags.empty()) {
2448 // Print output by default
2449 flags |= eHandleCommandFlagPrintResult;
2450 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) {
2451 flags |= eHandleCommandFlagPrintResult;
2452 }
2453 } else if (options.m_print_results == eLazyBoolYes) {
2454 flags |= eHandleCommandFlagPrintResult;
2455 }
2456
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002457 if (options.m_print_errors == eLazyBoolCalculate) {
2458 if (m_command_source_flags.empty()) {
2459 // Print output by default
2460 flags |= eHandleCommandFlagPrintErrors;
2461 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintErrors) {
2462 flags |= eHandleCommandFlagPrintErrors;
2463 }
2464 } else if (options.m_print_errors == eLazyBoolYes) {
2465 flags |= eHandleCommandFlagPrintErrors;
2466 }
2467
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002468 if (flags & eHandleCommandFlagPrintResult) {
2469 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2470 cmd_file_path.c_str());
2471 }
2472
2473 // Used for inheriting the right settings when "command source" might
2474 // have nested "command source" commands
2475 lldb::StreamFileSP empty_stream_sp;
2476 m_command_source_flags.push_back(flags);
2477 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2478 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2479 empty_stream_sp, // Pass in an empty stream so we inherit the top
2480 // input reader output stream
2481 empty_stream_sp, // Pass in an empty stream so we inherit the top
2482 // input reader error stream
2483 flags,
2484 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2485 // or written
2486 debugger.GetPrompt(), llvm::StringRef(),
2487 false, // Not multi-line
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002488 debugger.GetUseColor(), 0, *this, nullptr));
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002489 const bool old_async_execution = debugger.GetAsyncExecution();
2490
2491 // Set synchronous execution if we are not stopping on continue
2492 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2493 debugger.SetAsyncExecution(false);
2494
2495 m_command_source_depth++;
2496
2497 debugger.RunIOHandler(io_handler_sp);
2498 if (!m_command_source_flags.empty())
2499 m_command_source_flags.pop_back();
2500 m_command_source_depth--;
2501 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2502 debugger.SetAsyncExecution(old_async_execution);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002503}
2504
Kate Stoneb9c1b512016-09-06 20:57:50 +00002505bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2506
2507void CommandInterpreter::SetSynchronous(bool value) {
Jonas Devlieghere70df51b2019-07-31 23:34:45 +00002508 // Asynchronous mode is not supported during reproducer replay.
2509 if (repro::Reproducer::Instance().GetLoader())
2510 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002511 m_synchronous_execution = value;
2512}
2513
2514void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002515 llvm::StringRef prefix,
2516 llvm::StringRef help_text) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002517 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002518
Zachary Turner0ac5f982016-11-08 04:12:42 +00002519 size_t line_width_max = max_columns - prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002520 if (line_width_max < 16)
Zachary Turner0ac5f982016-11-08 04:12:42 +00002521 line_width_max = help_text.size() + prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002522
Zachary Turner0ac5f982016-11-08 04:12:42 +00002523 strm.IndentMore(prefix.size());
2524 bool prefixed_yet = false;
2525 while (!help_text.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002526 // Prefix the first line, indent subsequent lines to line up
Zachary Turner0ac5f982016-11-08 04:12:42 +00002527 if (!prefixed_yet) {
2528 strm << prefix;
2529 prefixed_yet = true;
2530 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002531 strm.Indent();
Zachary Turner0ac5f982016-11-08 04:12:42 +00002532
2533 // Never print more than the maximum on one line.
2534 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2535
2536 // Always break on an explicit newline.
2537 std::size_t first_newline = this_line.find_first_of("\n");
2538
2539 // Don't break on space/tab unless the text is too long to fit on one line.
2540 std::size_t last_space = llvm::StringRef::npos;
2541 if (this_line.size() != help_text.size())
2542 last_space = this_line.find_last_of(" \t");
2543
2544 // Break at whichever condition triggered first.
2545 this_line = this_line.substr(0, std::min(first_newline, last_space));
2546 strm.PutCString(this_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002547 strm.EOL();
2548
Zachary Turner0ac5f982016-11-08 04:12:42 +00002549 // Remove whitespace / newlines after breaking.
2550 help_text = help_text.drop_front(this_line.size()).ltrim();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002551 }
Zachary Turner0ac5f982016-11-08 04:12:42 +00002552 strm.IndentLess(prefix.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002553}
2554
2555void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002556 llvm::StringRef word_text,
2557 llvm::StringRef separator,
2558 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002559 size_t max_word_len) {
2560 StreamString prefix_stream;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002561 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2562 (int)separator.size(), separator.data());
Zachary Turnerc1564272016-11-16 21:15:24 +00002563 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2564}
2565
Zachary Turner0ac5f982016-11-08 04:12:42 +00002566void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2567 llvm::StringRef separator,
2568 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002569 uint32_t max_word_len) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00002570 int indent_size = max_word_len + separator.size() + 2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002571
2572 strm.IndentMore(indent_size);
2573
2574 StreamString text_strm;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002575 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2576 text_strm << separator << " " << help_text;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002577
2578 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2579
Zachary Turnerc1564272016-11-16 21:15:24 +00002580 llvm::StringRef text = text_strm.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002581
2582 uint32_t chars_left = max_columns;
2583
Davide Italianocf8a8292017-04-14 22:36:08 +00002584 auto nextWordLength = [](llvm::StringRef S) {
Jonas Devliegherec712bac2019-03-28 18:10:14 +00002585 size_t pos = S.find(' ');
Davide Italianocf8a8292017-04-14 22:36:08 +00002586 return pos == llvm::StringRef::npos ? S.size() : pos;
2587 };
2588
Zachary Turnerc1564272016-11-16 21:15:24 +00002589 while (!text.empty()) {
2590 if (text.front() == '\n' ||
Jim Inghama81bd7f2017-07-27 00:18:18 +00002591 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002592 strm.EOL();
2593 strm.Indent();
Zachary Turnerc1564272016-11-16 21:15:24 +00002594 chars_left = max_columns - indent_size;
2595 if (text.front() == '\n')
2596 text = text.drop_front();
2597 else
2598 text = text.ltrim(' ');
Kate Stoneb9c1b512016-09-06 20:57:50 +00002599 } else {
Zachary Turnerc1564272016-11-16 21:15:24 +00002600 strm.PutChar(text.front());
2601 --chars_left;
2602 text = text.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002603 }
2604 }
2605
2606 strm.EOL();
2607 strm.IndentLess(indent_size);
2608}
2609
2610void CommandInterpreter::FindCommandsForApropos(
Zachary Turner067d1db2016-11-16 21:45:04 +00002611 llvm::StringRef search_word, StringList &commands_found,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002612 StringList &commands_help, CommandObject::CommandMap &command_map) {
2613 CommandObject::CommandMap::const_iterator pos;
2614
2615 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
Zachary Turner067d1db2016-11-16 21:45:04 +00002616 llvm::StringRef command_name = pos->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002617 CommandObject *cmd_obj = pos->second.get();
2618
2619 const bool search_short_help = true;
2620 const bool search_long_help = false;
2621 const bool search_syntax = false;
2622 const bool search_options = false;
Zachary Turner067d1db2016-11-16 21:45:04 +00002623 if (command_name.contains_lower(search_word) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002624 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2625 search_long_help, search_syntax,
2626 search_options)) {
2627 commands_found.AppendString(cmd_obj->GetCommandName());
2628 commands_help.AppendString(cmd_obj->GetHelp());
2629 }
2630
2631 if (cmd_obj->IsMultiwordObject()) {
2632 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2633 FindCommandsForApropos(search_word, commands_found, commands_help,
2634 cmd_multiword->GetSubcommandDictionary());
2635 }
2636 }
2637}
2638
Zachary Turner067d1db2016-11-16 21:45:04 +00002639void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002640 StringList &commands_found,
2641 StringList &commands_help,
2642 bool search_builtin_commands,
2643 bool search_user_commands,
2644 bool search_alias_commands) {
2645 CommandObject::CommandMap::const_iterator pos;
2646
2647 if (search_builtin_commands)
2648 FindCommandsForApropos(search_word, commands_found, commands_help,
2649 m_command_dict);
2650
2651 if (search_user_commands)
2652 FindCommandsForApropos(search_word, commands_found, commands_help,
2653 m_user_dict);
2654
2655 if (search_alias_commands)
2656 FindCommandsForApropos(search_word, commands_found, commands_help,
2657 m_alias_dict);
2658}
2659
2660void CommandInterpreter::UpdateExecutionContext(
2661 ExecutionContext *override_context) {
2662 if (override_context != nullptr) {
2663 m_exe_ctx_ref = *override_context;
2664 } else {
2665 const bool adopt_selected = true;
2666 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2667 adopt_selected);
2668 }
2669}
2670
Pavel Labatha9d58432019-07-31 12:06:50 +00002671void CommandInterpreter::GetProcessOutput() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002672 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
Pavel Labatha9d58432019-07-31 12:06:50 +00002673 if (!target_sp)
2674 return;
2675
2676 if (ProcessSP process_sp = target_sp->GetProcessSP())
2677 m_debugger.FlushProcessOutput(*process_sp, /*flush_stdout*/ true,
2678 /*flush_stderr*/ true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002679}
2680
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002681void CommandInterpreter::StartHandlingCommand() {
2682 auto idle_state = CommandHandlingState::eIdle;
2683 if (m_command_state.compare_exchange_strong(
2684 idle_state, CommandHandlingState::eInProgress))
2685 lldbassert(m_iohandler_nesting_level == 0);
2686 else
2687 lldbassert(m_iohandler_nesting_level > 0);
2688 ++m_iohandler_nesting_level;
2689}
2690
2691void CommandInterpreter::FinishHandlingCommand() {
2692 lldbassert(m_iohandler_nesting_level > 0);
2693 if (--m_iohandler_nesting_level == 0) {
2694 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2695 lldbassert(prev_state != CommandHandlingState::eIdle);
2696 }
2697}
2698
2699bool CommandInterpreter::InterruptCommand() {
2700 auto in_progress = CommandHandlingState::eInProgress;
2701 return m_command_state.compare_exchange_strong(
2702 in_progress, CommandHandlingState::eInterrupted);
2703}
2704
2705bool CommandInterpreter::WasInterrupted() const {
2706 bool was_interrupted =
2707 (m_command_state == CommandHandlingState::eInterrupted);
2708 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2709 return was_interrupted;
2710}
2711
2712void CommandInterpreter::PrintCommandOutput(Stream &stream,
2713 llvm::StringRef str) {
2714 // Split the output into lines and poll for interrupt requests
2715 const char *data = str.data();
2716 size_t size = str.size();
2717 while (size > 0 && !WasInterrupted()) {
2718 size_t chunk_size = 0;
2719 for (; chunk_size < size; ++chunk_size) {
2720 lldbassert(data[chunk_size] != '\0');
2721 if (data[chunk_size] == '\n') {
2722 ++chunk_size;
2723 break;
2724 }
2725 }
2726 chunk_size = stream.Write(data, chunk_size);
2727 lldbassert(size >= chunk_size);
2728 data += chunk_size;
2729 size -= chunk_size;
2730 }
2731 if (size > 0) {
2732 stream.Printf("\n... Interrupted.\n");
2733 }
2734}
2735
Stefan Granitzc678ed72018-10-05 16:49:47 +00002736bool CommandInterpreter::EchoCommandNonInteractive(
2737 llvm::StringRef line, const Flags &io_handler_flags) const {
2738 if (!io_handler_flags.Test(eHandleCommandFlagEchoCommand))
2739 return false;
2740
2741 llvm::StringRef command = line.trim();
2742 if (command.empty())
2743 return true;
2744
2745 if (command.front() == m_comment_char)
2746 return io_handler_flags.Test(eHandleCommandFlagEchoCommentCommand);
2747
2748 return true;
2749}
2750
Kate Stoneb9c1b512016-09-06 20:57:50 +00002751void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2752 std::string &line) {
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002753 // If we were interrupted, bail out...
2754 if (WasInterrupted())
2755 return;
2756
Kate Stoneb9c1b512016-09-06 20:57:50 +00002757 const bool is_interactive = io_handler.GetIsInteractive();
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002758 if (!is_interactive) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002759 // When we are not interactive, don't execute blank lines. This will happen
2760 // sourcing a commands file. We don't want blank lines to repeat the
Adrian Prantl05097242018-04-30 16:49:04 +00002761 // previous command and cause any errors to occur (like redefining an
2762 // alias, get an error and stop parsing the commands file).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002763 if (line.empty())
2764 return;
2765
2766 // When using a non-interactive file handle (like when sourcing commands
Adrian Prantl05097242018-04-30 16:49:04 +00002767 // from a file) we need to echo the command out so we don't just see the
2768 // command output and no command...
Stefan Granitzc678ed72018-10-05 16:49:47 +00002769 if (EchoCommandNonInteractive(line, io_handler.GetFlags()))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002770 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2771 line.c_str());
2772 }
2773
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002774 StartHandlingCommand();
2775
Kate Stoneb9c1b512016-09-06 20:57:50 +00002776 lldb_private::CommandReturnObject result;
2777 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2778
2779 // Now emit the command output text from the command we just executed
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002780 if ((result.Succeeded() &&
2781 io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) ||
2782 io_handler.GetFlags().Test(eHandleCommandFlagPrintErrors)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002783 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2784 GetProcessOutput();
2785
2786 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002787 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002788 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002789 }
2790
2791 // Now emit the command error text from the command we just executed
2792 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002793 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002794 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002795 }
2796 }
2797
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002798 FinishHandlingCommand();
2799
Kate Stoneb9c1b512016-09-06 20:57:50 +00002800 switch (result.GetStatus()) {
2801 case eReturnStatusInvalid:
2802 case eReturnStatusSuccessFinishNoResult:
2803 case eReturnStatusSuccessFinishResult:
2804 case eReturnStatusStarted:
2805 break;
2806
2807 case eReturnStatusSuccessContinuingNoResult:
2808 case eReturnStatusSuccessContinuingResult:
2809 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2810 io_handler.SetIsDone(true);
2811 break;
2812
2813 case eReturnStatusFailed:
2814 m_num_errors++;
2815 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2816 io_handler.SetIsDone(true);
2817 break;
2818
2819 case eReturnStatusQuit:
2820 m_quit_requested = true;
2821 io_handler.SetIsDone(true);
2822 break;
2823 }
2824
2825 // Finally, if we're going to stop on crash, check that here:
2826 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2827 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2828 bool should_stop = false;
2829 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2830 if (target_sp) {
2831 ProcessSP process_sp(target_sp->GetProcessSP());
2832 if (process_sp) {
2833 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2834 StopReason reason = thread_sp->GetStopReason();
2835 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2836 reason == eStopReasonInstrumentation) &&
2837 !result.GetAbnormalStopWasExpected()) {
2838 should_stop = true;
2839 break;
2840 }
2841 }
2842 }
2843 }
2844 if (should_stop) {
2845 io_handler.SetIsDone(true);
2846 m_stopped_for_crash = true;
2847 }
2848 }
2849}
2850
2851bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2852 ExecutionContext exe_ctx(GetExecutionContext());
2853 Process *process = exe_ctx.GetProcessPtr();
2854
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002855 if (InterruptCommand())
2856 return true;
2857
Kate Stoneb9c1b512016-09-06 20:57:50 +00002858 if (process) {
2859 StateType state = process->GetState();
2860 if (StateIsRunningState(state)) {
2861 process->Halt();
2862 return true; // Don't do any updating when we are running
2863 }
2864 }
2865
Jonas Devlieghere2b29b432019-04-26 22:43:16 +00002866 ScriptInterpreter *script_interpreter =
2867 m_debugger.GetScriptInterpreter(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002868 if (script_interpreter) {
2869 if (script_interpreter->Interrupt())
2870 return true;
2871 }
2872 return false;
2873}
2874
2875void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2876 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2877 void *baton) {
2878 Debugger &debugger = GetDebugger();
2879 IOHandlerSP io_handler_sp(
2880 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2881 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002882 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2883 llvm::StringRef(), // Continuation prompt
2884 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002885 debugger.GetUseColor(),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002886 0, // Don't show line numbers
2887 delegate, // IOHandlerDelegate
2888 nullptr)); // FileShadowCollector
Kate Stoneb9c1b512016-09-06 20:57:50 +00002889
2890 if (io_handler_sp) {
2891 io_handler_sp->SetUserData(baton);
2892 if (asynchronously)
2893 debugger.PushIOHandler(io_handler_sp);
2894 else
2895 debugger.RunIOHandler(io_handler_sp);
2896 }
2897}
2898
2899void CommandInterpreter::GetPythonCommandsFromIOHandler(
2900 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2901 void *baton) {
2902 Debugger &debugger = GetDebugger();
2903 IOHandlerSP io_handler_sp(
2904 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2905 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002906 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2907 llvm::StringRef(), // Continuation prompt
2908 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002909 debugger.GetUseColor(),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002910 0, // Don't show line numbers
2911 delegate, // IOHandlerDelegate
2912 nullptr)); // FileShadowCollector
Kate Stoneb9c1b512016-09-06 20:57:50 +00002913
2914 if (io_handler_sp) {
2915 io_handler_sp->SetUserData(baton);
2916 if (asynchronously)
2917 debugger.PushIOHandler(io_handler_sp);
2918 else
2919 debugger.RunIOHandler(io_handler_sp);
2920 }
2921}
2922
2923bool CommandInterpreter::IsActive() {
2924 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2925}
2926
2927lldb::IOHandlerSP
2928CommandInterpreter::GetIOHandler(bool force_create,
2929 CommandInterpreterRunOptions *options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002930 // Always re-create the IOHandlerEditline in case the input changed. The old
2931 // instance might have had a non-interactive input and now it does or vice
2932 // versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002933 if (force_create || !m_command_io_handler_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002934 // Always re-create the IOHandlerEditline in case the input changed. The
2935 // old instance might have had a non-interactive input and now it does or
2936 // vice versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002937 uint32_t flags = 0;
2938
2939 if (options) {
2940 if (options->m_stop_on_continue == eLazyBoolYes)
2941 flags |= eHandleCommandFlagStopOnContinue;
2942 if (options->m_stop_on_error == eLazyBoolYes)
2943 flags |= eHandleCommandFlagStopOnError;
2944 if (options->m_stop_on_crash == eLazyBoolYes)
2945 flags |= eHandleCommandFlagStopOnCrash;
2946 if (options->m_echo_commands != eLazyBoolNo)
2947 flags |= eHandleCommandFlagEchoCommand;
Stefan Granitzc678ed72018-10-05 16:49:47 +00002948 if (options->m_echo_comment_commands != eLazyBoolNo)
2949 flags |= eHandleCommandFlagEchoCommentCommand;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002950 if (options->m_print_results != eLazyBoolNo)
2951 flags |= eHandleCommandFlagPrintResult;
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002952 if (options->m_print_errors != eLazyBoolNo)
2953 flags |= eHandleCommandFlagPrintErrors;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002954 } else {
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002955 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult |
2956 eHandleCommandFlagPrintErrors;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002957 }
2958
Jonas Devlieghere796ac802019-02-11 23:13:08 +00002959 m_command_io_handler_sp = std::make_shared<IOHandlerEditline>(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002960 m_debugger, IOHandler::Type::CommandInterpreter,
2961 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2962 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002963 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002964 false, // Don't enable multiple line input, just single line commands
2965 m_debugger.GetUseColor(),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002966 0, // Don't show line numbers
2967 *this, // IOHandlerDelegate
2968 GetDebugger().GetInputRecorder());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002969 }
2970 return m_command_io_handler_sp;
2971}
2972
2973void CommandInterpreter::RunCommandInterpreter(
2974 bool auto_handle_events, bool spawn_thread,
2975 CommandInterpreterRunOptions &options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002976 // Always re-create the command interpreter when we run it in case any file
2977 // handles have changed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002978 bool force_create = true;
2979 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2980 m_stopped_for_crash = false;
2981
2982 if (auto_handle_events)
2983 m_debugger.StartEventHandlerThread();
2984
2985 if (spawn_thread) {
2986 m_debugger.StartIOHandlerThread();
2987 } else {
2988 m_debugger.ExecuteIOHandlers();
2989
2990 if (auto_handle_events)
2991 m_debugger.StopEventHandlerThread();
2992 }
2993}
2994
2995CommandObject *
2996CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2997 CommandReturnObject &result) {
2998 std::string scratch_command(command_line); // working copy so we don't modify
2999 // command_line unless we succeed
3000 CommandObject *cmd_obj = nullptr;
3001 StreamString revised_command_line;
3002 bool wants_raw_input = false;
3003 size_t actual_cmd_name_len = 0;
3004 std::string next_word;
3005 StringList matches;
3006 bool done = false;
3007 while (!done) {
3008 char quote_char = '\0';
3009 std::string suffix;
3010 ExtractCommand(scratch_command, next_word, suffix, quote_char);
3011 if (cmd_obj == nullptr) {
3012 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003013 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00003014 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003015 bool is_real_command =
Jonas Devliegherea6682a42018-12-15 00:15:33 +00003016 (!is_alias) || (cmd_obj != nullptr && !cmd_obj->IsAlias());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003017 if (!is_real_command) {
3018 matches.Clear();
3019 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003020 cmd_obj =
3021 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003022 revised_command_line.Printf("%s", alias_result.c_str());
3023 if (cmd_obj) {
3024 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00003025 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003026 }
3027 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003028 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00003029 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
3030 actual_cmd_name_len += cmd_name.size();
3031 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003032 wants_raw_input = cmd_obj->WantsRawCommandString();
3033 } else {
3034 revised_command_line.Printf("%s", next_word.c_str());
3035 }
3036 }
3037 } else {
3038 if (cmd_obj->IsMultiwordObject()) {
3039 CommandObject *sub_cmd_obj =
3040 cmd_obj->GetSubcommandObject(next_word.c_str());
3041 if (sub_cmd_obj) {
Adrian Prantl05097242018-04-30 16:49:04 +00003042 // The subcommand's name includes the parent command's name, so
3043 // restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00003044 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3045 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003046 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00003047 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003048 cmd_obj = sub_cmd_obj;
3049 wants_raw_input = cmd_obj->WantsRawCommandString();
3050 } else {
3051 if (quote_char)
3052 revised_command_line.Printf(" %c%s%s%c", quote_char,
3053 next_word.c_str(), suffix.c_str(),
3054 quote_char);
3055 else
3056 revised_command_line.Printf(" %s%s", next_word.c_str(),
3057 suffix.c_str());
3058 done = true;
3059 }
3060 } else {
3061 if (quote_char)
3062 revised_command_line.Printf(" %c%s%s%c", quote_char,
3063 next_word.c_str(), suffix.c_str(),
3064 quote_char);
3065 else
3066 revised_command_line.Printf(" %s%s", next_word.c_str(),
3067 suffix.c_str());
3068 done = true;
3069 }
3070 }
3071
3072 if (cmd_obj == nullptr) {
3073 const size_t num_matches = matches.GetSize();
3074 if (matches.GetSize() > 1) {
3075 StreamString error_msg;
3076 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3077 next_word.c_str());
3078
3079 for (uint32_t i = 0; i < num_matches; ++i) {
3080 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3081 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003082 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003083 } else {
3084 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003085 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003086 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3087 next_word.c_str());
3088 }
3089 result.SetStatus(eReturnStatusFailed);
3090 return nullptr;
3091 }
3092
3093 if (cmd_obj->IsMultiwordObject()) {
3094 if (!suffix.empty()) {
3095 result.AppendErrorWithFormat(
3096 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3097 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003098 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003099 next_word.empty() ? "" : next_word.c_str(),
3100 next_word.empty() ? " -- " : " ", suffix.c_str());
3101 result.SetStatus(eReturnStatusFailed);
3102 return nullptr;
3103 }
3104 } else {
3105 // If we found a normal command, we are done
3106 done = true;
3107 if (!suffix.empty()) {
3108 switch (suffix[0]) {
3109 case '/':
3110 // GDB format suffixes
3111 {
3112 Options *command_options = cmd_obj->GetOptions();
3113 if (command_options &&
3114 command_options->SupportsLongOption("gdb-format")) {
3115 std::string gdb_format_option("--gdb-format=");
3116 gdb_format_option += (suffix.c_str() + 1);
3117
Zachary Turnerc1564272016-11-16 21:15:24 +00003118 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003119 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3120 if (arg_terminator_idx != std::string::npos) {
3121 // Insert the gdb format option before the "--" that terminates
3122 // options
3123 gdb_format_option.append(1, ' ');
3124 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003125 revised_command_line.Clear();
3126 revised_command_line.PutCString(cmd);
3127 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003128 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3129
3130 if (wants_raw_input &&
3131 FindArgumentTerminator(cmd) == std::string::npos)
3132 revised_command_line.PutCString(" --");
3133 } else {
3134 result.AppendErrorWithFormat(
3135 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003136 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003137 result.SetStatus(eReturnStatusFailed);
3138 return nullptr;
3139 }
3140 }
3141 break;
3142
3143 default:
3144 result.AppendErrorWithFormat(
3145 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3146 result.SetStatus(eReturnStatusFailed);
3147 return nullptr;
3148 }
3149 }
3150 }
3151 if (scratch_command.empty())
3152 done = true;
3153 }
3154
3155 if (!scratch_command.empty())
3156 revised_command_line.Printf(" %s", scratch_command.c_str());
3157
Konrad Kleine248a1302019-05-23 11:14:47 +00003158 if (cmd_obj != nullptr)
Zachary Turnerc1564272016-11-16 21:15:24 +00003159 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003160
3161 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003162}