blob: 71f766ed7b5b8e6ac33d6059c1a7c03e822a4036 [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"
James Y Knight2ad48212018-05-22 22:53:50 +000019#include "Commands/CommandObjectCommands.h"
20#include "Commands/CommandObjectDisassemble.h"
21#include "Commands/CommandObjectExpression.h"
22#include "Commands/CommandObjectFrame.h"
23#include "Commands/CommandObjectGUI.h"
24#include "Commands/CommandObjectHelp.h"
25#include "Commands/CommandObjectLanguage.h"
26#include "Commands/CommandObjectLog.h"
27#include "Commands/CommandObjectMemory.h"
28#include "Commands/CommandObjectPlatform.h"
29#include "Commands/CommandObjectPlugin.h"
30#include "Commands/CommandObjectProcess.h"
31#include "Commands/CommandObjectQuit.h"
32#include "Commands/CommandObjectRegister.h"
Jonas Devlieghere9e046f02018-11-13 19:18:16 +000033#include "Commands/CommandObjectReproducer.h"
James Y Knight2ad48212018-05-22 22:53:50 +000034#include "Commands/CommandObjectSettings.h"
35#include "Commands/CommandObjectSource.h"
36#include "Commands/CommandObjectStats.h"
37#include "Commands/CommandObjectTarget.h"
38#include "Commands/CommandObjectThread.h"
39#include "Commands/CommandObjectType.h"
40#include "Commands/CommandObjectVersion.h"
41#include "Commands/CommandObjectWatchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043#include "lldb/Core/Debugger.h"
Zachary Turner2c1f46d2015-07-30 20:28:07 +000044#include "lldb/Core/PluginManager.h"
Greg Clayton44d93782014-01-27 23:43:24 +000045#include "lldb/Core/StreamFile.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000046#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000047#include "lldb/Utility/State.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000048#include "lldb/Utility/Stream.h"
Pavel Labath38d06322017-06-29 14:32:17 +000049#include "lldb/Utility/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000050
Todd Fialacacde7d2014-09-27 16:54:22 +000051#ifndef LLDB_DISABLE_LIBEDIT
Greg Clayton44d93782014-01-27 23:43:24 +000052#include "lldb/Host/Editline.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000053#endif
Greg Clayton7fb56d02011-02-01 01:31:41 +000054#include "lldb/Host/Host.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000055#include "lldb/Host/HostInfo.h"
Enrico Granatab5887262012-10-29 21:18:03 +000056
Greg Clayton7d2ef162013-03-29 17:03:23 +000057#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000058#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000059#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000060#include "lldb/Interpreter/OptionValueProperties.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000061#include "lldb/Interpreter/Options.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000062#include "lldb/Interpreter/Property.h"
Pavel Labath145d95c2018-04-17 18:53:35 +000063#include "lldb/Utility/Args.h"
Enrico Granatab5887262012-10-29 21:18:03 +000064
Chris Lattner30fdc8d2010-06-08 16:52:24 +000065#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066#include "lldb/Target/TargetList.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000067#include "lldb/Target/Thread.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000068
Saleem Abdulrasool28606952014-06-27 05:17:41 +000069#include "llvm/ADT/STLExtras.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000070#include "llvm/ADT/SmallString.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000071#include "llvm/Support/Path.h"
Sean Callanan237c3ed2016-12-14 21:31:31 +000072#include "llvm/Support/PrettyStackTrace.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000073
Chris Lattner30fdc8d2010-06-08 16:52:24 +000074using namespace lldb;
75using namespace lldb_private;
76
Adrian McCarthy2304b6f2015-04-23 20:00:25 +000077static const char *k_white_space = " \t\v";
Greg Clayton754a9362012-08-23 00:22:02 +000078
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +000079static constexpr const char *InitFileWarning =
80 "There is a .lldbinit file in the current directory which is not being "
81 "read.\n"
82 "To silence this warning without sourcing in the local .lldbinit,\n"
83 "add the following to the lldbinit file in your home directory:\n"
84 " settings set target.load-cwd-lldbinit false\n"
85 "To allow lldb to source .lldbinit files in the current working "
86 "directory,\n"
87 "set the value of this variable to true. Only do so if you understand "
88 "and\n"
89 "accept the security risk.";
Stefan Granitzc678ed72018-10-05 16:49:47 +000090
Jonas Devliegherea8ea5952019-07-29 16:41:30 +000091#define LLDB_PROPERTIES_interpreter
Jordan Rupprecht6a253d32019-07-29 17:22:10 +000092#include "InterpreterProperties.inc"
Kate Stoneb9c1b512016-09-06 20:57:50 +000093
94enum {
Jonas Devliegherea8ea5952019-07-29 16:41:30 +000095#define LLDB_PROPERTIES_interpreter
Jordan Rupprecht6a253d32019-07-29 17:22:10 +000096#include "InterpreterPropertiesEnum.inc"
Greg Clayton754a9362012-08-23 00:22:02 +000097};
98
Kate Stoneb9c1b512016-09-06 20:57:50 +000099ConstString &CommandInterpreter::GetStaticBroadcasterClass() {
100 static ConstString class_name("lldb.commandInterpreter");
101 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000102}
103
Kate Stoneb9c1b512016-09-06 20:57:50 +0000104CommandInterpreter::CommandInterpreter(Debugger &debugger,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105 bool synchronous_execution)
106 : Broadcaster(debugger.GetBroadcasterManager(),
107 CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
108 Properties(OptionValuePropertiesSP(
109 new OptionValueProperties(ConstString("interpreter")))),
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000110 IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand),
Jonas Devlieghere70df51b2019-07-31 23:34:45 +0000111 m_debugger(debugger), m_synchronous_execution(true),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112 m_skip_lldbinit_files(false), m_skip_app_init_files(false),
Jonas Devlieghere2b29b432019-04-26 22:43:16 +0000113 m_command_io_handler_sp(), m_comment_char('#'),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114 m_batch_command_mode(false), m_truncation_warning(eNoTruncation),
115 m_command_source_depth(0), m_num_errors(0), m_quit_requested(false),
116 m_stopped_for_crash(false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit");
118 SetEventName(eBroadcastBitResetPrompt, "reset-prompt");
119 SetEventName(eBroadcastBitQuitCommandReceived, "quit");
Jonas Devlieghere70df51b2019-07-31 23:34:45 +0000120 SetSynchronous(synchronous_execution);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121 CheckInWithManager();
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000122 m_collection_sp->Initialize(g_interpreter_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000123}
124
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125bool CommandInterpreter::GetExpandRegexAliases() const {
126 const uint32_t idx = ePropertyExpandRegexAliases;
127 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000128 nullptr, idx, g_interpreter_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000129}
130
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131bool CommandInterpreter::GetPromptOnQuit() const {
132 const uint32_t idx = ePropertyPromptOnQuit;
133 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000134 nullptr, idx, g_interpreter_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000135}
Greg Clayton754a9362012-08-23 00:22:02 +0000136
Kate Stoneb9c1b512016-09-06 20:57:50 +0000137void CommandInterpreter::SetPromptOnQuit(bool b) {
138 const uint32_t idx = ePropertyPromptOnQuit;
139 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ilia Kacf28be2015-03-23 22:45:13 +0000140}
141
Stefan Granitzc678ed72018-10-05 16:49:47 +0000142bool CommandInterpreter::GetEchoCommands() const {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000143 const uint32_t idx = ePropertyEchoCommands;
Stefan Granitzc678ed72018-10-05 16:49:47 +0000144 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000145 nullptr, idx, g_interpreter_properties[idx].default_uint_value != 0);
Stefan Granitzc678ed72018-10-05 16:49:47 +0000146}
147
148void CommandInterpreter::SetEchoCommands(bool b) {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000149 const uint32_t idx = ePropertyEchoCommands;
Stefan Granitzc678ed72018-10-05 16:49:47 +0000150 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
151}
152
153bool CommandInterpreter::GetEchoCommentCommands() const {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000154 const uint32_t idx = ePropertyEchoCommentCommands;
Stefan Granitzc678ed72018-10-05 16:49:47 +0000155 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000156 nullptr, idx, g_interpreter_properties[idx].default_uint_value != 0);
Stefan Granitzc678ed72018-10-05 16:49:47 +0000157}
158
159void CommandInterpreter::SetEchoCommentCommands(bool b) {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000160 const uint32_t idx = ePropertyEchoCommentCommands;
Stefan Granitzc678ed72018-10-05 16:49:47 +0000161 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
162}
163
Raphael Isemannc094d232018-07-11 17:18:01 +0000164void CommandInterpreter::AllowExitCodeOnQuit(bool allow) {
165 m_allow_exit_code = allow;
166 if (!allow)
167 m_quit_exit_code.reset();
168}
169
170bool CommandInterpreter::SetQuitExitCode(int exit_code) {
171 if (!m_allow_exit_code)
172 return false;
173 m_quit_exit_code = exit_code;
174 return true;
175}
176
177int CommandInterpreter::GetQuitExitCode(bool &exited) const {
178 exited = m_quit_exit_code.hasValue();
179 if (exited)
180 return *m_quit_exit_code;
181 return 0;
182}
183
Kate Stoneb9c1b512016-09-06 20:57:50 +0000184void CommandInterpreter::ResolveCommand(const char *command_line,
185 CommandReturnObject &result) {
186 std::string command = command_line;
187 if (ResolveCommandImpl(command, result) != nullptr) {
188 result.AppendMessageWithFormat("%s", command.c_str());
189 result.SetStatus(eReturnStatusSuccessFinishResult);
190 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000191}
192
Kate Stoneb9c1b512016-09-06 20:57:50 +0000193bool CommandInterpreter::GetStopCmdSourceOnError() const {
194 const uint32_t idx = ePropertyStopCmdSourceOnError;
195 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000196 nullptr, idx, g_interpreter_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000197}
198
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199bool CommandInterpreter::GetSpaceReplPrompts() const {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000200 const uint32_t idx = ePropertySpaceReplPrompts;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000202 nullptr, idx, g_interpreter_properties[idx].default_uint_value != 0);
Sean Callanan66810412015-10-19 23:11:07 +0000203}
204
Kate Stoneb9c1b512016-09-06 20:57:50 +0000205void CommandInterpreter::Initialize() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000206 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
207 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000208
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209 CommandReturnObject result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000210
Kate Stoneb9c1b512016-09-06 20:57:50 +0000211 LoadCommandDictionary();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000212
Kate Stoneb9c1b512016-09-06 20:57:50 +0000213 // An alias arguments vector to reuse - reset it before use...
214 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
215
216 // Set up some initial aliases.
217 CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
218 if (cmd_obj_sp) {
219 AddAlias("q", cmd_obj_sp);
220 AddAlias("exit", cmd_obj_sp);
221 }
222
223 cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
224 if (cmd_obj_sp)
225 AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
226
227 cmd_obj_sp = GetCommandSPExact("process detach", false);
228 if (cmd_obj_sp) {
229 AddAlias("detach", cmd_obj_sp);
230 }
231
232 cmd_obj_sp = GetCommandSPExact("process continue", false);
233 if (cmd_obj_sp) {
234 AddAlias("c", cmd_obj_sp);
235 AddAlias("continue", cmd_obj_sp);
236 }
237
238 cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
239 if (cmd_obj_sp)
240 AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
241
242 cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
243 if (cmd_obj_sp)
244 AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
245
246 cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
247 if (cmd_obj_sp) {
248 AddAlias("stepi", cmd_obj_sp);
249 AddAlias("si", cmd_obj_sp);
250 }
251
252 cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
253 if (cmd_obj_sp) {
254 AddAlias("nexti", cmd_obj_sp);
255 AddAlias("ni", cmd_obj_sp);
256 }
257
258 cmd_obj_sp = GetCommandSPExact("thread step-in", false);
259 if (cmd_obj_sp) {
260 AddAlias("s", cmd_obj_sp);
261 AddAlias("step", cmd_obj_sp);
262 CommandAlias *sif_alias = AddAlias(
263 "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
264 if (sif_alias) {
265 sif_alias->SetHelp("Step through the current block, stopping if you step "
266 "directly into a function whose name matches the "
267 "TargetFunctionName.");
268 sif_alias->SetSyntax("sif <TargetFunctionName>");
Caroline Ticeca90c472011-05-06 21:37:15 +0000269 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000271
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272 cmd_obj_sp = GetCommandSPExact("thread step-over", false);
273 if (cmd_obj_sp) {
274 AddAlias("n", cmd_obj_sp);
275 AddAlias("next", cmd_obj_sp);
276 }
277
278 cmd_obj_sp = GetCommandSPExact("thread step-out", false);
279 if (cmd_obj_sp) {
280 AddAlias("finish", cmd_obj_sp);
281 }
282
283 cmd_obj_sp = GetCommandSPExact("frame select", false);
284 if (cmd_obj_sp) {
285 AddAlias("f", cmd_obj_sp);
286 }
287
288 cmd_obj_sp = GetCommandSPExact("thread select", false);
289 if (cmd_obj_sp) {
290 AddAlias("t", cmd_obj_sp);
291 }
292
293 cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
294 if (cmd_obj_sp) {
295 AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
296 AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
297 }
298
299 cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
300 if (cmd_obj_sp) {
301 AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
302 AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
303 }
304
305 cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
306 if (cmd_obj_sp)
307 AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
308
309 cmd_obj_sp = GetCommandSPExact("memory read", false);
310 if (cmd_obj_sp)
311 AddAlias("x", cmd_obj_sp);
312
313 cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
314 if (cmd_obj_sp)
315 AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
316
317 cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
318 if (cmd_obj_sp)
319 AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
320
321 cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
322 if (cmd_obj_sp)
323 AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
324
325 cmd_obj_sp = GetCommandSPExact("disassemble", false);
326 if (cmd_obj_sp)
327 AddAlias("dis", cmd_obj_sp);
328
329 cmd_obj_sp = GetCommandSPExact("disassemble", false);
330 if (cmd_obj_sp)
331 AddAlias("di", cmd_obj_sp);
332
333 cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
334 if (cmd_obj_sp)
335 AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
336
337 cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
338 if (cmd_obj_sp)
339 AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
340
341 cmd_obj_sp = GetCommandSPExact("target create", false);
342 if (cmd_obj_sp)
343 AddAlias("file", cmd_obj_sp);
344
345 cmd_obj_sp = GetCommandSPExact("target modules", false);
346 if (cmd_obj_sp)
347 AddAlias("image", cmd_obj_sp);
348
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000349 alias_arguments_vector_sp = std::make_shared<OptionArgVector>();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350
351 cmd_obj_sp = GetCommandSPExact("expression", false);
352 if (cmd_obj_sp) {
353 AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
354 AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
355 AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
356 if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
357 po->SetHelp("Evaluate an expression on the current thread. Displays any "
358 "returned value with formatting "
359 "controlled by the type's author.");
360 po->SetHelpLong("");
Johnny Chen6d675242012-08-24 18:15:45 +0000361 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
363 AddAlias("poarray", cmd_obj_sp,
364 "--object-description --element-count %1 --")
365 ->SetHelpLong("");
366 }
Johnny Chen6d675242012-08-24 18:15:45 +0000367
Kate Stoneb9c1b512016-09-06 20:57:50 +0000368 cmd_obj_sp = GetCommandSPExact("process kill", false);
369 if (cmd_obj_sp) {
370 AddAlias("kill", cmd_obj_sp);
371 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000372
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 cmd_obj_sp = GetCommandSPExact("process launch", false);
374 if (cmd_obj_sp) {
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000375 alias_arguments_vector_sp = std::make_shared<OptionArgVector>();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000376#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
377 AddAlias("r", cmd_obj_sp, "--");
378 AddAlias("run", cmd_obj_sp, "--");
Jason Molenda85da3122012-07-06 02:46:23 +0000379#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380#if defined(__APPLE__)
381 std::string shell_option;
382 shell_option.append("--shell-expand-args");
383 shell_option.append(" true");
384 shell_option.append(" --");
385 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
386 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
387#else
388 StreamString defaultshell;
389 defaultshell.Printf("--shell=%s --",
390 HostInfo::GetDefaultShell().GetPath().c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +0000391 AddAlias("r", cmd_obj_sp, defaultshell.GetString());
392 AddAlias("run", cmd_obj_sp, defaultshell.GetString());
Jason Molenda85da3122012-07-06 02:46:23 +0000393#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394#endif
395 }
396
397 cmd_obj_sp = GetCommandSPExact("target symbols add", false);
398 if (cmd_obj_sp) {
399 AddAlias("add-dsym", cmd_obj_sp);
400 }
401
402 cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
403 if (cmd_obj_sp) {
404 AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
405 }
Jim Ingham285ae0c2018-10-10 00:51:30 +0000406
407 cmd_obj_sp = GetCommandSPExact("frame variable", false);
408 if (cmd_obj_sp) {
Jim Ingham9082c1c2018-10-12 18:46:02 +0000409 AddAlias("v", cmd_obj_sp);
Jim Ingham285ae0c2018-10-10 00:51:30 +0000410 AddAlias("var", cmd_obj_sp);
411 AddAlias("vo", cmd_obj_sp, "--object-description");
412 }
Jonas Devliegheree5f7d602019-05-03 20:37:09 +0000413
414 cmd_obj_sp = GetCommandSPExact("register", false);
415 if (cmd_obj_sp) {
416 AddAlias("re", cmd_obj_sp);
417 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000418}
419
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420void CommandInterpreter::Clear() {
421 m_command_io_handler_sp.reset();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000422}
423
Kate Stoneb9c1b512016-09-06 20:57:50 +0000424const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
425 // This function has not yet been implemented.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000426
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427 // Look for any embedded script command
428 // If found,
429 // get interpreter object from the command dictionary,
430 // call execute_one_command on it,
431 // get the results as a string,
432 // substitute that string for current stuff.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000433
Kate Stoneb9c1b512016-09-06 20:57:50 +0000434 return arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000435}
436
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437void CommandInterpreter::LoadCommandDictionary() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000438 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
439 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000440
Kate Stoneb9c1b512016-09-06 20:57:50 +0000441 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000442
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
444 m_command_dict["breakpoint"] =
445 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446 m_command_dict["command"] =
447 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
448 m_command_dict["disassemble"] =
449 CommandObjectSP(new CommandObjectDisassemble(*this));
450 m_command_dict["expression"] =
451 CommandObjectSP(new CommandObjectExpression(*this));
452 m_command_dict["frame"] =
453 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
454 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
455 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
456 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
457 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
458 m_command_dict["platform"] =
459 CommandObjectSP(new CommandObjectPlatform(*this));
460 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
461 m_command_dict["process"] =
462 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
463 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
464 m_command_dict["register"] =
465 CommandObjectSP(new CommandObjectRegister(*this));
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000466 m_command_dict["reproducer"] =
467 CommandObjectSP(new CommandObjectReproducer(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468 m_command_dict["script"] =
469 CommandObjectSP(new CommandObjectScript(*this, script_language));
470 m_command_dict["settings"] =
471 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
472 m_command_dict["source"] =
473 CommandObjectSP(new CommandObjectMultiwordSource(*this));
Davide Italiano24fff242018-04-13 18:02:39 +0000474 m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000475 m_command_dict["target"] =
476 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
477 m_command_dict["thread"] =
478 CommandObjectSP(new CommandObjectMultiwordThread(*this));
479 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
480 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
481 m_command_dict["watchpoint"] =
482 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
483 m_command_dict["language"] =
484 CommandObjectSP(new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000485
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486 const char *break_regexes[][2] = {
487 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
488 "breakpoint set --file '%1' --line %2"},
489 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
490 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
491 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
492 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
493 "breakpoint set --name '%1'"},
494 {"^(-.*)$", "breakpoint set %1"},
495 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
496 "breakpoint set --name '%2' --shlib '%1'"},
497 {"^\\&(.*[^[:space:]])[[:space:]]*$",
498 "breakpoint set --name '%1' --skip-prologue=0"},
499 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
500 "breakpoint set --name '%1'"}};
Kate Stone7428a182016-07-14 22:03:10 +0000501
Kate Stoneb9c1b512016-09-06 20:57:50 +0000502 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000503
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000504 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505 new CommandObjectRegexCommand(
506 *this, "_regexp-break",
Raphael Isemann129fe892018-07-30 21:41:13 +0000507 "Set a breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508 "\n"
509 "_regexp-break <filename>:<linenum>\n"
510 " main.c:12 // Break at line 12 of "
511 "main.c\n\n"
512 "_regexp-break <linenum>\n"
513 " 12 // Break at line 12 of current "
514 "file\n\n"
515 "_regexp-break 0x<address>\n"
516 " 0x1234000 // Break at address "
517 "0x1234000\n\n"
518 "_regexp-break <name>\n"
519 " main // Break in 'main' after the "
520 "prologue\n\n"
521 "_regexp-break &<name>\n"
522 " &main // Break at first instruction "
523 "in 'main'\n\n"
524 "_regexp-break <module>`<name>\n"
525 " libc.so`malloc // Break in 'malloc' from "
526 "'libc.so'\n\n"
527 "_regexp-break /<source-regex>/\n"
528 " /break here/ // Break on source lines in "
529 "current file\n"
530 " // containing text 'break "
531 "here'.\n",
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000532 2,
533 CommandCompletions::eSymbolCompletion |
534 CommandCompletions::eSourceFileCompletion,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000535 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000536
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000537 if (break_regex_cmd_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538 bool success = true;
539 for (size_t i = 0; i < num_regexes; i++) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000540 success = break_regex_cmd_up->AddRegexCommand(break_regexes[i][0],
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 break_regexes[i][1]);
542 if (!success)
543 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000544 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545 success =
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000546 break_regex_cmd_up->AddRegexCommand("^$", "breakpoint list --full");
Jim Inghamffba2292011-03-22 02:29:32 +0000547
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 if (success) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000549 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
Jim Inghamca36cd12012-10-05 19:16:31 +0000551 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 }
Jim Inghamca36cd12012-10-05 19:16:31 +0000553
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000554 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 new CommandObjectRegexCommand(
556 *this, "_regexp-tbreak",
Raphael Isemann129fe892018-07-30 21:41:13 +0000557 "Set a one-shot breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 "\n"
559 "_regexp-break <filename>:<linenum>\n"
560 " main.c:12 // Break at line 12 of "
561 "main.c\n\n"
562 "_regexp-break <linenum>\n"
563 " 12 // Break at line 12 of current "
564 "file\n\n"
565 "_regexp-break 0x<address>\n"
566 " 0x1234000 // Break at address "
567 "0x1234000\n\n"
568 "_regexp-break <name>\n"
569 " main // Break in 'main' after the "
570 "prologue\n\n"
571 "_regexp-break &<name>\n"
572 " &main // Break at first instruction "
573 "in 'main'\n\n"
574 "_regexp-break <module>`<name>\n"
575 " libc.so`malloc // Break in 'malloc' from "
576 "'libc.so'\n\n"
577 "_regexp-break /<source-regex>/\n"
578 " /break here/ // Break on source lines in "
579 "current file\n"
580 " // containing text 'break "
581 "here'.\n",
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000582 2,
583 CommandCompletions::eSymbolCompletion |
584 CommandCompletions::eSourceFileCompletion,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585 false));
586
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000587 if (tbreak_regex_cmd_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000588 bool success = true;
589 for (size_t i = 0; i < num_regexes; i++) {
590 // If you add a resultant command string longer than 1024 characters be
591 // sure to increase the size of this buffer.
592 char buffer[1024];
593 int num_printed =
Frederic Riss49c9d8b2018-06-18 04:34:33 +0000594 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1");
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000595 lldbassert(num_printed < 1024);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596 UNUSED_IF_ASSERT_DISABLED(num_printed);
597 success =
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000598 tbreak_regex_cmd_up->AddRegexCommand(break_regexes[i][0], buffer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599 if (!success)
600 break;
Johnny Chen6d675242012-08-24 18:15:45 +0000601 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000602 success =
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000603 tbreak_regex_cmd_up->AddRegexCommand("^$", "breakpoint list --full");
Kate Stone7428a182016-07-14 22:03:10 +0000604
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605 if (success) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000606 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000607 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
608 tbreak_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000609 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000610 }
Kate Stone7428a182016-07-14 22:03:10 +0000611
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000612 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613 new CommandObjectRegexCommand(
614 *this, "_regexp-attach", "Attach to process by ID or name.",
615 "_regexp-attach <pid> | <process-name>", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000616 if (attach_regex_cmd_up) {
617 if (attach_regex_cmd_up->AddRegexCommand("^([0-9]+)[[:space:]]*$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000618 "process attach --pid %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000619 attach_regex_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000620 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
621 // specified get passed to
622 // 'process attach'
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000623 attach_regex_cmd_up->AddRegexCommand("^(.+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000624 "process attach --name '%1'") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000625 attach_regex_cmd_up->AddRegexCommand("^$", "process attach")) {
626 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
628 attach_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000629 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000631
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000632 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633 new CommandObjectRegexCommand(*this, "_regexp-down",
634 "Select a newer stack frame. Defaults to "
635 "moving one frame, a numeric argument can "
636 "specify an arbitrary number.",
637 "_regexp-down [<count>]", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000638 if (down_regex_cmd_up) {
639 if (down_regex_cmd_up->AddRegexCommand("^$", "frame select -r -1") &&
640 down_regex_cmd_up->AddRegexCommand("^([0-9]+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641 "frame select -r -%1")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000642 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000643 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000644 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000645 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000646
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000647 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648 new CommandObjectRegexCommand(
649 *this, "_regexp-up",
650 "Select an older stack frame. Defaults to moving one "
651 "frame, a numeric argument can specify an arbitrary number.",
652 "_regexp-up [<count>]", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000653 if (up_regex_cmd_up) {
654 if (up_regex_cmd_up->AddRegexCommand("^$", "frame select -r 1") &&
655 up_regex_cmd_up->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
656 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000658 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000660
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000661 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000662 new CommandObjectRegexCommand(
663 *this, "_regexp-display",
664 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
665 "_regexp-display expression", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000666 if (display_regex_cmd_up) {
667 if (display_regex_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000669 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
671 display_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000672 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000674
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000675 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_up(
676 new CommandObjectRegexCommand(*this, "_regexp-undisplay",
677 "Stop displaying expression at every "
678 "stop (specified by stop-hook index.)",
679 "_regexp-undisplay stop-hook-number", 2, 0,
680 false));
681 if (undisplay_regex_cmd_up) {
682 if (undisplay_regex_cmd_up->AddRegexCommand("^([0-9]+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000683 "target stop-hook delete %1")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000684 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000685 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
686 undisplay_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000687 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000688 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000689
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000690 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691 new CommandObjectRegexCommand(
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000692 *this, "gdb-remote",
693 "Connect to a process via remote GDB server. "
694 "If no host is specifed, localhost is assumed.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000696 if (connect_gdb_remote_cmd_up) {
697 if (connect_gdb_remote_cmd_up->AddRegexCommand(
Chris Bieneman51978f52017-04-27 16:13:58 +0000698 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
699 "process connect --plugin gdb-remote connect://%1:%2") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000700 connect_gdb_remote_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701 "^([[:digit:]]+)$",
702 "process connect --plugin gdb-remote connect://localhost:%1")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000703 CommandObjectSP command_sp(connect_gdb_remote_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000704 m_command_dict[command_sp->GetCommandName()] = command_sp;
Jason Molenda4cddfed2012-10-05 05:29:32 +0000705 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000706 }
Jason Molenda4cddfed2012-10-05 05:29:32 +0000707
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000708 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000709 new CommandObjectRegexCommand(
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000710 *this, "kdp-remote",
711 "Connect to a process via remote KDP server. "
712 "If no UDP port is specified, port 41139 is "
713 "assumed.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000714 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000715 if (connect_kdp_remote_cmd_up) {
716 if (connect_kdp_remote_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717 "^([^:]+:[[:digit:]]+)$",
718 "process connect --plugin kdp-remote udp://%1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000719 connect_kdp_remote_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000720 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000721 CommandObjectSP command_sp(connect_kdp_remote_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Clayton6bade322013-02-01 23:33:03 +0000723 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000724 }
Greg Clayton6bade322013-02-01 23:33:03 +0000725
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000726 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727 new CommandObjectRegexCommand(
728 *this, "_regexp-bt",
729 "Show the current thread's call stack. Any numeric argument "
730 "displays at most that many "
Jim Inghame91ad7d2019-05-02 02:14:08 +0000731 "frames. The argument 'all' displays all threads. Use 'settings"
732 " set frame-format' to customize the printing of individual frames "
733 "and 'settings set thread-format' to customize the thread header.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000734 "bt [<digit> | all]", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000735 if (bt_regex_cmd_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000736 // accept but don't document "bt -c <number>" -- before bt was a regex
Adrian Prantl05097242018-04-30 16:49:04 +0000737 // command if you wanted to backtrace three frames you would do "bt -c 3"
738 // but the intention is to have this emulate the gdb "bt" command and so
739 // now "bt 3" is the preferred form, in line with gdb.
Stella Stamenova5bac7062019-05-17 18:52:42 +0000740 if (bt_regex_cmd_up->AddRegexCommand("^([[:digit:]]+)[[:space:]]*$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741 "thread backtrace -c %1") &&
Stella Stamenova5bac7062019-05-17 18:52:42 +0000742 bt_regex_cmd_up->AddRegexCommand("^-c ([[:digit:]]+)[[:space:]]*$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000743 "thread backtrace -c %1") &&
Stella Stamenova5bac7062019-05-17 18:52:42 +0000744 bt_regex_cmd_up->AddRegexCommand("^all[[:space:]]*$", "thread backtrace all") &&
745 bt_regex_cmd_up->AddRegexCommand("^[[:space:]]*$", "thread backtrace")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000746 CommandObjectSP command_sp(bt_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000747 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Claytonef5651d2013-02-12 18:52:24 +0000748 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000749 }
Greg Claytonef5651d2013-02-12 18:52:24 +0000750
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000751 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 new CommandObjectRegexCommand(
753 *this, "_regexp-list",
754 "List relevant source code using one of several shorthand formats.",
755 "\n"
756 "_regexp-list <file>:<line> // List around specific file/line\n"
757 "_regexp-list <line> // List current file around specified "
758 "line\n"
759 "_regexp-list <function-name> // List specified function\n"
760 "_regexp-list 0x<address> // List around specified address\n"
761 "_regexp-list -[<count>] // List previous <count> lines\n"
762 "_regexp-list // List subsequent lines",
763 2, CommandCompletions::eSourceFileCompletion, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000764 if (list_regex_cmd_up) {
765 if (list_regex_cmd_up->AddRegexCommand("^([0-9]+)[[:space:]]*$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000766 "source list --line %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000767 list_regex_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000768 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
769 "]*$",
770 "source list --file '%1' --line %2") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000771 list_regex_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
773 "source list --address %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000774 list_regex_cmd_up->AddRegexCommand("^-[[:space:]]*$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 "source list --reverse") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000776 list_regex_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777 "^-([[:digit:]]+)[[:space:]]*$",
778 "source list --reverse --count %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000779 list_regex_cmd_up->AddRegexCommand("^(.+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000780 "source list --name \"%1\"") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000781 list_regex_cmd_up->AddRegexCommand("^$", "source list")) {
782 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
Richard Mittonf86248d2013-09-12 02:20:34 +0000784 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000785 }
Richard Mittonf86248d2013-09-12 02:20:34 +0000786
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000787 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000788 new CommandObjectRegexCommand(
789 *this, "_regexp-env",
790 "Shorthand for viewing and setting environment variables.",
791 "\n"
Adrian McCarthy17c18a92019-06-25 23:13:16 +0000792 "_regexp-env // Show environment\n"
Kate Stoneb9c1b512016-09-06 20:57:50 +0000793 "_regexp-env <name>=<value> // Set an environment variable",
794 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000795 if (env_regex_cmd_up) {
796 if (env_regex_cmd_up->AddRegexCommand("^$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 "settings show target.env-vars") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000798 env_regex_cmd_up->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799 "settings set target.env-vars %1")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000800 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
802 }
803 }
804
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000805 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000806 new CommandObjectRegexCommand(
807 *this, "_regexp-jump", "Set the program counter to a new address.",
808 "\n"
809 "_regexp-jump <line>\n"
810 "_regexp-jump +<line-offset> | -<line-offset>\n"
811 "_regexp-jump <file>:<line>\n"
812 "_regexp-jump *<addr>\n",
813 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000814 if (jump_regex_cmd_up) {
815 if (jump_regex_cmd_up->AddRegexCommand("^\\*(.*)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816 "thread jump --addr %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000817 jump_regex_cmd_up->AddRegexCommand("^([0-9]+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 "thread jump --line %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000819 jump_regex_cmd_up->AddRegexCommand("^([^:]+):([0-9]+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000820 "thread jump --file %1 --line %2") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000821 jump_regex_cmd_up->AddRegexCommand("^([+\\-][0-9]+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000822 "thread jump --by %1")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000823 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000824 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
825 }
826 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000827}
828
Kate Stoneb9c1b512016-09-06 20:57:50 +0000829int CommandInterpreter::GetCommandNamesMatchingPartialString(
Raphael Isemann7f888292018-09-13 21:26:00 +0000830 const char *cmd_str, bool include_aliases, StringList &matches,
831 StringList &descriptions) {
832 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches,
833 &descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000834
Kate Stoneb9c1b512016-09-06 20:57:50 +0000835 if (include_aliases) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000836 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches,
837 &descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000838 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000839
Kate Stoneb9c1b512016-09-06 20:57:50 +0000840 return matches.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000841}
842
Raphael Isemann7f888292018-09-13 21:26:00 +0000843CommandObjectSP
844CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases,
845 bool exact, StringList *matches,
846 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000847 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000848
Zachary Turnera4496982016-10-05 21:14:38 +0000849 std::string cmd = cmd_str;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000850
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 if (HasCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000852 auto pos = m_command_dict.find(cmd);
Greg Claytonb5472782015-01-09 19:08:20 +0000853 if (pos != m_command_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000854 command_sp = pos->second;
855 }
856
857 if (include_aliases && HasAliases()) {
858 auto alias_pos = m_alias_dict.find(cmd);
859 if (alias_pos != m_alias_dict.end())
860 command_sp = alias_pos->second;
861 }
862
863 if (HasUserCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000864 auto pos = m_user_dict.find(cmd);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000865 if (pos != m_user_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866 command_sp = pos->second;
867 }
868
869 if (!exact && !command_sp) {
870 // We will only get into here if we didn't find any exact matches.
871
872 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
873
874 StringList local_matches;
875 if (matches == nullptr)
876 matches = &local_matches;
877
878 unsigned int num_cmd_matches = 0;
879 unsigned int num_alias_matches = 0;
880 unsigned int num_user_matches = 0;
881
882 // Look through the command dictionaries one by one, and if we get only one
Adrian Prantl05097242018-04-30 16:49:04 +0000883 // match from any of them in toto, then return that, otherwise return an
884 // empty CommandObjectSP and the list of matches.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885
886 if (HasCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000887 num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str,
888 *matches, descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000889 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000890
891 if (num_cmd_matches == 1) {
892 cmd.assign(matches->GetStringAtIndex(0));
Zachary Turnera4496982016-10-05 21:14:38 +0000893 auto pos = m_command_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000894 if (pos != m_command_dict.end())
895 real_match_sp = pos->second;
896 }
897
898 if (include_aliases && HasAliases()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000899 num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str,
900 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901 }
902
903 if (num_alias_matches == 1) {
904 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
905 auto alias_pos = m_alias_dict.find(cmd);
906 if (alias_pos != m_alias_dict.end())
907 alias_match_sp = alias_pos->second;
908 }
909
910 if (HasUserCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000911 num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str,
912 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000913 }
914
915 if (num_user_matches == 1) {
916 cmd.assign(
917 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
918
Zachary Turnera4496982016-10-05 21:14:38 +0000919 auto pos = m_user_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920 if (pos != m_user_dict.end())
921 user_match_sp = pos->second;
922 }
923
924 // If we got exactly one match, return that, otherwise return the match
925 // list.
926
927 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
928 if (num_cmd_matches)
929 return real_match_sp;
930 else if (num_alias_matches)
931 return alias_match_sp;
932 else
933 return user_match_sp;
934 }
935 } else if (matches && command_sp) {
Zachary Turnera4496982016-10-05 21:14:38 +0000936 matches->AppendString(cmd_str);
Raphael Isemann7f888292018-09-13 21:26:00 +0000937 if (descriptions)
938 descriptions->AppendString(command_sp->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000939 }
940
941 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000942}
943
Zachary Turnera4496982016-10-05 21:14:38 +0000944bool CommandInterpreter::AddCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000945 const lldb::CommandObjectSP &cmd_sp,
946 bool can_replace) {
947 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000948 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
949 "tried to add a CommandObject from a different interpreter");
Kate Stonea487aa42015-01-15 00:52:41 +0000950
Zachary Turnera4496982016-10-05 21:14:38 +0000951 if (name.empty())
952 return false;
953
954 std::string name_sstr(name);
955 auto name_iter = m_command_dict.find(name_sstr);
956 if (name_iter != m_command_dict.end()) {
957 if (!can_replace || !name_iter->second->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000958 return false;
Zachary Turnera4496982016-10-05 21:14:38 +0000959 name_iter->second = cmd_sp;
960 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961 m_command_dict[name_sstr] = cmd_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000962 }
Zachary Turnera4496982016-10-05 21:14:38 +0000963 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000964}
965
Zachary Turnera483f572016-10-05 21:14:49 +0000966bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000967 const lldb::CommandObjectSP &cmd_sp,
968 bool can_replace) {
969 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000970 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
971 "tried to add a CommandObject from a different interpreter");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000972
Kate Stoneb9c1b512016-09-06 20:57:50 +0000973 if (!name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 // do not allow replacement of internal commands
Zachary Turnera483f572016-10-05 21:14:49 +0000975 if (CommandExists(name)) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000976 if (!can_replace)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000977 return false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000978 if (!m_command_dict[name]->IsRemovable())
Greg Clayton5a314712011-10-14 07:41:33 +0000979 return false;
980 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000981
Zachary Turnera483f572016-10-05 21:14:49 +0000982 if (UserCommandExists(name)) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000983 if (!can_replace)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 return false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000985 if (!m_user_dict[name]->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000986 return false;
Caroline Tice844d2302010-12-09 22:52:49 +0000987 }
988
Kate Stoneb9c1b512016-09-06 20:57:50 +0000989 m_user_dict[name] = cmd_sp;
990 return true;
991 }
992 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000993}
994
Zachary Turnera4496982016-10-05 21:14:38 +0000995CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
996 bool include_aliases) const {
997 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 // it's a multi-word command.
999 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001000
Zachary Turnera4496982016-10-05 21:14:38 +00001001 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002 return ret_val;
1003
1004 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +00001005 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001006 else {
1007 // We have a multi-word command (seemingly), so we need to do more work.
1008 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +00001009 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001010 include_aliases, true, nullptr);
1011 if (cmd_obj_sp.get() != nullptr) {
Adrian Prantl05097242018-04-30 16:49:04 +00001012 // Loop through the rest of the words in the command (everything passed
1013 // in was supposed to be part of a command name), and find the
1014 // appropriate sub-command SP for each command word....
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015 size_t end = cmd_words.GetArgumentCount();
1016 for (size_t j = 1; j < end; ++j) {
1017 if (cmd_obj_sp->IsMultiwordObject()) {
1018 cmd_obj_sp =
1019 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
1020 if (cmd_obj_sp.get() == nullptr)
1021 // The sub-command name was invalid. Fail and return the empty
1022 // 'ret_val'.
1023 return ret_val;
1024 } else
1025 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +00001026 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001027 return ret_val;
1028 }
1029 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +00001030 // command objects for them. Assign the last object retrieved to
1031 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001032 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001033 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001034 }
1035 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001036}
1037
Raphael Isemann7f888292018-09-13 21:26:00 +00001038CommandObject *
1039CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
1040 StringList *matches,
1041 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001042 CommandObject *command_obj =
Raphael Isemann7f888292018-09-13 21:26:00 +00001043 GetCommandSP(cmd_str, false, true, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001044
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 // If we didn't find an exact match to the command string in the commands,
Adrian Prantl05097242018-04-30 16:49:04 +00001046 // look in the aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001047
1048 if (command_obj)
1049 return command_obj;
1050
Raphael Isemann7f888292018-09-13 21:26:00 +00001051 command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001052
1053 if (command_obj)
1054 return command_obj;
1055
1056 // If there wasn't an exact match then look for an inexact one in just the
1057 // commands
Zachary Turnera4496982016-10-05 21:14:38 +00001058 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059
1060 // Finally, if there wasn't an inexact match among the commands, look for an
Adrian Prantl05097242018-04-30 16:49:04 +00001061 // inexact match in both the commands and aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001062
1063 if (command_obj) {
1064 if (matches)
1065 matches->AppendString(command_obj->GetCommandName());
Raphael Isemann7f888292018-09-13 21:26:00 +00001066 if (descriptions)
1067 descriptions->AppendString(command_obj->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001068 return command_obj;
1069 }
1070
Raphael Isemann7f888292018-09-13 21:26:00 +00001071 return GetCommandSP(cmd_str, true, false, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001072}
1073
Zachary Turnera483f572016-10-05 21:14:49 +00001074bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001076}
1077
Zachary Turnera483f572016-10-05 21:14:49 +00001078bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1079 std::string &full_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1081 if (exact_match) {
1082 full_name.assign(cmd);
1083 return exact_match;
1084 } else {
1085 StringList matches;
1086 size_t num_alias_matches;
1087 num_alias_matches =
1088 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1089 if (num_alias_matches == 1) {
1090 // Make sure this isn't shadowing a command in the regular command space:
1091 StringList regular_matches;
1092 const bool include_aliases = false;
1093 const bool exact = false;
1094 CommandObjectSP cmd_obj_sp(
1095 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1096 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1097 return false;
1098 else {
1099 full_name.assign(matches.GetStringAtIndex(0));
1100 return true;
1101 }
1102 } else
1103 return false;
1104 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001105}
1106
Zachary Turnera483f572016-10-05 21:14:49 +00001107bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001108 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001109}
1110
Zachary Turnera483f572016-10-05 21:14:49 +00001111bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001112 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001113}
1114
Kate Stoneb9c1b512016-09-06 20:57:50 +00001115CommandAlias *
Zachary Turnera483f572016-10-05 21:14:49 +00001116CommandInterpreter::AddAlias(llvm::StringRef alias_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001117 lldb::CommandObjectSP &command_obj_sp,
Zachary Turnera483f572016-10-05 21:14:49 +00001118 llvm::StringRef args_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001119 if (command_obj_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001120 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1121 "tried to add a CommandObject from a different interpreter");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122
1123 std::unique_ptr<CommandAlias> command_alias_up(
1124 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1125
1126 if (command_alias_up && command_alias_up->IsValid()) {
1127 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1128 return command_alias_up.release();
1129 }
1130
1131 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001132}
1133
Zachary Turnera483f572016-10-05 21:14:49 +00001134bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001135 auto pos = m_alias_dict.find(alias_name);
1136 if (pos != m_alias_dict.end()) {
1137 m_alias_dict.erase(pos);
1138 return true;
1139 }
1140 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141}
1142
Zachary Turnera483f572016-10-05 21:14:49 +00001143bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001144 auto pos = m_command_dict.find(cmd);
1145 if (pos != m_command_dict.end()) {
1146 if (pos->second->IsRemovable()) {
1147 // Only regular expression objects or python commands are removable
1148 m_command_dict.erase(pos);
1149 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001150 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001151 }
1152 return false;
1153}
Zachary Turnera483f572016-10-05 21:14:49 +00001154bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001155 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1156 if (pos != m_user_dict.end()) {
1157 m_user_dict.erase(pos);
1158 return true;
1159 }
1160 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001161}
1162
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163void CommandInterpreter::GetHelp(CommandReturnObject &result,
1164 uint32_t cmd_types) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001165 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1166 if (!help_prologue.empty()) {
1167 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1168 help_prologue);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001169 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001170
Kate Stoneb9c1b512016-09-06 20:57:50 +00001171 CommandObject::CommandMap::const_iterator pos;
1172 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001173
Kate Stoneb9c1b512016-09-06 20:57:50 +00001174 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1175 result.AppendMessage("Debugger commands:");
1176 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001177
Kate Stoneb9c1b512016-09-06 20:57:50 +00001178 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1179 if (!(cmd_types & eCommandTypesHidden) &&
1180 (pos->first.compare(0, 1, "_") == 0))
1181 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001182
Zachary Turner0ac5f982016-11-08 04:12:42 +00001183 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1184 pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001185 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001186 result.AppendMessage("");
1187 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001188
Kate Stoneb9c1b512016-09-06 20:57:50 +00001189 if (!m_alias_dict.empty() &&
1190 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1191 result.AppendMessageWithFormat(
1192 "Current command abbreviations "
1193 "(type '%shelp command alias' for more info):\n",
1194 GetCommandPrefix());
1195 result.AppendMessage("");
1196 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001197
Kate Stoneb9c1b512016-09-06 20:57:50 +00001198 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1199 ++alias_pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001200 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001202 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001203 result.AppendMessage("");
1204 }
Greg Clayton14a35512011-09-11 00:01:44 +00001205
Kate Stoneb9c1b512016-09-06 20:57:50 +00001206 if (!m_user_dict.empty() &&
1207 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1208 result.AppendMessage("Current user-defined commands:");
1209 result.AppendMessage("");
1210 max_len = FindLongestCommandWord(m_user_dict);
1211 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001212 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1213 pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001214 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001215 result.AppendMessage("");
1216 }
Greg Clayton14a35512011-09-11 00:01:44 +00001217
Kate Stoneb9c1b512016-09-06 20:57:50 +00001218 result.AppendMessageWithFormat(
1219 "For more information on any command, type '%shelp <command-name>'.\n",
1220 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001221}
1222
Zachary Turnera01bccd2016-10-05 21:14:56 +00001223CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1224 llvm::StringRef &command_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001225 // This function finds the final, lowest-level, alias-resolved command object
Adrian Prantl05097242018-04-30 16:49:04 +00001226 // whose 'Execute' function will eventually be invoked by the given command
1227 // line.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001228
1229 CommandObject *cmd_obj = nullptr;
1230 size_t start = command_string.find_first_not_of(k_white_space);
1231 size_t end = 0;
1232 bool done = false;
1233 while (!done) {
1234 if (start != std::string::npos) {
1235 // Get the next word from command_string.
1236 end = command_string.find_first_of(k_white_space, start);
1237 if (end == std::string::npos)
1238 end = command_string.size();
1239 std::string cmd_word = command_string.substr(start, end - start);
1240
1241 if (cmd_obj == nullptr)
1242 // Since cmd_obj is NULL we are on our first time through this loop.
Zachary Turnera01bccd2016-10-05 21:14:56 +00001243 // Check to see if cmd_word is a valid command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001244 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001245 else if (cmd_obj->IsMultiwordObject()) {
1246 // Our current object is a multi-word object; see if the cmd_word is a
1247 // valid sub-command for our object.
1248 CommandObject *sub_cmd_obj =
1249 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1250 if (sub_cmd_obj)
1251 cmd_obj = sub_cmd_obj;
1252 else // cmd_word was not a valid sub-command word, so we are done
1253 done = true;
1254 } else
1255 // We have a cmd_obj and it is not a multi-word object, so we are done.
1256 done = true;
1257
1258 // If we didn't find a valid command object, or our command object is not
Zachary Turnera01bccd2016-10-05 21:14:56 +00001259 // a multi-word object, or we are at the end of the command_string, then
1260 // we are done. Otherwise, find the start of the next word.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261
1262 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1263 end >= command_string.size())
1264 done = true;
1265 else
1266 start = command_string.find_first_not_of(k_white_space, end);
1267 } else
1268 // Unable to find any more words.
1269 done = true;
1270 }
1271
Zachary Turnera01bccd2016-10-05 21:14:56 +00001272 command_string = command_string.substr(end);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001273 return cmd_obj;
1274}
1275
1276static const char *k_valid_command_chars =
1277 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1278static void StripLeadingSpaces(std::string &s) {
1279 if (!s.empty()) {
1280 size_t pos = s.find_first_not_of(k_white_space);
1281 if (pos == std::string::npos)
1282 s.clear();
1283 else if (pos == 0)
1284 return;
1285 s.erase(0, pos);
1286 }
1287}
1288
1289static size_t FindArgumentTerminator(const std::string &s) {
1290 const size_t s_len = s.size();
1291 size_t offset = 0;
1292 while (offset < s_len) {
1293 size_t pos = s.find("--", offset);
1294 if (pos == std::string::npos)
1295 break;
1296 if (pos > 0) {
1297 if (isspace(s[pos - 1])) {
Adrian Prantl05097242018-04-30 16:49:04 +00001298 // Check if the string ends "\s--" (where \s is a space character) or
1299 // if we have "\s--\s".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001300 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1301 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001302 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001303 }
1304 }
1305 offset = pos + 2;
1306 }
1307 return std::string::npos;
1308}
1309
1310static bool ExtractCommand(std::string &command_string, std::string &command,
1311 std::string &suffix, char &quote_char) {
1312 command.clear();
1313 suffix.clear();
1314 StripLeadingSpaces(command_string);
1315
1316 bool result = false;
1317 quote_char = '\0';
1318
1319 if (!command_string.empty()) {
1320 const char first_char = command_string[0];
1321 if (first_char == '\'' || first_char == '"') {
1322 quote_char = first_char;
1323 const size_t end_quote_pos = command_string.find(quote_char, 1);
1324 if (end_quote_pos == std::string::npos) {
1325 command.swap(command_string);
1326 command_string.erase();
1327 } else {
1328 command.assign(command_string, 1, end_quote_pos - 1);
1329 if (end_quote_pos + 1 < command_string.size())
1330 command_string.erase(0, command_string.find_first_not_of(
1331 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001332 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001333 command_string.erase();
1334 }
1335 } else {
1336 const size_t first_space_pos =
1337 command_string.find_first_of(k_white_space);
1338 if (first_space_pos == std::string::npos) {
1339 command.swap(command_string);
1340 command_string.erase();
1341 } else {
1342 command.assign(command_string, 0, first_space_pos);
1343 command_string.erase(0, command_string.find_first_not_of(
1344 k_white_space, first_space_pos));
1345 }
1346 }
1347 result = true;
1348 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001349
Kate Stoneb9c1b512016-09-06 20:57:50 +00001350 if (!command.empty()) {
1351 // actual commands can't start with '-' or '_'
1352 if (command[0] != '-' && command[0] != '_') {
1353 size_t pos = command.find_first_not_of(k_valid_command_chars);
1354 if (pos > 0 && pos != std::string::npos) {
1355 suffix.assign(command.begin() + pos, command.end());
1356 command.erase(pos);
1357 }
1358 }
1359 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001360
Kate Stoneb9c1b512016-09-06 20:57:50 +00001361 return result;
1362}
1363
1364CommandObject *CommandInterpreter::BuildAliasResult(
Zachary Turnera483f572016-10-05 21:14:49 +00001365 llvm::StringRef alias_name, std::string &raw_input_string,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001366 std::string &alias_result, CommandReturnObject &result) {
1367 CommandObject *alias_cmd_obj = nullptr;
1368 Args cmd_args(raw_input_string);
1369 alias_cmd_obj = GetCommandObject(alias_name);
1370 StreamString result_str;
1371
Zachary Turner5c28c662016-10-03 23:20:36 +00001372 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1373 alias_result.clear();
1374 return alias_cmd_obj;
1375 }
1376 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1377 ((CommandAlias *)alias_cmd_obj)->Desugar();
1378 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1379 alias_cmd_obj = desugared.first.get();
1380 std::string alias_name_str = alias_name;
1381 if ((cmd_args.GetArgumentCount() == 0) ||
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001382 (alias_name_str != cmd_args.GetArgumentAtIndex(0)))
Zachary Turner5c28c662016-10-03 23:20:36 +00001383 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001384
Zachary Turnera4496982016-10-05 21:14:38 +00001385 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001386
Zachary Turner5c28c662016-10-03 23:20:36 +00001387 if (!option_arg_vector_sp.get()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001388 alias_result = result_str.GetString();
Zachary Turner5c28c662016-10-03 23:20:36 +00001389 return alias_cmd_obj;
1390 }
1391 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001392
Zachary Turner5c28c662016-10-03 23:20:36 +00001393 int value_type;
1394 std::string option;
1395 std::string value;
1396 for (const auto &entry : *option_arg_vector) {
1397 std::tie(option, value_type, value) = entry;
1398 if (option == "<argument>") {
1399 result_str.Printf(" %s", value.c_str());
1400 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001401 }
1402
Zachary Turner5c28c662016-10-03 23:20:36 +00001403 result_str.Printf(" %s", option.c_str());
1404 if (value_type == OptionParser::eNoArgument)
1405 continue;
1406
1407 if (value_type != OptionParser::eOptionalArgument)
1408 result_str.Printf(" ");
1409 int index = GetOptionArgumentPosition(value.c_str());
1410 if (index == 0)
1411 result_str.Printf("%s", value.c_str());
1412 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1413
1414 result.AppendErrorWithFormat("Not enough arguments provided; you "
1415 "need at least %d arguments to use "
1416 "this alias.\n",
1417 index);
1418 result.SetStatus(eReturnStatusFailed);
1419 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001420 } else {
1421 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1422 if (strpos != std::string::npos)
1423 raw_input_string = raw_input_string.erase(
1424 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1425 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001426 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001427 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001428
Zachary Turnerc1564272016-11-16 21:15:24 +00001429 alias_result = result_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001430 return alias_cmd_obj;
1431}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001432
Zachary Turner97206d52017-05-12 04:51:55 +00001433Status CommandInterpreter::PreprocessCommand(std::string &command) {
Adrian Prantl05097242018-04-30 16:49:04 +00001434 // The command preprocessor needs to do things to the command line before any
1435 // parsing of arguments or anything else is done. The only current stuff that
1436 // gets preprocessed is anything enclosed in backtick ('`') characters is
1437 // evaluated as an expression and the result of the expression must be a
1438 // scalar that can be substituted into the command. An example would be:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001439 // (lldb) memory read `$rsp + 20`
Zachary Turner97206d52017-05-12 04:51:55 +00001440 Status error; // Status for any expressions that might not evaluate
Kate Stoneb9c1b512016-09-06 20:57:50 +00001441 size_t start_backtick;
1442 size_t pos = 0;
1443 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001444 // Stop if an error was encountered during the previous iteration.
1445 if (error.Fail())
1446 break;
1447
Kate Stoneb9c1b512016-09-06 20:57:50 +00001448 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
Adrian Prantl05097242018-04-30 16:49:04 +00001449 // The backtick was preceded by a '\' character, remove the slash and
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001450 // don't treat the backtick as the start of an expression.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001451 command.erase(start_backtick - 1, 1);
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001452 // No need to add one to start_backtick since we just deleted a char.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001453 pos = start_backtick;
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001454 continue;
1455 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001456
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001457 const size_t expr_content_start = start_backtick + 1;
1458 const size_t end_backtick = command.find('`', expr_content_start);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001459
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001460 if (end_backtick == std::string::npos) {
1461 // Stop if there's no end backtick.
1462 break;
1463 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001464
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001465 if (end_backtick == expr_content_start) {
1466 // Skip over empty expression. (two backticks in a row)
1467 command.erase(start_backtick, 2);
1468 continue;
1469 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001470
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001471 std::string expr_str(command, expr_content_start,
1472 end_backtick - expr_content_start);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001473
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001474 ExecutionContext exe_ctx(GetExecutionContext());
1475 Target *target = exe_ctx.GetTargetPtr();
1476
1477 // Get a dummy target to allow for calculator mode while processing
1478 // backticks. This also helps break the infinite loop caused when target is
1479 // null.
1480 if (!target)
1481 target = m_debugger.GetDummyTarget();
1482
1483 if (!target)
1484 continue;
1485
1486 ValueObjectSP expr_result_valobj_sp;
1487
1488 EvaluateExpressionOptions options;
1489 options.SetCoerceToId(false);
1490 options.SetUnwindOnError(true);
1491 options.SetIgnoreBreakpoints(true);
1492 options.SetKeepInMemory(false);
1493 options.SetTryAllThreads(true);
1494 options.SetTimeout(llvm::None);
1495
1496 ExpressionResults expr_result =
1497 target->EvaluateExpression(expr_str.c_str(), exe_ctx.GetFramePtr(),
1498 expr_result_valobj_sp, options);
1499
1500 if (expr_result == eExpressionCompleted) {
1501 Scalar scalar;
1502 if (expr_result_valobj_sp)
1503 expr_result_valobj_sp =
1504 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1505 expr_result_valobj_sp->GetDynamicValueType(), true);
1506 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1507 command.erase(start_backtick, end_backtick - start_backtick + 1);
1508 StreamString value_strm;
1509 const bool show_type = false;
1510 scalar.GetValue(&value_strm, show_type);
1511 size_t value_string_size = value_strm.GetSize();
1512 if (value_string_size) {
1513 command.insert(start_backtick, value_strm.GetString());
1514 pos = start_backtick + value_string_size;
1515 continue;
1516 } else {
1517 error.SetErrorStringWithFormat("expression value didn't result "
1518 "in a scalar value for the "
1519 "expression '%s'",
1520 expr_str.c_str());
1521 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001522 }
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001523 } else {
1524 error.SetErrorStringWithFormat("expression value didn't result "
1525 "in a scalar value for the "
1526 "expression '%s'",
1527 expr_str.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001528 break;
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001529 }
1530
1531 continue;
1532 }
1533
1534 if (expr_result_valobj_sp)
1535 error = expr_result_valobj_sp->GetError();
1536
1537 if (error.Success()) {
1538 switch (expr_result) {
1539 case eExpressionSetupError:
1540 error.SetErrorStringWithFormat(
1541 "expression setup error for the expression '%s'", expr_str.c_str());
1542 break;
1543 case eExpressionParseError:
1544 error.SetErrorStringWithFormat(
1545 "expression parse error for the expression '%s'", expr_str.c_str());
1546 break;
1547 case eExpressionResultUnavailable:
1548 error.SetErrorStringWithFormat(
1549 "expression error fetching result for the expression '%s'",
1550 expr_str.c_str());
1551 break;
1552 case eExpressionCompleted:
1553 break;
1554 case eExpressionDiscarded:
1555 error.SetErrorStringWithFormat(
1556 "expression discarded for the expression '%s'", expr_str.c_str());
1557 break;
1558 case eExpressionInterrupted:
1559 error.SetErrorStringWithFormat(
1560 "expression interrupted for the expression '%s'", expr_str.c_str());
1561 break;
1562 case eExpressionHitBreakpoint:
1563 error.SetErrorStringWithFormat(
1564 "expression hit breakpoint for the expression '%s'",
1565 expr_str.c_str());
1566 break;
1567 case eExpressionTimedOut:
1568 error.SetErrorStringWithFormat(
1569 "expression timed out for the expression '%s'", expr_str.c_str());
1570 break;
1571 case eExpressionStoppedForDebug:
1572 error.SetErrorStringWithFormat("expression stop at entry point "
1573 "for debugging for the "
1574 "expression '%s'",
1575 expr_str.c_str());
1576 break;
1577 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001578 }
1579 }
1580 return error;
1581}
1582
1583bool CommandInterpreter::HandleCommand(const char *command_line,
1584 LazyBool lazy_add_to_history,
1585 CommandReturnObject &result,
1586 ExecutionContext *override_context,
1587 bool repeat_on_empty_command,
1588 bool no_context_switching)
1589
1590{
1591
1592 std::string command_string(command_line);
1593 std::string original_command_string(command_line);
1594
1595 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
Jim Ingham8f7db522016-12-15 00:30:30 +00001596 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
Sean Callanan237c3ed2016-12-14 21:31:31 +00001597 command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001598
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001599 LLDB_LOGF(log, "Processing command: %s", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001600
Pavel Labathf9d16472017-05-15 13:02:37 +00001601 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1602 Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001603
1604 if (!no_context_switching)
1605 UpdateExecutionContext(override_context);
1606
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001607 if (WasInterrupted()) {
1608 result.AppendError("interrupted");
1609 result.SetStatus(eReturnStatusFailed);
1610 return false;
1611 }
1612
Kate Stoneb9c1b512016-09-06 20:57:50 +00001613 bool add_to_history;
1614 if (lazy_add_to_history == eLazyBoolCalculate)
1615 add_to_history = (m_command_source_depth == 0);
1616 else
1617 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1618
1619 bool empty_command = false;
1620 bool comment_command = false;
1621 if (command_string.empty())
1622 empty_command = true;
1623 else {
1624 const char *k_space_characters = "\t\n\v\f\r ";
1625
1626 size_t non_space = command_string.find_first_not_of(k_space_characters);
Adrian Prantl05097242018-04-30 16:49:04 +00001627 // Check for empty line or comment line (lines whose first non-space
1628 // character is the comment character for this interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001629 if (non_space == std::string::npos)
1630 empty_command = true;
1631 else if (command_string[non_space] == m_comment_char)
1632 comment_command = true;
1633 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001634 llvm::StringRef search_str(command_string);
1635 search_str = search_str.drop_front(non_space);
1636 if (auto hist_str = m_command_history.FindString(search_str)) {
1637 add_to_history = false;
1638 command_string = *hist_str;
1639 original_command_string = *hist_str;
1640 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001641 result.AppendErrorWithFormat("Could not find entry: %s in history",
1642 command_string.c_str());
1643 result.SetStatus(eReturnStatusFailed);
1644 return false;
1645 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001646 }
1647 }
1648
1649 if (empty_command) {
1650 if (repeat_on_empty_command) {
1651 if (m_command_history.IsEmpty()) {
1652 result.AppendError("empty command");
1653 result.SetStatus(eReturnStatusFailed);
1654 return false;
1655 } else {
1656 command_line = m_repeat_command.c_str();
1657 command_string = command_line;
1658 original_command_string = command_line;
1659 if (m_repeat_command.empty()) {
1660 result.AppendErrorWithFormat("No auto repeat.\n");
1661 result.SetStatus(eReturnStatusFailed);
1662 return false;
1663 }
1664 }
1665 add_to_history = false;
1666 } else {
1667 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1668 return true;
1669 }
1670 } else if (comment_command) {
1671 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1672 return true;
1673 }
1674
Zachary Turner97206d52017-05-12 04:51:55 +00001675 Status error(PreprocessCommand(command_string));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001676
1677 if (error.Fail()) {
1678 result.AppendError(error.AsCString());
1679 result.SetStatus(eReturnStatusFailed);
1680 return false;
1681 }
1682
1683 // Phase 1.
1684
1685 // Before we do ANY kind of argument processing, we need to figure out what
1686 // the real/final command object is for the specified command. This gets
1687 // complicated by the fact that the user could have specified an alias, and,
1688 // in translating the alias, there may also be command options and/or even
1689 // data (including raw text strings) that need to be found and inserted into
1690 // the command line as part of the translation. So this first step is plain
1691 // look-up and replacement, resulting in:
1692 // 1. the command object whose Execute method will actually be called
1693 // 2. a revised command string, with all substitutions and replacements
1694 // taken care of
1695 // From 1 above, we can determine whether the Execute function wants raw
1696 // input or not.
1697
1698 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1699
1700 // Although the user may have abbreviated the command, the command_string now
Adrian Prantl05097242018-04-30 16:49:04 +00001701 // has the command expanded to the full name. For example, if the input was
1702 // "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001703 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001704 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001705 LLDB_LOGF(log, "HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
1706 LLDB_LOGF(log, "HandleCommand, (revised) command_string: '%s'",
1707 command_string.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001708 const bool wants_raw_input =
Konrad Kleine248a1302019-05-23 11:14:47 +00001709 (cmd_obj != nullptr) ? cmd_obj->WantsRawCommandString() : false;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001710 LLDB_LOGF(log, "HandleCommand, wants_raw_input:'%s'",
1711 wants_raw_input ? "True" : "False");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001712 }
1713
1714 // Phase 2.
1715 // Take care of things like setting up the history command & calling the
Adrian Prantl05097242018-04-30 16:49:04 +00001716 // appropriate Execute method on the CommandObject, with the appropriate
1717 // arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001718
1719 if (cmd_obj != nullptr) {
1720 if (add_to_history) {
1721 Args command_args(command_string);
1722 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1723 if (repeat_command != nullptr)
1724 m_repeat_command.assign(repeat_command);
1725 else
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001726 m_repeat_command.assign(original_command_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001727
1728 m_command_history.AppendString(original_command_string);
1729 }
1730
1731 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001732 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001733 if (actual_cmd_name_len < command_string.length())
1734 remainder = command_string.substr(actual_cmd_name_len);
1735
1736 // Remove any initial spaces
1737 size_t pos = remainder.find_first_not_of(k_white_space);
1738 if (pos != 0 && pos != std::string::npos)
1739 remainder.erase(0, pos);
1740
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001741 LLDB_LOGF(
1742 log, "HandleCommand, command line after removing command name(s): '%s'",
1743 remainder.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001744
1745 cmd_obj->Execute(remainder.c_str(), result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001746 }
1747
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001748 LLDB_LOGF(log, "HandleCommand, command %s",
1749 (result.Succeeded() ? "succeeded" : "did not succeed"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001750
1751 return result.Succeeded();
1752}
1753
Raphael Isemannae34ed22019-08-22 07:41:23 +00001754void CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001755 bool look_for_subcommand = false;
1756
1757 // For any of the command completions a unique match will be a complete word.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001758
Raphael Isemannef06dd42019-09-24 07:22:44 +00001759 if (request.GetParsedLine().GetArgumentCount() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001760 // We got nothing on the command line, so return the list of commands
1761 bool include_aliases = true;
Raphael Isemann7f888292018-09-13 21:26:00 +00001762 StringList new_matches, descriptions;
Raphael Isemannae34ed22019-08-22 07:41:23 +00001763 GetCommandNamesMatchingPartialString("", include_aliases, new_matches,
1764 descriptions);
Raphael Isemann7f888292018-09-13 21:26:00 +00001765 request.AddCompletions(new_matches, descriptions);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001766 } else if (request.GetCursorIndex() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001767 // The cursor is in the first argument, so just do a lookup in the
1768 // dictionary.
Raphael Isemann7f888292018-09-13 21:26:00 +00001769 StringList new_matches, new_descriptions;
1770 CommandObject *cmd_obj =
1771 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0),
1772 &new_matches, &new_descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001773
Raphael Isemannae34ed22019-08-22 07:41:23 +00001774 if (new_matches.GetSize() && cmd_obj && cmd_obj->IsMultiwordObject() &&
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001775 new_matches.GetStringAtIndex(0) != nullptr &&
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001776 strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001777 new_matches.GetStringAtIndex(0)) == 0) {
Raphael Isemannae34ed22019-08-22 07:41:23 +00001778 if (request.GetParsedLine().GetArgumentCount() != 1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001779 look_for_subcommand = true;
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001780 new_matches.DeleteStringAtIndex(0);
Raphael Isemann7f888292018-09-13 21:26:00 +00001781 new_descriptions.DeleteStringAtIndex(0);
Raphael Isemann823fd952019-09-25 12:40:01 +00001782 request.AppendEmptyArgument();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001783 }
1784 }
Raphael Isemann7f888292018-09-13 21:26:00 +00001785 request.AddCompletions(new_matches, new_descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001786 }
1787
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001788 if (request.GetCursorIndex() > 0 || look_for_subcommand) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001789 // We are completing further on into a commands arguments, so find the
Adrian Prantl05097242018-04-30 16:49:04 +00001790 // command and tell it to complete the command. First see if there is a
1791 // matching initial command:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001792 CommandObject *command_object =
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001793 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
Raphael Isemannae34ed22019-08-22 07:41:23 +00001794 if (command_object) {
Raphael Isemannf8e733f2019-09-23 08:16:19 +00001795 request.ShiftArguments();
Raphael Isemannae34ed22019-08-22 07:41:23 +00001796 command_object->HandleCompletion(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001797 }
1798 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001799}
1800
Raphael Isemannae34ed22019-08-22 07:41:23 +00001801void CommandInterpreter::HandleCompletion(CompletionRequest &request) {
1802
Kate Stoneb9c1b512016-09-06 20:57:50 +00001803 // Don't complete comments, and if the line we are completing is just the
Adrian Prantl05097242018-04-30 16:49:04 +00001804 // history repeat character, substitute the appropriate history line.
Raphael Isemannae34ed22019-08-22 07:41:23 +00001805 llvm::StringRef first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
Raphael Isemann2fc20f62019-08-15 13:14:10 +00001806
Raphael Isemannae34ed22019-08-22 07:41:23 +00001807 if (!first_arg.empty()) {
1808 if (first_arg.front() == m_comment_char)
1809 return;
1810 if (first_arg.front() == CommandHistory::g_repeat_char) {
1811 if (auto hist_str = m_command_history.FindString(first_arg))
1812 request.AddCompletion(*hist_str, "Previous command history event",
1813 CompletionMode::RewriteLine);
1814 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001815 }
1816 }
1817
Raphael Isemannae34ed22019-08-22 07:41:23 +00001818 HandleCompletionMatches(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001819}
1820
1821CommandInterpreter::~CommandInterpreter() {}
1822
Zachary Turner514d8cd2016-09-23 18:06:53 +00001823void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001824 EventSP prompt_change_event_sp(
1825 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1826 ;
1827 BroadcastEvent(prompt_change_event_sp);
1828 if (m_command_io_handler_sp)
1829 m_command_io_handler_sp->SetPrompt(new_prompt);
1830}
1831
Zachary Turner7a120c82016-11-13 03:05:58 +00001832bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001833 // Check AutoConfirm first:
1834 if (m_debugger.GetAutoConfirm())
1835 return default_answer;
1836
1837 IOHandlerConfirm *confirm =
1838 new IOHandlerConfirm(m_debugger, message, default_answer);
1839 IOHandlerSP io_handler_sp(confirm);
1840 m_debugger.RunIOHandler(io_handler_sp);
1841 return confirm->GetResponse();
1842}
1843
Zachary Turnera483f572016-10-05 21:14:49 +00001844const CommandAlias *
1845CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001846 OptionArgVectorSP ret_val;
1847
Zachary Turnera483f572016-10-05 21:14:49 +00001848 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001849 if (pos != m_alias_dict.end())
1850 return (CommandAlias *)pos->second.get();
1851
1852 return nullptr;
1853}
1854
Zachary Turnera4496982016-10-05 21:14:38 +00001855bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001856
Zachary Turnera4496982016-10-05 21:14:38 +00001857bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001858
Zachary Turnera4496982016-10-05 21:14:38 +00001859bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001860
Zachary Turnera4496982016-10-05 21:14:38 +00001861bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001862
1863void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1864 const char *alias_name,
1865 Args &cmd_args,
1866 std::string &raw_input_string,
1867 CommandReturnObject &result) {
1868 OptionArgVectorSP option_arg_vector_sp =
1869 GetAlias(alias_name)->GetOptionArguments();
1870
1871 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1872
1873 // Make sure that the alias name is the 0th element in cmd_args
1874 std::string alias_name_str = alias_name;
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001875 if (alias_name_str != cmd_args.GetArgumentAtIndex(0))
Zachary Turner5c725f32016-09-19 21:56:59 +00001876 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001877
1878 Args new_args(alias_cmd_obj->GetCommandName());
1879 if (new_args.GetArgumentCount() == 2)
1880 new_args.Shift();
1881
1882 if (option_arg_vector_sp.get()) {
1883 if (wants_raw_input) {
1884 // We have a command that both has command options and takes raw input.
Adrian Prantl05097242018-04-30 16:49:04 +00001885 // Make *sure* it has a " -- " in the right place in the
1886 // raw_input_string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001887 size_t pos = raw_input_string.find(" -- ");
1888 if (pos == std::string::npos) {
1889 // None found; assume it goes at the beginning of the raw input string
1890 raw_input_string.insert(0, " -- ");
1891 }
1892 }
1893
1894 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1895 const size_t old_size = cmd_args.GetArgumentCount();
1896 std::vector<bool> used(old_size + 1, false);
1897
1898 used[0] = true;
1899
Zachary Turner5c28c662016-10-03 23:20:36 +00001900 int value_type;
1901 std::string option;
1902 std::string value;
1903 for (const auto &option_entry : *option_arg_vector) {
1904 std::tie(option, value_type, value) = option_entry;
1905 if (option == "<argument>") {
1906 if (!wants_raw_input || (value != "--")) {
1907 // Since we inserted this above, make sure we don't insert it twice
1908 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001909 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001910 continue;
1911 }
1912
1913 if (value_type != OptionParser::eOptionalArgument)
1914 new_args.AppendArgument(option);
1915
1916 if (value == "<no-argument>")
1917 continue;
1918
1919 int index = GetOptionArgumentPosition(value.c_str());
1920 if (index == 0) {
1921 // value was NOT a positional argument; must be a real value
1922 if (value_type != OptionParser::eOptionalArgument)
1923 new_args.AppendArgument(value);
1924 else {
1925 char buffer[255];
1926 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1927 value.c_str());
1928 new_args.AppendArgument(llvm::StringRef(buffer));
1929 }
1930
1931 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1932 result.AppendErrorWithFormat("Not enough arguments provided; you "
1933 "need at least %d arguments to use "
1934 "this alias.\n",
1935 index);
1936 result.SetStatus(eReturnStatusFailed);
1937 return;
1938 } else {
1939 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1940 size_t strpos =
1941 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1942 if (strpos != std::string::npos) {
1943 raw_input_string = raw_input_string.erase(
1944 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1945 }
1946
1947 if (value_type != OptionParser::eOptionalArgument)
1948 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
1949 else {
1950 char buffer[255];
1951 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1952 cmd_args.GetArgumentAtIndex(index));
1953 new_args.AppendArgument(buffer);
1954 }
1955 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001956 }
1957 }
1958
Zachary Turner97d2c402016-10-05 23:40:23 +00001959 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00001960 if (!used[entry.index()] && !wants_raw_input)
Raphael Isemann0d9a2012019-09-13 11:26:48 +00001961 new_args.AppendArgument(entry.value().ref());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001962 }
1963
1964 cmd_args.Clear();
1965 cmd_args.SetArguments(new_args.GetArgumentCount(),
1966 new_args.GetConstArgumentVector());
1967 } else {
1968 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1969 // This alias was not created with any options; nothing further needs to be
Adrian Prantl05097242018-04-30 16:49:04 +00001970 // done, unless it is a command that wants raw input, in which case we need
1971 // to clear the rest of the data from cmd_args, since its in the raw input
1972 // string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001973 if (wants_raw_input) {
1974 cmd_args.Clear();
1975 cmd_args.SetArguments(new_args.GetArgumentCount(),
1976 new_args.GetConstArgumentVector());
1977 }
1978 return;
1979 }
1980
1981 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1982 return;
1983}
1984
1985int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
1986 int position = 0; // Any string that isn't an argument position, i.e. '%'
1987 // followed by an integer, gets a position
1988 // of zero.
1989
1990 const char *cptr = in_string;
1991
1992 // Does it start with '%'
1993 if (cptr[0] == '%') {
1994 ++cptr;
1995
1996 // Is the rest of it entirely digits?
1997 if (isdigit(cptr[0])) {
1998 const char *start = cptr;
1999 while (isdigit(cptr[0]))
2000 ++cptr;
2001
Adrian Prantl05097242018-04-30 16:49:04 +00002002 // We've gotten to the end of the digits; are we at the end of the
2003 // string?
Kate Stoneb9c1b512016-09-06 20:57:50 +00002004 if (cptr[0] == '\0')
2005 position = atoi(start);
2006 }
2007 }
2008
2009 return position;
2010}
2011
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002012static void GetHomeInitFile(llvm::SmallVectorImpl<char> &init_file,
2013 llvm::StringRef suffix = {}) {
2014 std::string init_file_name = ".lldbinit";
2015 if (!suffix.empty()) {
2016 init_file_name.append("-");
2017 init_file_name.append(suffix.str());
2018 }
2019
2020 llvm::sys::path::home_directory(init_file);
2021 llvm::sys::path::append(init_file, init_file_name);
2022
2023 FileSystem::Instance().Resolve(init_file);
2024}
2025
2026static void GetCwdInitFile(llvm::SmallVectorImpl<char> &init_file) {
2027 llvm::StringRef s = ".lldbinit";
2028 init_file.assign(s.begin(), s.end());
2029 FileSystem::Instance().Resolve(init_file);
2030}
2031
2032static LoadCWDlldbinitFile ShouldLoadCwdInitFile() {
2033 lldb::TargetPropertiesSP properties = Target::GetGlobalProperties();
2034 if (!properties)
2035 return eLoadCWDlldbinitFalse;
2036 return properties->GetLoadCWDlldbinitFile();
2037}
2038
2039void CommandInterpreter::SourceInitFile(FileSpec file,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002040 CommandReturnObject &result) {
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002041 assert(!m_skip_lldbinit_files);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002042
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002043 if (!FileSystem::Instance().Exists(file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002044 result.SetStatus(eReturnStatusSuccessFinishNoResult);
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002045 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002046 }
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002047
2048 // Use HandleCommand to 'source' the given file; this will do the actual
2049 // broadcasting of the commands back to any appropriate listener (see
2050 // CommandObjectSource::Execute for more details).
2051 const bool saved_batch = SetBatchCommandMode(true);
2052 ExecutionContext *ctx = nullptr;
2053 CommandInterpreterRunOptions options;
2054 options.SetSilent(true);
2055 options.SetPrintErrors(true);
2056 options.SetStopOnError(false);
2057 options.SetStopOnContinue(true);
2058 HandleCommandsFromFile(file, ctx, options, result);
2059 SetBatchCommandMode(saved_batch);
2060}
2061
2062void CommandInterpreter::SourceInitFileCwd(CommandReturnObject &result) {
2063 if (m_skip_lldbinit_files) {
2064 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2065 return;
2066 }
2067
2068 llvm::SmallString<128> init_file;
2069 GetCwdInitFile(init_file);
2070 if (!FileSystem::Instance().Exists(init_file)) {
2071 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2072 return;
2073 }
2074
2075 LoadCWDlldbinitFile should_load = ShouldLoadCwdInitFile();
2076
2077 switch (should_load) {
2078 case eLoadCWDlldbinitFalse:
2079 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2080 break;
2081 case eLoadCWDlldbinitTrue:
2082 SourceInitFile(FileSpec(init_file.str()), result);
2083 break;
2084 case eLoadCWDlldbinitWarn: {
2085 llvm::SmallString<128> home_init_file;
2086 GetHomeInitFile(home_init_file);
2087 if (llvm::sys::path::parent_path(init_file) ==
2088 llvm::sys::path::parent_path(home_init_file)) {
2089 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2090 } else {
2091 result.AppendErrorWithFormat(InitFileWarning);
2092 result.SetStatus(eReturnStatusFailed);
2093 }
2094 }
2095 }
2096}
2097
2098/// We will first see if there is an application specific ".lldbinit" file
2099/// whose name is "~/.lldbinit" followed by a "-" and the name of the program.
2100/// If this file doesn't exist, we fall back to just the "~/.lldbinit" file.
2101void CommandInterpreter::SourceInitFileHome(CommandReturnObject &result) {
2102 if (m_skip_lldbinit_files) {
2103 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2104 return;
2105 }
2106
2107 llvm::SmallString<128> init_file;
2108 GetHomeInitFile(init_file);
2109
2110 if (!m_skip_app_init_files) {
2111 llvm::StringRef program_name =
2112 HostInfo::GetProgramFileSpec().GetFilename().GetStringRef();
2113 llvm::SmallString<128> program_init_file;
2114 GetHomeInitFile(program_init_file, program_name);
2115 if (FileSystem::Instance().Exists(program_init_file))
2116 init_file = program_init_file;
2117 }
2118
2119 SourceInitFile(FileSpec(init_file.str()), result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002120}
2121
2122const char *CommandInterpreter::GetCommandPrefix() {
2123 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
Konrad Kleine248a1302019-05-23 11:14:47 +00002124 return prefix == nullptr ? "" : prefix;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002125}
2126
2127PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2128 PlatformSP platform_sp;
2129 if (prefer_target_platform) {
2130 ExecutionContext exe_ctx(GetExecutionContext());
2131 Target *target = exe_ctx.GetTargetPtr();
2132 if (target)
2133 platform_sp = target->GetPlatform();
2134 }
2135
2136 if (!platform_sp)
2137 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2138 return platform_sp;
2139}
2140
2141void CommandInterpreter::HandleCommands(const StringList &commands,
2142 ExecutionContext *override_context,
2143 CommandInterpreterRunOptions &options,
2144 CommandReturnObject &result) {
2145 size_t num_lines = commands.GetSize();
2146
2147 // If we are going to continue past a "continue" then we need to run the
Adrian Prantl05097242018-04-30 16:49:04 +00002148 // commands synchronously. Make sure you reset this value anywhere you return
2149 // from the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002150
2151 bool old_async_execution = m_debugger.GetAsyncExecution();
2152
2153 // If we've been given an execution context, set it at the start, but don't
Adrian Prantl05097242018-04-30 16:49:04 +00002154 // keep resetting it or we will cause series of commands that change the
2155 // context, then do an operation that relies on that context to fail.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002156
2157 if (override_context != nullptr)
2158 UpdateExecutionContext(override_context);
2159
2160 if (!options.GetStopOnContinue()) {
2161 m_debugger.SetAsyncExecution(false);
2162 }
2163
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002164 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002165 const char *cmd = commands.GetStringAtIndex(idx);
2166 if (cmd[0] == '\0')
2167 continue;
2168
2169 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002170 // TODO: Add Stream support.
2171 result.AppendMessageWithFormat("%s %s\n",
2172 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002173 }
2174
2175 CommandReturnObject tmp_result;
2176 // If override_context is not NULL, pass no_context_switching = true for
2177 // HandleCommand() since we updated our context already.
2178
2179 // We might call into a regex or alias command, in which case the
Adrian Prantl05097242018-04-30 16:49:04 +00002180 // add_to_history will get lost. This m_command_source_depth dingus is the
2181 // way we turn off adding to the history in that case, so set it up here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002182 if (!options.GetAddToHistory())
2183 m_command_source_depth++;
2184 bool success =
2185 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2186 nullptr, /* override_context */
2187 true, /* repeat_on_empty_command */
2188 override_context != nullptr /* no_context_switching */);
2189 if (!options.GetAddToHistory())
2190 m_command_source_depth--;
2191
2192 if (options.GetPrintResults()) {
2193 if (tmp_result.Succeeded())
Zachary Turner03c9f362016-11-14 23:23:31 +00002194 result.AppendMessage(tmp_result.GetOutputData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002195 }
2196
2197 if (!success || !tmp_result.Succeeded()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002198 llvm::StringRef error_msg = tmp_result.GetErrorData();
2199 if (error_msg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002200 error_msg = "<unknown error>.\n";
2201 if (options.GetStopOnError()) {
2202 result.AppendErrorWithFormat(
2203 "Aborting reading of commands after command #%" PRIu64
2204 ": '%s' failed with %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00002205 (uint64_t)idx, cmd, error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002206 result.SetStatus(eReturnStatusFailed);
2207 m_debugger.SetAsyncExecution(old_async_execution);
2208 return;
2209 } else if (options.GetPrintResults()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002210 result.AppendMessageWithFormat(
2211 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2212 error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002213 }
2214 }
2215
2216 if (result.GetImmediateOutputStream())
2217 result.GetImmediateOutputStream()->Flush();
2218
2219 if (result.GetImmediateErrorStream())
2220 result.GetImmediateErrorStream()->Flush();
2221
Adrian Prantl05097242018-04-30 16:49:04 +00002222 // N.B. Can't depend on DidChangeProcessState, because the state coming
2223 // into the command execution could be running (for instance in Breakpoint
2224 // Commands. So we check the return value to see if it is has running in
2225 // it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002226 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2227 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2228 if (options.GetStopOnContinue()) {
2229 // If we caused the target to proceed, and we're going to stop in that
Adrian Prantl05097242018-04-30 16:49:04 +00002230 // case, set the status in our real result before returning. This is
2231 // an error if the continue was not the last command in the set of
2232 // commands to be run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002233 if (idx != num_lines - 1)
2234 result.AppendErrorWithFormat(
2235 "Aborting reading of commands after command #%" PRIu64
2236 ": '%s' continued the target.\n",
2237 (uint64_t)idx + 1, cmd);
2238 else
2239 result.AppendMessageWithFormat("Command #%" PRIu64
2240 " '%s' continued the target.\n",
2241 (uint64_t)idx + 1, cmd);
2242
2243 result.SetStatus(tmp_result.GetStatus());
2244 m_debugger.SetAsyncExecution(old_async_execution);
2245
2246 return;
2247 }
2248 }
2249
2250 // Also check for "stop on crash here:
2251 bool should_stop = false;
2252 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2253 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2254 if (target_sp) {
2255 ProcessSP process_sp(target_sp->GetProcessSP());
2256 if (process_sp) {
2257 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2258 StopReason reason = thread_sp->GetStopReason();
2259 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2260 reason == eStopReasonInstrumentation) {
2261 should_stop = true;
2262 break;
2263 }
2264 }
2265 }
2266 }
2267 if (should_stop) {
2268 if (idx != num_lines - 1)
2269 result.AppendErrorWithFormat(
2270 "Aborting reading of commands after command #%" PRIu64
2271 ": '%s' stopped with a signal or exception.\n",
2272 (uint64_t)idx + 1, cmd);
2273 else
2274 result.AppendMessageWithFormat(
2275 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2276 (uint64_t)idx + 1, cmd);
2277
2278 result.SetStatus(tmp_result.GetStatus());
2279 m_debugger.SetAsyncExecution(old_async_execution);
2280
2281 return;
2282 }
2283 }
2284 }
2285
2286 result.SetStatus(eReturnStatusSuccessFinishResult);
2287 m_debugger.SetAsyncExecution(old_async_execution);
2288
2289 return;
2290}
2291
2292// Make flags that we can pass into the IOHandler so our delegates can do the
2293// right thing
2294enum {
2295 eHandleCommandFlagStopOnContinue = (1u << 0),
2296 eHandleCommandFlagStopOnError = (1u << 1),
2297 eHandleCommandFlagEchoCommand = (1u << 2),
Stefan Granitzc678ed72018-10-05 16:49:47 +00002298 eHandleCommandFlagEchoCommentCommand = (1u << 3),
2299 eHandleCommandFlagPrintResult = (1u << 4),
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002300 eHandleCommandFlagPrintErrors = (1u << 5),
2301 eHandleCommandFlagStopOnCrash = (1u << 6)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002302};
2303
2304void CommandInterpreter::HandleCommandsFromFile(
2305 FileSpec &cmd_file, ExecutionContext *context,
2306 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002307 if (!FileSystem::Instance().Exists(cmd_file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002308 result.AppendErrorWithFormat(
2309 "Error reading commands from file %s - file not found.\n",
2310 cmd_file.GetFilename().AsCString("<Unknown>"));
2311 result.SetStatus(eReturnStatusFailed);
2312 return;
2313 }
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002314
2315 StreamFileSP input_file_sp(new StreamFile());
2316 std::string cmd_file_path = cmd_file.GetPath();
2317 Status error = FileSystem::Instance().Open(input_file_sp->GetFile(), cmd_file,
2318 File::eOpenOptionRead);
2319
2320 if (error.Fail()) {
2321 result.AppendErrorWithFormat(
2322 "error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(),
2323 error.AsCString());
2324 result.SetStatus(eReturnStatusFailed);
2325 return;
2326 }
2327
2328 Debugger &debugger = GetDebugger();
2329
2330 uint32_t flags = 0;
2331
2332 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2333 if (m_command_source_flags.empty()) {
2334 // Stop on continue by default
2335 flags |= eHandleCommandFlagStopOnContinue;
2336 } else if (m_command_source_flags.back() &
2337 eHandleCommandFlagStopOnContinue) {
2338 flags |= eHandleCommandFlagStopOnContinue;
2339 }
2340 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2341 flags |= eHandleCommandFlagStopOnContinue;
2342 }
2343
2344 if (options.m_stop_on_error == eLazyBoolCalculate) {
2345 if (m_command_source_flags.empty()) {
2346 if (GetStopCmdSourceOnError())
2347 flags |= eHandleCommandFlagStopOnError;
2348 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) {
2349 flags |= eHandleCommandFlagStopOnError;
2350 }
2351 } else if (options.m_stop_on_error == eLazyBoolYes) {
2352 flags |= eHandleCommandFlagStopOnError;
2353 }
2354
2355 // stop-on-crash can only be set, if it is present in all levels of
2356 // pushed flag sets.
2357 if (options.GetStopOnCrash()) {
2358 if (m_command_source_flags.empty()) {
2359 flags |= eHandleCommandFlagStopOnCrash;
2360 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) {
2361 flags |= eHandleCommandFlagStopOnCrash;
2362 }
2363 }
2364
2365 if (options.m_echo_commands == eLazyBoolCalculate) {
2366 if (m_command_source_flags.empty()) {
2367 // Echo command by default
2368 flags |= eHandleCommandFlagEchoCommand;
2369 } else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) {
2370 flags |= eHandleCommandFlagEchoCommand;
2371 }
2372 } else if (options.m_echo_commands == eLazyBoolYes) {
2373 flags |= eHandleCommandFlagEchoCommand;
2374 }
2375
2376 // We will only ever ask for this flag, if we echo commands in general.
2377 if (options.m_echo_comment_commands == eLazyBoolCalculate) {
2378 if (m_command_source_flags.empty()) {
2379 // Echo comments by default
2380 flags |= eHandleCommandFlagEchoCommentCommand;
2381 } else if (m_command_source_flags.back() &
2382 eHandleCommandFlagEchoCommentCommand) {
2383 flags |= eHandleCommandFlagEchoCommentCommand;
2384 }
2385 } else if (options.m_echo_comment_commands == eLazyBoolYes) {
2386 flags |= eHandleCommandFlagEchoCommentCommand;
2387 }
2388
2389 if (options.m_print_results == eLazyBoolCalculate) {
2390 if (m_command_source_flags.empty()) {
2391 // Print output by default
2392 flags |= eHandleCommandFlagPrintResult;
2393 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) {
2394 flags |= eHandleCommandFlagPrintResult;
2395 }
2396 } else if (options.m_print_results == eLazyBoolYes) {
2397 flags |= eHandleCommandFlagPrintResult;
2398 }
2399
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002400 if (options.m_print_errors == eLazyBoolCalculate) {
2401 if (m_command_source_flags.empty()) {
2402 // Print output by default
2403 flags |= eHandleCommandFlagPrintErrors;
2404 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintErrors) {
2405 flags |= eHandleCommandFlagPrintErrors;
2406 }
2407 } else if (options.m_print_errors == eLazyBoolYes) {
2408 flags |= eHandleCommandFlagPrintErrors;
2409 }
2410
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002411 if (flags & eHandleCommandFlagPrintResult) {
2412 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2413 cmd_file_path.c_str());
2414 }
2415
2416 // Used for inheriting the right settings when "command source" might
2417 // have nested "command source" commands
2418 lldb::StreamFileSP empty_stream_sp;
2419 m_command_source_flags.push_back(flags);
2420 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2421 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2422 empty_stream_sp, // Pass in an empty stream so we inherit the top
2423 // input reader output stream
2424 empty_stream_sp, // Pass in an empty stream so we inherit the top
2425 // input reader error stream
2426 flags,
2427 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2428 // or written
2429 debugger.GetPrompt(), llvm::StringRef(),
2430 false, // Not multi-line
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002431 debugger.GetUseColor(), 0, *this, nullptr));
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002432 const bool old_async_execution = debugger.GetAsyncExecution();
2433
2434 // Set synchronous execution if we are not stopping on continue
2435 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2436 debugger.SetAsyncExecution(false);
2437
2438 m_command_source_depth++;
2439
2440 debugger.RunIOHandler(io_handler_sp);
2441 if (!m_command_source_flags.empty())
2442 m_command_source_flags.pop_back();
2443 m_command_source_depth--;
2444 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2445 debugger.SetAsyncExecution(old_async_execution);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002446}
2447
Kate Stoneb9c1b512016-09-06 20:57:50 +00002448bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2449
2450void CommandInterpreter::SetSynchronous(bool value) {
Jonas Devlieghere70df51b2019-07-31 23:34:45 +00002451 // Asynchronous mode is not supported during reproducer replay.
2452 if (repro::Reproducer::Instance().GetLoader())
2453 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002454 m_synchronous_execution = value;
2455}
2456
2457void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002458 llvm::StringRef prefix,
2459 llvm::StringRef help_text) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002460 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002461
Zachary Turner0ac5f982016-11-08 04:12:42 +00002462 size_t line_width_max = max_columns - prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002463 if (line_width_max < 16)
Zachary Turner0ac5f982016-11-08 04:12:42 +00002464 line_width_max = help_text.size() + prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002465
Zachary Turner0ac5f982016-11-08 04:12:42 +00002466 strm.IndentMore(prefix.size());
2467 bool prefixed_yet = false;
2468 while (!help_text.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002469 // Prefix the first line, indent subsequent lines to line up
Zachary Turner0ac5f982016-11-08 04:12:42 +00002470 if (!prefixed_yet) {
2471 strm << prefix;
2472 prefixed_yet = true;
2473 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002474 strm.Indent();
Zachary Turner0ac5f982016-11-08 04:12:42 +00002475
2476 // Never print more than the maximum on one line.
2477 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2478
2479 // Always break on an explicit newline.
2480 std::size_t first_newline = this_line.find_first_of("\n");
2481
2482 // Don't break on space/tab unless the text is too long to fit on one line.
2483 std::size_t last_space = llvm::StringRef::npos;
2484 if (this_line.size() != help_text.size())
2485 last_space = this_line.find_last_of(" \t");
2486
2487 // Break at whichever condition triggered first.
2488 this_line = this_line.substr(0, std::min(first_newline, last_space));
2489 strm.PutCString(this_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002490 strm.EOL();
2491
Zachary Turner0ac5f982016-11-08 04:12:42 +00002492 // Remove whitespace / newlines after breaking.
2493 help_text = help_text.drop_front(this_line.size()).ltrim();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002494 }
Zachary Turner0ac5f982016-11-08 04:12:42 +00002495 strm.IndentLess(prefix.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002496}
2497
2498void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002499 llvm::StringRef word_text,
2500 llvm::StringRef separator,
2501 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002502 size_t max_word_len) {
2503 StreamString prefix_stream;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002504 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2505 (int)separator.size(), separator.data());
Zachary Turnerc1564272016-11-16 21:15:24 +00002506 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2507}
2508
Zachary Turner0ac5f982016-11-08 04:12:42 +00002509void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2510 llvm::StringRef separator,
2511 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002512 uint32_t max_word_len) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00002513 int indent_size = max_word_len + separator.size() + 2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002514
2515 strm.IndentMore(indent_size);
2516
2517 StreamString text_strm;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002518 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2519 text_strm << separator << " " << help_text;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002520
2521 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2522
Zachary Turnerc1564272016-11-16 21:15:24 +00002523 llvm::StringRef text = text_strm.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002524
2525 uint32_t chars_left = max_columns;
2526
Davide Italianocf8a8292017-04-14 22:36:08 +00002527 auto nextWordLength = [](llvm::StringRef S) {
Jonas Devliegherec712bac2019-03-28 18:10:14 +00002528 size_t pos = S.find(' ');
Davide Italianocf8a8292017-04-14 22:36:08 +00002529 return pos == llvm::StringRef::npos ? S.size() : pos;
2530 };
2531
Zachary Turnerc1564272016-11-16 21:15:24 +00002532 while (!text.empty()) {
2533 if (text.front() == '\n' ||
Jim Inghama81bd7f2017-07-27 00:18:18 +00002534 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002535 strm.EOL();
2536 strm.Indent();
Zachary Turnerc1564272016-11-16 21:15:24 +00002537 chars_left = max_columns - indent_size;
2538 if (text.front() == '\n')
2539 text = text.drop_front();
2540 else
2541 text = text.ltrim(' ');
Kate Stoneb9c1b512016-09-06 20:57:50 +00002542 } else {
Zachary Turnerc1564272016-11-16 21:15:24 +00002543 strm.PutChar(text.front());
2544 --chars_left;
2545 text = text.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002546 }
2547 }
2548
2549 strm.EOL();
2550 strm.IndentLess(indent_size);
2551}
2552
2553void CommandInterpreter::FindCommandsForApropos(
Zachary Turner067d1db2016-11-16 21:45:04 +00002554 llvm::StringRef search_word, StringList &commands_found,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002555 StringList &commands_help, CommandObject::CommandMap &command_map) {
2556 CommandObject::CommandMap::const_iterator pos;
2557
2558 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
Zachary Turner067d1db2016-11-16 21:45:04 +00002559 llvm::StringRef command_name = pos->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002560 CommandObject *cmd_obj = pos->second.get();
2561
2562 const bool search_short_help = true;
2563 const bool search_long_help = false;
2564 const bool search_syntax = false;
2565 const bool search_options = false;
Zachary Turner067d1db2016-11-16 21:45:04 +00002566 if (command_name.contains_lower(search_word) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002567 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2568 search_long_help, search_syntax,
2569 search_options)) {
2570 commands_found.AppendString(cmd_obj->GetCommandName());
2571 commands_help.AppendString(cmd_obj->GetHelp());
2572 }
2573
2574 if (cmd_obj->IsMultiwordObject()) {
2575 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2576 FindCommandsForApropos(search_word, commands_found, commands_help,
2577 cmd_multiword->GetSubcommandDictionary());
2578 }
2579 }
2580}
2581
Zachary Turner067d1db2016-11-16 21:45:04 +00002582void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002583 StringList &commands_found,
2584 StringList &commands_help,
2585 bool search_builtin_commands,
2586 bool search_user_commands,
2587 bool search_alias_commands) {
2588 CommandObject::CommandMap::const_iterator pos;
2589
2590 if (search_builtin_commands)
2591 FindCommandsForApropos(search_word, commands_found, commands_help,
2592 m_command_dict);
2593
2594 if (search_user_commands)
2595 FindCommandsForApropos(search_word, commands_found, commands_help,
2596 m_user_dict);
2597
2598 if (search_alias_commands)
2599 FindCommandsForApropos(search_word, commands_found, commands_help,
2600 m_alias_dict);
2601}
2602
2603void CommandInterpreter::UpdateExecutionContext(
2604 ExecutionContext *override_context) {
2605 if (override_context != nullptr) {
2606 m_exe_ctx_ref = *override_context;
2607 } else {
2608 const bool adopt_selected = true;
2609 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2610 adopt_selected);
2611 }
2612}
2613
Pavel Labatha9d58432019-07-31 12:06:50 +00002614void CommandInterpreter::GetProcessOutput() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002615 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
Pavel Labatha9d58432019-07-31 12:06:50 +00002616 if (!target_sp)
2617 return;
2618
2619 if (ProcessSP process_sp = target_sp->GetProcessSP())
2620 m_debugger.FlushProcessOutput(*process_sp, /*flush_stdout*/ true,
2621 /*flush_stderr*/ true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002622}
2623
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002624void CommandInterpreter::StartHandlingCommand() {
2625 auto idle_state = CommandHandlingState::eIdle;
2626 if (m_command_state.compare_exchange_strong(
2627 idle_state, CommandHandlingState::eInProgress))
2628 lldbassert(m_iohandler_nesting_level == 0);
2629 else
2630 lldbassert(m_iohandler_nesting_level > 0);
2631 ++m_iohandler_nesting_level;
2632}
2633
2634void CommandInterpreter::FinishHandlingCommand() {
2635 lldbassert(m_iohandler_nesting_level > 0);
2636 if (--m_iohandler_nesting_level == 0) {
2637 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2638 lldbassert(prev_state != CommandHandlingState::eIdle);
2639 }
2640}
2641
2642bool CommandInterpreter::InterruptCommand() {
2643 auto in_progress = CommandHandlingState::eInProgress;
2644 return m_command_state.compare_exchange_strong(
2645 in_progress, CommandHandlingState::eInterrupted);
2646}
2647
2648bool CommandInterpreter::WasInterrupted() const {
2649 bool was_interrupted =
2650 (m_command_state == CommandHandlingState::eInterrupted);
2651 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2652 return was_interrupted;
2653}
2654
2655void CommandInterpreter::PrintCommandOutput(Stream &stream,
2656 llvm::StringRef str) {
2657 // Split the output into lines and poll for interrupt requests
2658 const char *data = str.data();
2659 size_t size = str.size();
2660 while (size > 0 && !WasInterrupted()) {
2661 size_t chunk_size = 0;
2662 for (; chunk_size < size; ++chunk_size) {
2663 lldbassert(data[chunk_size] != '\0');
2664 if (data[chunk_size] == '\n') {
2665 ++chunk_size;
2666 break;
2667 }
2668 }
2669 chunk_size = stream.Write(data, chunk_size);
2670 lldbassert(size >= chunk_size);
2671 data += chunk_size;
2672 size -= chunk_size;
2673 }
2674 if (size > 0) {
2675 stream.Printf("\n... Interrupted.\n");
2676 }
2677}
2678
Stefan Granitzc678ed72018-10-05 16:49:47 +00002679bool CommandInterpreter::EchoCommandNonInteractive(
2680 llvm::StringRef line, const Flags &io_handler_flags) const {
2681 if (!io_handler_flags.Test(eHandleCommandFlagEchoCommand))
2682 return false;
2683
2684 llvm::StringRef command = line.trim();
2685 if (command.empty())
2686 return true;
2687
2688 if (command.front() == m_comment_char)
2689 return io_handler_flags.Test(eHandleCommandFlagEchoCommentCommand);
2690
2691 return true;
2692}
2693
Kate Stoneb9c1b512016-09-06 20:57:50 +00002694void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2695 std::string &line) {
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002696 // If we were interrupted, bail out...
2697 if (WasInterrupted())
2698 return;
2699
Kate Stoneb9c1b512016-09-06 20:57:50 +00002700 const bool is_interactive = io_handler.GetIsInteractive();
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002701 if (!is_interactive) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002702 // When we are not interactive, don't execute blank lines. This will happen
2703 // sourcing a commands file. We don't want blank lines to repeat the
Adrian Prantl05097242018-04-30 16:49:04 +00002704 // previous command and cause any errors to occur (like redefining an
2705 // alias, get an error and stop parsing the commands file).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002706 if (line.empty())
2707 return;
2708
2709 // When using a non-interactive file handle (like when sourcing commands
Adrian Prantl05097242018-04-30 16:49:04 +00002710 // from a file) we need to echo the command out so we don't just see the
2711 // command output and no command...
Stefan Granitzc678ed72018-10-05 16:49:47 +00002712 if (EchoCommandNonInteractive(line, io_handler.GetFlags()))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002713 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2714 line.c_str());
2715 }
2716
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002717 StartHandlingCommand();
2718
Kate Stoneb9c1b512016-09-06 20:57:50 +00002719 lldb_private::CommandReturnObject result;
2720 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2721
2722 // Now emit the command output text from the command we just executed
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002723 if ((result.Succeeded() &&
2724 io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) ||
2725 io_handler.GetFlags().Test(eHandleCommandFlagPrintErrors)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002726 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2727 GetProcessOutput();
2728
2729 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002730 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002731 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002732 }
2733
2734 // Now emit the command error text from the command we just executed
2735 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002736 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002737 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002738 }
2739 }
2740
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002741 FinishHandlingCommand();
2742
Kate Stoneb9c1b512016-09-06 20:57:50 +00002743 switch (result.GetStatus()) {
2744 case eReturnStatusInvalid:
2745 case eReturnStatusSuccessFinishNoResult:
2746 case eReturnStatusSuccessFinishResult:
2747 case eReturnStatusStarted:
2748 break;
2749
2750 case eReturnStatusSuccessContinuingNoResult:
2751 case eReturnStatusSuccessContinuingResult:
2752 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2753 io_handler.SetIsDone(true);
2754 break;
2755
2756 case eReturnStatusFailed:
2757 m_num_errors++;
2758 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2759 io_handler.SetIsDone(true);
2760 break;
2761
2762 case eReturnStatusQuit:
2763 m_quit_requested = true;
2764 io_handler.SetIsDone(true);
2765 break;
2766 }
2767
2768 // Finally, if we're going to stop on crash, check that here:
2769 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2770 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2771 bool should_stop = false;
2772 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2773 if (target_sp) {
2774 ProcessSP process_sp(target_sp->GetProcessSP());
2775 if (process_sp) {
2776 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2777 StopReason reason = thread_sp->GetStopReason();
2778 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2779 reason == eStopReasonInstrumentation) &&
2780 !result.GetAbnormalStopWasExpected()) {
2781 should_stop = true;
2782 break;
2783 }
2784 }
2785 }
2786 }
2787 if (should_stop) {
2788 io_handler.SetIsDone(true);
2789 m_stopped_for_crash = true;
2790 }
2791 }
2792}
2793
2794bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2795 ExecutionContext exe_ctx(GetExecutionContext());
2796 Process *process = exe_ctx.GetProcessPtr();
2797
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002798 if (InterruptCommand())
2799 return true;
2800
Kate Stoneb9c1b512016-09-06 20:57:50 +00002801 if (process) {
2802 StateType state = process->GetState();
2803 if (StateIsRunningState(state)) {
2804 process->Halt();
2805 return true; // Don't do any updating when we are running
2806 }
2807 }
2808
Jonas Devlieghere2b29b432019-04-26 22:43:16 +00002809 ScriptInterpreter *script_interpreter =
2810 m_debugger.GetScriptInterpreter(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002811 if (script_interpreter) {
2812 if (script_interpreter->Interrupt())
2813 return true;
2814 }
2815 return false;
2816}
2817
2818void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2819 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2820 void *baton) {
2821 Debugger &debugger = GetDebugger();
2822 IOHandlerSP io_handler_sp(
2823 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2824 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002825 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2826 llvm::StringRef(), // Continuation prompt
2827 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002828 debugger.GetUseColor(),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002829 0, // Don't show line numbers
2830 delegate, // IOHandlerDelegate
2831 nullptr)); // FileShadowCollector
Kate Stoneb9c1b512016-09-06 20:57:50 +00002832
2833 if (io_handler_sp) {
2834 io_handler_sp->SetUserData(baton);
2835 if (asynchronously)
2836 debugger.PushIOHandler(io_handler_sp);
2837 else
2838 debugger.RunIOHandler(io_handler_sp);
2839 }
2840}
2841
2842void CommandInterpreter::GetPythonCommandsFromIOHandler(
2843 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2844 void *baton) {
2845 Debugger &debugger = GetDebugger();
2846 IOHandlerSP io_handler_sp(
2847 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2848 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002849 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2850 llvm::StringRef(), // Continuation prompt
2851 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002852 debugger.GetUseColor(),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002853 0, // Don't show line numbers
2854 delegate, // IOHandlerDelegate
2855 nullptr)); // FileShadowCollector
Kate Stoneb9c1b512016-09-06 20:57:50 +00002856
2857 if (io_handler_sp) {
2858 io_handler_sp->SetUserData(baton);
2859 if (asynchronously)
2860 debugger.PushIOHandler(io_handler_sp);
2861 else
2862 debugger.RunIOHandler(io_handler_sp);
2863 }
2864}
2865
2866bool CommandInterpreter::IsActive() {
2867 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2868}
2869
2870lldb::IOHandlerSP
2871CommandInterpreter::GetIOHandler(bool force_create,
2872 CommandInterpreterRunOptions *options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002873 // Always re-create the IOHandlerEditline in case the input changed. The old
2874 // instance might have had a non-interactive input and now it does or vice
2875 // versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002876 if (force_create || !m_command_io_handler_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002877 // Always re-create the IOHandlerEditline in case the input changed. The
2878 // old instance might have had a non-interactive input and now it does or
2879 // vice versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002880 uint32_t flags = 0;
2881
2882 if (options) {
2883 if (options->m_stop_on_continue == eLazyBoolYes)
2884 flags |= eHandleCommandFlagStopOnContinue;
2885 if (options->m_stop_on_error == eLazyBoolYes)
2886 flags |= eHandleCommandFlagStopOnError;
2887 if (options->m_stop_on_crash == eLazyBoolYes)
2888 flags |= eHandleCommandFlagStopOnCrash;
2889 if (options->m_echo_commands != eLazyBoolNo)
2890 flags |= eHandleCommandFlagEchoCommand;
Stefan Granitzc678ed72018-10-05 16:49:47 +00002891 if (options->m_echo_comment_commands != eLazyBoolNo)
2892 flags |= eHandleCommandFlagEchoCommentCommand;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002893 if (options->m_print_results != eLazyBoolNo)
2894 flags |= eHandleCommandFlagPrintResult;
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002895 if (options->m_print_errors != eLazyBoolNo)
2896 flags |= eHandleCommandFlagPrintErrors;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002897 } else {
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002898 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult |
2899 eHandleCommandFlagPrintErrors;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002900 }
2901
Jonas Devlieghere796ac802019-02-11 23:13:08 +00002902 m_command_io_handler_sp = std::make_shared<IOHandlerEditline>(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002903 m_debugger, IOHandler::Type::CommandInterpreter,
2904 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2905 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002906 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002907 false, // Don't enable multiple line input, just single line commands
2908 m_debugger.GetUseColor(),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002909 0, // Don't show line numbers
2910 *this, // IOHandlerDelegate
2911 GetDebugger().GetInputRecorder());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002912 }
2913 return m_command_io_handler_sp;
2914}
2915
2916void CommandInterpreter::RunCommandInterpreter(
2917 bool auto_handle_events, bool spawn_thread,
2918 CommandInterpreterRunOptions &options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002919 // Always re-create the command interpreter when we run it in case any file
2920 // handles have changed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002921 bool force_create = true;
2922 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2923 m_stopped_for_crash = false;
2924
2925 if (auto_handle_events)
2926 m_debugger.StartEventHandlerThread();
2927
2928 if (spawn_thread) {
2929 m_debugger.StartIOHandlerThread();
2930 } else {
2931 m_debugger.ExecuteIOHandlers();
2932
2933 if (auto_handle_events)
2934 m_debugger.StopEventHandlerThread();
2935 }
2936}
2937
2938CommandObject *
2939CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2940 CommandReturnObject &result) {
2941 std::string scratch_command(command_line); // working copy so we don't modify
2942 // command_line unless we succeed
2943 CommandObject *cmd_obj = nullptr;
2944 StreamString revised_command_line;
2945 bool wants_raw_input = false;
2946 size_t actual_cmd_name_len = 0;
2947 std::string next_word;
2948 StringList matches;
2949 bool done = false;
2950 while (!done) {
2951 char quote_char = '\0';
2952 std::string suffix;
2953 ExtractCommand(scratch_command, next_word, suffix, quote_char);
2954 if (cmd_obj == nullptr) {
2955 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002956 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00002957 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002958 bool is_real_command =
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002959 (!is_alias) || (cmd_obj != nullptr && !cmd_obj->IsAlias());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002960 if (!is_real_command) {
2961 matches.Clear();
2962 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002963 cmd_obj =
2964 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002965 revised_command_line.Printf("%s", alias_result.c_str());
2966 if (cmd_obj) {
2967 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00002968 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002969 }
2970 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002971 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00002972 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
2973 actual_cmd_name_len += cmd_name.size();
2974 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002975 wants_raw_input = cmd_obj->WantsRawCommandString();
2976 } else {
2977 revised_command_line.Printf("%s", next_word.c_str());
2978 }
2979 }
2980 } else {
2981 if (cmd_obj->IsMultiwordObject()) {
2982 CommandObject *sub_cmd_obj =
2983 cmd_obj->GetSubcommandObject(next_word.c_str());
2984 if (sub_cmd_obj) {
Adrian Prantl05097242018-04-30 16:49:04 +00002985 // The subcommand's name includes the parent command's name, so
2986 // restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00002987 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
2988 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002989 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00002990 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002991 cmd_obj = sub_cmd_obj;
2992 wants_raw_input = cmd_obj->WantsRawCommandString();
2993 } else {
2994 if (quote_char)
2995 revised_command_line.Printf(" %c%s%s%c", quote_char,
2996 next_word.c_str(), suffix.c_str(),
2997 quote_char);
2998 else
2999 revised_command_line.Printf(" %s%s", next_word.c_str(),
3000 suffix.c_str());
3001 done = true;
3002 }
3003 } else {
3004 if (quote_char)
3005 revised_command_line.Printf(" %c%s%s%c", quote_char,
3006 next_word.c_str(), suffix.c_str(),
3007 quote_char);
3008 else
3009 revised_command_line.Printf(" %s%s", next_word.c_str(),
3010 suffix.c_str());
3011 done = true;
3012 }
3013 }
3014
3015 if (cmd_obj == nullptr) {
3016 const size_t num_matches = matches.GetSize();
3017 if (matches.GetSize() > 1) {
3018 StreamString error_msg;
3019 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3020 next_word.c_str());
3021
3022 for (uint32_t i = 0; i < num_matches; ++i) {
3023 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3024 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003025 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003026 } else {
3027 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003028 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003029 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3030 next_word.c_str());
3031 }
3032 result.SetStatus(eReturnStatusFailed);
3033 return nullptr;
3034 }
3035
3036 if (cmd_obj->IsMultiwordObject()) {
3037 if (!suffix.empty()) {
3038 result.AppendErrorWithFormat(
3039 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3040 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003041 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003042 next_word.empty() ? "" : next_word.c_str(),
3043 next_word.empty() ? " -- " : " ", suffix.c_str());
3044 result.SetStatus(eReturnStatusFailed);
3045 return nullptr;
3046 }
3047 } else {
3048 // If we found a normal command, we are done
3049 done = true;
3050 if (!suffix.empty()) {
3051 switch (suffix[0]) {
3052 case '/':
3053 // GDB format suffixes
3054 {
3055 Options *command_options = cmd_obj->GetOptions();
3056 if (command_options &&
3057 command_options->SupportsLongOption("gdb-format")) {
3058 std::string gdb_format_option("--gdb-format=");
3059 gdb_format_option += (suffix.c_str() + 1);
3060
Zachary Turnerc1564272016-11-16 21:15:24 +00003061 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003062 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3063 if (arg_terminator_idx != std::string::npos) {
3064 // Insert the gdb format option before the "--" that terminates
3065 // options
3066 gdb_format_option.append(1, ' ');
3067 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003068 revised_command_line.Clear();
3069 revised_command_line.PutCString(cmd);
3070 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003071 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3072
3073 if (wants_raw_input &&
3074 FindArgumentTerminator(cmd) == std::string::npos)
3075 revised_command_line.PutCString(" --");
3076 } else {
3077 result.AppendErrorWithFormat(
3078 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003079 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003080 result.SetStatus(eReturnStatusFailed);
3081 return nullptr;
3082 }
3083 }
3084 break;
3085
3086 default:
3087 result.AppendErrorWithFormat(
3088 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3089 result.SetStatus(eReturnStatusFailed);
3090 return nullptr;
3091 }
3092 }
3093 }
3094 if (scratch_command.empty())
3095 done = true;
3096 }
3097
3098 if (!scratch_command.empty())
3099 revised_command_line.Printf(" %s", scratch_command.c_str());
3100
Konrad Kleine248a1302019-05-23 11:14:47 +00003101 if (cmd_obj != nullptr)
Zachary Turnerc1564272016-11-16 21:15:24 +00003102 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003103
3104 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003105}