blob: c8a64b0952668070e857999b6c08f3d596cd0a89 [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 Isemann2443bbd2018-07-02 21:29:56 +00001759 if (request.GetCursorIndex() == -1) {
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 Isemann2443bbd2018-07-02 21:29:56 +00001782 request.GetParsedLine().AppendArgument(llvm::StringRef());
1783 request.SetCursorIndex(request.GetCursorIndex() + 1);
1784 request.SetCursorCharPosition(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001785 }
1786 }
Raphael Isemann7f888292018-09-13 21:26:00 +00001787 request.AddCompletions(new_matches, new_descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001788 }
1789
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001790 if (request.GetCursorIndex() > 0 || look_for_subcommand) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001791 // We are completing further on into a commands arguments, so find the
Adrian Prantl05097242018-04-30 16:49:04 +00001792 // command and tell it to complete the command. First see if there is a
1793 // matching initial command:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001794 CommandObject *command_object =
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001795 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
Raphael Isemannae34ed22019-08-22 07:41:23 +00001796 if (command_object) {
Raphael Isemannf8e733f2019-09-23 08:16:19 +00001797 request.ShiftArguments();
Raphael Isemannae34ed22019-08-22 07:41:23 +00001798 command_object->HandleCompletion(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001799 }
1800 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001801}
1802
Raphael Isemannae34ed22019-08-22 07:41:23 +00001803void CommandInterpreter::HandleCompletion(CompletionRequest &request) {
1804
Kate Stoneb9c1b512016-09-06 20:57:50 +00001805 // Don't complete comments, and if the line we are completing is just the
Adrian Prantl05097242018-04-30 16:49:04 +00001806 // history repeat character, substitute the appropriate history line.
Raphael Isemannae34ed22019-08-22 07:41:23 +00001807 llvm::StringRef first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
Raphael Isemann2fc20f62019-08-15 13:14:10 +00001808
Raphael Isemannae34ed22019-08-22 07:41:23 +00001809 if (!first_arg.empty()) {
1810 if (first_arg.front() == m_comment_char)
1811 return;
1812 if (first_arg.front() == CommandHistory::g_repeat_char) {
1813 if (auto hist_str = m_command_history.FindString(first_arg))
1814 request.AddCompletion(*hist_str, "Previous command history event",
1815 CompletionMode::RewriteLine);
1816 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001817 }
1818 }
1819
Raphael Isemannae34ed22019-08-22 07:41:23 +00001820 HandleCompletionMatches(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001821}
1822
1823CommandInterpreter::~CommandInterpreter() {}
1824
Zachary Turner514d8cd2016-09-23 18:06:53 +00001825void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001826 EventSP prompt_change_event_sp(
1827 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1828 ;
1829 BroadcastEvent(prompt_change_event_sp);
1830 if (m_command_io_handler_sp)
1831 m_command_io_handler_sp->SetPrompt(new_prompt);
1832}
1833
Zachary Turner7a120c82016-11-13 03:05:58 +00001834bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001835 // Check AutoConfirm first:
1836 if (m_debugger.GetAutoConfirm())
1837 return default_answer;
1838
1839 IOHandlerConfirm *confirm =
1840 new IOHandlerConfirm(m_debugger, message, default_answer);
1841 IOHandlerSP io_handler_sp(confirm);
1842 m_debugger.RunIOHandler(io_handler_sp);
1843 return confirm->GetResponse();
1844}
1845
Zachary Turnera483f572016-10-05 21:14:49 +00001846const CommandAlias *
1847CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001848 OptionArgVectorSP ret_val;
1849
Zachary Turnera483f572016-10-05 21:14:49 +00001850 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001851 if (pos != m_alias_dict.end())
1852 return (CommandAlias *)pos->second.get();
1853
1854 return nullptr;
1855}
1856
Zachary Turnera4496982016-10-05 21:14:38 +00001857bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001858
Zachary Turnera4496982016-10-05 21:14:38 +00001859bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001860
Zachary Turnera4496982016-10-05 21:14:38 +00001861bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001862
Zachary Turnera4496982016-10-05 21:14:38 +00001863bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001864
1865void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1866 const char *alias_name,
1867 Args &cmd_args,
1868 std::string &raw_input_string,
1869 CommandReturnObject &result) {
1870 OptionArgVectorSP option_arg_vector_sp =
1871 GetAlias(alias_name)->GetOptionArguments();
1872
1873 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1874
1875 // Make sure that the alias name is the 0th element in cmd_args
1876 std::string alias_name_str = alias_name;
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001877 if (alias_name_str != cmd_args.GetArgumentAtIndex(0))
Zachary Turner5c725f32016-09-19 21:56:59 +00001878 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001879
1880 Args new_args(alias_cmd_obj->GetCommandName());
1881 if (new_args.GetArgumentCount() == 2)
1882 new_args.Shift();
1883
1884 if (option_arg_vector_sp.get()) {
1885 if (wants_raw_input) {
1886 // We have a command that both has command options and takes raw input.
Adrian Prantl05097242018-04-30 16:49:04 +00001887 // Make *sure* it has a " -- " in the right place in the
1888 // raw_input_string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001889 size_t pos = raw_input_string.find(" -- ");
1890 if (pos == std::string::npos) {
1891 // None found; assume it goes at the beginning of the raw input string
1892 raw_input_string.insert(0, " -- ");
1893 }
1894 }
1895
1896 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1897 const size_t old_size = cmd_args.GetArgumentCount();
1898 std::vector<bool> used(old_size + 1, false);
1899
1900 used[0] = true;
1901
Zachary Turner5c28c662016-10-03 23:20:36 +00001902 int value_type;
1903 std::string option;
1904 std::string value;
1905 for (const auto &option_entry : *option_arg_vector) {
1906 std::tie(option, value_type, value) = option_entry;
1907 if (option == "<argument>") {
1908 if (!wants_raw_input || (value != "--")) {
1909 // Since we inserted this above, make sure we don't insert it twice
1910 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001911 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001912 continue;
1913 }
1914
1915 if (value_type != OptionParser::eOptionalArgument)
1916 new_args.AppendArgument(option);
1917
1918 if (value == "<no-argument>")
1919 continue;
1920
1921 int index = GetOptionArgumentPosition(value.c_str());
1922 if (index == 0) {
1923 // value was NOT a positional argument; must be a real value
1924 if (value_type != OptionParser::eOptionalArgument)
1925 new_args.AppendArgument(value);
1926 else {
1927 char buffer[255];
1928 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1929 value.c_str());
1930 new_args.AppendArgument(llvm::StringRef(buffer));
1931 }
1932
1933 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1934 result.AppendErrorWithFormat("Not enough arguments provided; you "
1935 "need at least %d arguments to use "
1936 "this alias.\n",
1937 index);
1938 result.SetStatus(eReturnStatusFailed);
1939 return;
1940 } else {
1941 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1942 size_t strpos =
1943 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1944 if (strpos != std::string::npos) {
1945 raw_input_string = raw_input_string.erase(
1946 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1947 }
1948
1949 if (value_type != OptionParser::eOptionalArgument)
1950 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
1951 else {
1952 char buffer[255];
1953 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1954 cmd_args.GetArgumentAtIndex(index));
1955 new_args.AppendArgument(buffer);
1956 }
1957 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001958 }
1959 }
1960
Zachary Turner97d2c402016-10-05 23:40:23 +00001961 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00001962 if (!used[entry.index()] && !wants_raw_input)
Raphael Isemann0d9a2012019-09-13 11:26:48 +00001963 new_args.AppendArgument(entry.value().ref());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001964 }
1965
1966 cmd_args.Clear();
1967 cmd_args.SetArguments(new_args.GetArgumentCount(),
1968 new_args.GetConstArgumentVector());
1969 } else {
1970 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1971 // This alias was not created with any options; nothing further needs to be
Adrian Prantl05097242018-04-30 16:49:04 +00001972 // done, unless it is a command that wants raw input, in which case we need
1973 // to clear the rest of the data from cmd_args, since its in the raw input
1974 // string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001975 if (wants_raw_input) {
1976 cmd_args.Clear();
1977 cmd_args.SetArguments(new_args.GetArgumentCount(),
1978 new_args.GetConstArgumentVector());
1979 }
1980 return;
1981 }
1982
1983 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1984 return;
1985}
1986
1987int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
1988 int position = 0; // Any string that isn't an argument position, i.e. '%'
1989 // followed by an integer, gets a position
1990 // of zero.
1991
1992 const char *cptr = in_string;
1993
1994 // Does it start with '%'
1995 if (cptr[0] == '%') {
1996 ++cptr;
1997
1998 // Is the rest of it entirely digits?
1999 if (isdigit(cptr[0])) {
2000 const char *start = cptr;
2001 while (isdigit(cptr[0]))
2002 ++cptr;
2003
Adrian Prantl05097242018-04-30 16:49:04 +00002004 // We've gotten to the end of the digits; are we at the end of the
2005 // string?
Kate Stoneb9c1b512016-09-06 20:57:50 +00002006 if (cptr[0] == '\0')
2007 position = atoi(start);
2008 }
2009 }
2010
2011 return position;
2012}
2013
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002014static void GetHomeInitFile(llvm::SmallVectorImpl<char> &init_file,
2015 llvm::StringRef suffix = {}) {
2016 std::string init_file_name = ".lldbinit";
2017 if (!suffix.empty()) {
2018 init_file_name.append("-");
2019 init_file_name.append(suffix.str());
2020 }
2021
2022 llvm::sys::path::home_directory(init_file);
2023 llvm::sys::path::append(init_file, init_file_name);
2024
2025 FileSystem::Instance().Resolve(init_file);
2026}
2027
2028static void GetCwdInitFile(llvm::SmallVectorImpl<char> &init_file) {
2029 llvm::StringRef s = ".lldbinit";
2030 init_file.assign(s.begin(), s.end());
2031 FileSystem::Instance().Resolve(init_file);
2032}
2033
2034static LoadCWDlldbinitFile ShouldLoadCwdInitFile() {
2035 lldb::TargetPropertiesSP properties = Target::GetGlobalProperties();
2036 if (!properties)
2037 return eLoadCWDlldbinitFalse;
2038 return properties->GetLoadCWDlldbinitFile();
2039}
2040
2041void CommandInterpreter::SourceInitFile(FileSpec file,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002042 CommandReturnObject &result) {
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002043 assert(!m_skip_lldbinit_files);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002044
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002045 if (!FileSystem::Instance().Exists(file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002046 result.SetStatus(eReturnStatusSuccessFinishNoResult);
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002047 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002048 }
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002049
2050 // Use HandleCommand to 'source' the given file; this will do the actual
2051 // broadcasting of the commands back to any appropriate listener (see
2052 // CommandObjectSource::Execute for more details).
2053 const bool saved_batch = SetBatchCommandMode(true);
2054 ExecutionContext *ctx = nullptr;
2055 CommandInterpreterRunOptions options;
2056 options.SetSilent(true);
2057 options.SetPrintErrors(true);
2058 options.SetStopOnError(false);
2059 options.SetStopOnContinue(true);
2060 HandleCommandsFromFile(file, ctx, options, result);
2061 SetBatchCommandMode(saved_batch);
2062}
2063
2064void CommandInterpreter::SourceInitFileCwd(CommandReturnObject &result) {
2065 if (m_skip_lldbinit_files) {
2066 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2067 return;
2068 }
2069
2070 llvm::SmallString<128> init_file;
2071 GetCwdInitFile(init_file);
2072 if (!FileSystem::Instance().Exists(init_file)) {
2073 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2074 return;
2075 }
2076
2077 LoadCWDlldbinitFile should_load = ShouldLoadCwdInitFile();
2078
2079 switch (should_load) {
2080 case eLoadCWDlldbinitFalse:
2081 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2082 break;
2083 case eLoadCWDlldbinitTrue:
2084 SourceInitFile(FileSpec(init_file.str()), result);
2085 break;
2086 case eLoadCWDlldbinitWarn: {
2087 llvm::SmallString<128> home_init_file;
2088 GetHomeInitFile(home_init_file);
2089 if (llvm::sys::path::parent_path(init_file) ==
2090 llvm::sys::path::parent_path(home_init_file)) {
2091 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2092 } else {
2093 result.AppendErrorWithFormat(InitFileWarning);
2094 result.SetStatus(eReturnStatusFailed);
2095 }
2096 }
2097 }
2098}
2099
2100/// We will first see if there is an application specific ".lldbinit" file
2101/// whose name is "~/.lldbinit" followed by a "-" and the name of the program.
2102/// If this file doesn't exist, we fall back to just the "~/.lldbinit" file.
2103void CommandInterpreter::SourceInitFileHome(CommandReturnObject &result) {
2104 if (m_skip_lldbinit_files) {
2105 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2106 return;
2107 }
2108
2109 llvm::SmallString<128> init_file;
2110 GetHomeInitFile(init_file);
2111
2112 if (!m_skip_app_init_files) {
2113 llvm::StringRef program_name =
2114 HostInfo::GetProgramFileSpec().GetFilename().GetStringRef();
2115 llvm::SmallString<128> program_init_file;
2116 GetHomeInitFile(program_init_file, program_name);
2117 if (FileSystem::Instance().Exists(program_init_file))
2118 init_file = program_init_file;
2119 }
2120
2121 SourceInitFile(FileSpec(init_file.str()), result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002122}
2123
2124const char *CommandInterpreter::GetCommandPrefix() {
2125 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
Konrad Kleine248a1302019-05-23 11:14:47 +00002126 return prefix == nullptr ? "" : prefix;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002127}
2128
2129PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2130 PlatformSP platform_sp;
2131 if (prefer_target_platform) {
2132 ExecutionContext exe_ctx(GetExecutionContext());
2133 Target *target = exe_ctx.GetTargetPtr();
2134 if (target)
2135 platform_sp = target->GetPlatform();
2136 }
2137
2138 if (!platform_sp)
2139 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2140 return platform_sp;
2141}
2142
2143void CommandInterpreter::HandleCommands(const StringList &commands,
2144 ExecutionContext *override_context,
2145 CommandInterpreterRunOptions &options,
2146 CommandReturnObject &result) {
2147 size_t num_lines = commands.GetSize();
2148
2149 // If we are going to continue past a "continue" then we need to run the
Adrian Prantl05097242018-04-30 16:49:04 +00002150 // commands synchronously. Make sure you reset this value anywhere you return
2151 // from the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002152
2153 bool old_async_execution = m_debugger.GetAsyncExecution();
2154
2155 // If we've been given an execution context, set it at the start, but don't
Adrian Prantl05097242018-04-30 16:49:04 +00002156 // keep resetting it or we will cause series of commands that change the
2157 // context, then do an operation that relies on that context to fail.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002158
2159 if (override_context != nullptr)
2160 UpdateExecutionContext(override_context);
2161
2162 if (!options.GetStopOnContinue()) {
2163 m_debugger.SetAsyncExecution(false);
2164 }
2165
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002166 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002167 const char *cmd = commands.GetStringAtIndex(idx);
2168 if (cmd[0] == '\0')
2169 continue;
2170
2171 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002172 // TODO: Add Stream support.
2173 result.AppendMessageWithFormat("%s %s\n",
2174 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002175 }
2176
2177 CommandReturnObject tmp_result;
2178 // If override_context is not NULL, pass no_context_switching = true for
2179 // HandleCommand() since we updated our context already.
2180
2181 // We might call into a regex or alias command, in which case the
Adrian Prantl05097242018-04-30 16:49:04 +00002182 // add_to_history will get lost. This m_command_source_depth dingus is the
2183 // way we turn off adding to the history in that case, so set it up here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002184 if (!options.GetAddToHistory())
2185 m_command_source_depth++;
2186 bool success =
2187 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2188 nullptr, /* override_context */
2189 true, /* repeat_on_empty_command */
2190 override_context != nullptr /* no_context_switching */);
2191 if (!options.GetAddToHistory())
2192 m_command_source_depth--;
2193
2194 if (options.GetPrintResults()) {
2195 if (tmp_result.Succeeded())
Zachary Turner03c9f362016-11-14 23:23:31 +00002196 result.AppendMessage(tmp_result.GetOutputData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002197 }
2198
2199 if (!success || !tmp_result.Succeeded()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002200 llvm::StringRef error_msg = tmp_result.GetErrorData();
2201 if (error_msg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002202 error_msg = "<unknown error>.\n";
2203 if (options.GetStopOnError()) {
2204 result.AppendErrorWithFormat(
2205 "Aborting reading of commands after command #%" PRIu64
2206 ": '%s' failed with %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00002207 (uint64_t)idx, cmd, error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002208 result.SetStatus(eReturnStatusFailed);
2209 m_debugger.SetAsyncExecution(old_async_execution);
2210 return;
2211 } else if (options.GetPrintResults()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002212 result.AppendMessageWithFormat(
2213 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2214 error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002215 }
2216 }
2217
2218 if (result.GetImmediateOutputStream())
2219 result.GetImmediateOutputStream()->Flush();
2220
2221 if (result.GetImmediateErrorStream())
2222 result.GetImmediateErrorStream()->Flush();
2223
Adrian Prantl05097242018-04-30 16:49:04 +00002224 // N.B. Can't depend on DidChangeProcessState, because the state coming
2225 // into the command execution could be running (for instance in Breakpoint
2226 // Commands. So we check the return value to see if it is has running in
2227 // it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002228 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2229 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2230 if (options.GetStopOnContinue()) {
2231 // If we caused the target to proceed, and we're going to stop in that
Adrian Prantl05097242018-04-30 16:49:04 +00002232 // case, set the status in our real result before returning. This is
2233 // an error if the continue was not the last command in the set of
2234 // commands to be run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 if (idx != num_lines - 1)
2236 result.AppendErrorWithFormat(
2237 "Aborting reading of commands after command #%" PRIu64
2238 ": '%s' continued the target.\n",
2239 (uint64_t)idx + 1, cmd);
2240 else
2241 result.AppendMessageWithFormat("Command #%" PRIu64
2242 " '%s' continued the target.\n",
2243 (uint64_t)idx + 1, cmd);
2244
2245 result.SetStatus(tmp_result.GetStatus());
2246 m_debugger.SetAsyncExecution(old_async_execution);
2247
2248 return;
2249 }
2250 }
2251
2252 // Also check for "stop on crash here:
2253 bool should_stop = false;
2254 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2255 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2256 if (target_sp) {
2257 ProcessSP process_sp(target_sp->GetProcessSP());
2258 if (process_sp) {
2259 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2260 StopReason reason = thread_sp->GetStopReason();
2261 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2262 reason == eStopReasonInstrumentation) {
2263 should_stop = true;
2264 break;
2265 }
2266 }
2267 }
2268 }
2269 if (should_stop) {
2270 if (idx != num_lines - 1)
2271 result.AppendErrorWithFormat(
2272 "Aborting reading of commands after command #%" PRIu64
2273 ": '%s' stopped with a signal or exception.\n",
2274 (uint64_t)idx + 1, cmd);
2275 else
2276 result.AppendMessageWithFormat(
2277 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2278 (uint64_t)idx + 1, cmd);
2279
2280 result.SetStatus(tmp_result.GetStatus());
2281 m_debugger.SetAsyncExecution(old_async_execution);
2282
2283 return;
2284 }
2285 }
2286 }
2287
2288 result.SetStatus(eReturnStatusSuccessFinishResult);
2289 m_debugger.SetAsyncExecution(old_async_execution);
2290
2291 return;
2292}
2293
2294// Make flags that we can pass into the IOHandler so our delegates can do the
2295// right thing
2296enum {
2297 eHandleCommandFlagStopOnContinue = (1u << 0),
2298 eHandleCommandFlagStopOnError = (1u << 1),
2299 eHandleCommandFlagEchoCommand = (1u << 2),
Stefan Granitzc678ed72018-10-05 16:49:47 +00002300 eHandleCommandFlagEchoCommentCommand = (1u << 3),
2301 eHandleCommandFlagPrintResult = (1u << 4),
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002302 eHandleCommandFlagPrintErrors = (1u << 5),
2303 eHandleCommandFlagStopOnCrash = (1u << 6)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002304};
2305
2306void CommandInterpreter::HandleCommandsFromFile(
2307 FileSpec &cmd_file, ExecutionContext *context,
2308 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002309 if (!FileSystem::Instance().Exists(cmd_file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002310 result.AppendErrorWithFormat(
2311 "Error reading commands from file %s - file not found.\n",
2312 cmd_file.GetFilename().AsCString("<Unknown>"));
2313 result.SetStatus(eReturnStatusFailed);
2314 return;
2315 }
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002316
2317 StreamFileSP input_file_sp(new StreamFile());
2318 std::string cmd_file_path = cmd_file.GetPath();
2319 Status error = FileSystem::Instance().Open(input_file_sp->GetFile(), cmd_file,
2320 File::eOpenOptionRead);
2321
2322 if (error.Fail()) {
2323 result.AppendErrorWithFormat(
2324 "error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(),
2325 error.AsCString());
2326 result.SetStatus(eReturnStatusFailed);
2327 return;
2328 }
2329
2330 Debugger &debugger = GetDebugger();
2331
2332 uint32_t flags = 0;
2333
2334 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2335 if (m_command_source_flags.empty()) {
2336 // Stop on continue by default
2337 flags |= eHandleCommandFlagStopOnContinue;
2338 } else if (m_command_source_flags.back() &
2339 eHandleCommandFlagStopOnContinue) {
2340 flags |= eHandleCommandFlagStopOnContinue;
2341 }
2342 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2343 flags |= eHandleCommandFlagStopOnContinue;
2344 }
2345
2346 if (options.m_stop_on_error == eLazyBoolCalculate) {
2347 if (m_command_source_flags.empty()) {
2348 if (GetStopCmdSourceOnError())
2349 flags |= eHandleCommandFlagStopOnError;
2350 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) {
2351 flags |= eHandleCommandFlagStopOnError;
2352 }
2353 } else if (options.m_stop_on_error == eLazyBoolYes) {
2354 flags |= eHandleCommandFlagStopOnError;
2355 }
2356
2357 // stop-on-crash can only be set, if it is present in all levels of
2358 // pushed flag sets.
2359 if (options.GetStopOnCrash()) {
2360 if (m_command_source_flags.empty()) {
2361 flags |= eHandleCommandFlagStopOnCrash;
2362 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) {
2363 flags |= eHandleCommandFlagStopOnCrash;
2364 }
2365 }
2366
2367 if (options.m_echo_commands == eLazyBoolCalculate) {
2368 if (m_command_source_flags.empty()) {
2369 // Echo command by default
2370 flags |= eHandleCommandFlagEchoCommand;
2371 } else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) {
2372 flags |= eHandleCommandFlagEchoCommand;
2373 }
2374 } else if (options.m_echo_commands == eLazyBoolYes) {
2375 flags |= eHandleCommandFlagEchoCommand;
2376 }
2377
2378 // We will only ever ask for this flag, if we echo commands in general.
2379 if (options.m_echo_comment_commands == eLazyBoolCalculate) {
2380 if (m_command_source_flags.empty()) {
2381 // Echo comments by default
2382 flags |= eHandleCommandFlagEchoCommentCommand;
2383 } else if (m_command_source_flags.back() &
2384 eHandleCommandFlagEchoCommentCommand) {
2385 flags |= eHandleCommandFlagEchoCommentCommand;
2386 }
2387 } else if (options.m_echo_comment_commands == eLazyBoolYes) {
2388 flags |= eHandleCommandFlagEchoCommentCommand;
2389 }
2390
2391 if (options.m_print_results == eLazyBoolCalculate) {
2392 if (m_command_source_flags.empty()) {
2393 // Print output by default
2394 flags |= eHandleCommandFlagPrintResult;
2395 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) {
2396 flags |= eHandleCommandFlagPrintResult;
2397 }
2398 } else if (options.m_print_results == eLazyBoolYes) {
2399 flags |= eHandleCommandFlagPrintResult;
2400 }
2401
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002402 if (options.m_print_errors == eLazyBoolCalculate) {
2403 if (m_command_source_flags.empty()) {
2404 // Print output by default
2405 flags |= eHandleCommandFlagPrintErrors;
2406 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintErrors) {
2407 flags |= eHandleCommandFlagPrintErrors;
2408 }
2409 } else if (options.m_print_errors == eLazyBoolYes) {
2410 flags |= eHandleCommandFlagPrintErrors;
2411 }
2412
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002413 if (flags & eHandleCommandFlagPrintResult) {
2414 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2415 cmd_file_path.c_str());
2416 }
2417
2418 // Used for inheriting the right settings when "command source" might
2419 // have nested "command source" commands
2420 lldb::StreamFileSP empty_stream_sp;
2421 m_command_source_flags.push_back(flags);
2422 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2423 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2424 empty_stream_sp, // Pass in an empty stream so we inherit the top
2425 // input reader output stream
2426 empty_stream_sp, // Pass in an empty stream so we inherit the top
2427 // input reader error stream
2428 flags,
2429 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2430 // or written
2431 debugger.GetPrompt(), llvm::StringRef(),
2432 false, // Not multi-line
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002433 debugger.GetUseColor(), 0, *this, nullptr));
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002434 const bool old_async_execution = debugger.GetAsyncExecution();
2435
2436 // Set synchronous execution if we are not stopping on continue
2437 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2438 debugger.SetAsyncExecution(false);
2439
2440 m_command_source_depth++;
2441
2442 debugger.RunIOHandler(io_handler_sp);
2443 if (!m_command_source_flags.empty())
2444 m_command_source_flags.pop_back();
2445 m_command_source_depth--;
2446 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2447 debugger.SetAsyncExecution(old_async_execution);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002448}
2449
Kate Stoneb9c1b512016-09-06 20:57:50 +00002450bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2451
2452void CommandInterpreter::SetSynchronous(bool value) {
Jonas Devlieghere70df51b2019-07-31 23:34:45 +00002453 // Asynchronous mode is not supported during reproducer replay.
2454 if (repro::Reproducer::Instance().GetLoader())
2455 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002456 m_synchronous_execution = value;
2457}
2458
2459void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002460 llvm::StringRef prefix,
2461 llvm::StringRef help_text) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002462 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002463
Zachary Turner0ac5f982016-11-08 04:12:42 +00002464 size_t line_width_max = max_columns - prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002465 if (line_width_max < 16)
Zachary Turner0ac5f982016-11-08 04:12:42 +00002466 line_width_max = help_text.size() + prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002467
Zachary Turner0ac5f982016-11-08 04:12:42 +00002468 strm.IndentMore(prefix.size());
2469 bool prefixed_yet = false;
2470 while (!help_text.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002471 // Prefix the first line, indent subsequent lines to line up
Zachary Turner0ac5f982016-11-08 04:12:42 +00002472 if (!prefixed_yet) {
2473 strm << prefix;
2474 prefixed_yet = true;
2475 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002476 strm.Indent();
Zachary Turner0ac5f982016-11-08 04:12:42 +00002477
2478 // Never print more than the maximum on one line.
2479 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2480
2481 // Always break on an explicit newline.
2482 std::size_t first_newline = this_line.find_first_of("\n");
2483
2484 // Don't break on space/tab unless the text is too long to fit on one line.
2485 std::size_t last_space = llvm::StringRef::npos;
2486 if (this_line.size() != help_text.size())
2487 last_space = this_line.find_last_of(" \t");
2488
2489 // Break at whichever condition triggered first.
2490 this_line = this_line.substr(0, std::min(first_newline, last_space));
2491 strm.PutCString(this_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002492 strm.EOL();
2493
Zachary Turner0ac5f982016-11-08 04:12:42 +00002494 // Remove whitespace / newlines after breaking.
2495 help_text = help_text.drop_front(this_line.size()).ltrim();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002496 }
Zachary Turner0ac5f982016-11-08 04:12:42 +00002497 strm.IndentLess(prefix.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002498}
2499
2500void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002501 llvm::StringRef word_text,
2502 llvm::StringRef separator,
2503 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002504 size_t max_word_len) {
2505 StreamString prefix_stream;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002506 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2507 (int)separator.size(), separator.data());
Zachary Turnerc1564272016-11-16 21:15:24 +00002508 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2509}
2510
Zachary Turner0ac5f982016-11-08 04:12:42 +00002511void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2512 llvm::StringRef separator,
2513 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002514 uint32_t max_word_len) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00002515 int indent_size = max_word_len + separator.size() + 2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002516
2517 strm.IndentMore(indent_size);
2518
2519 StreamString text_strm;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002520 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2521 text_strm << separator << " " << help_text;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002522
2523 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2524
Zachary Turnerc1564272016-11-16 21:15:24 +00002525 llvm::StringRef text = text_strm.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002526
2527 uint32_t chars_left = max_columns;
2528
Davide Italianocf8a8292017-04-14 22:36:08 +00002529 auto nextWordLength = [](llvm::StringRef S) {
Jonas Devliegherec712bac2019-03-28 18:10:14 +00002530 size_t pos = S.find(' ');
Davide Italianocf8a8292017-04-14 22:36:08 +00002531 return pos == llvm::StringRef::npos ? S.size() : pos;
2532 };
2533
Zachary Turnerc1564272016-11-16 21:15:24 +00002534 while (!text.empty()) {
2535 if (text.front() == '\n' ||
Jim Inghama81bd7f2017-07-27 00:18:18 +00002536 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002537 strm.EOL();
2538 strm.Indent();
Zachary Turnerc1564272016-11-16 21:15:24 +00002539 chars_left = max_columns - indent_size;
2540 if (text.front() == '\n')
2541 text = text.drop_front();
2542 else
2543 text = text.ltrim(' ');
Kate Stoneb9c1b512016-09-06 20:57:50 +00002544 } else {
Zachary Turnerc1564272016-11-16 21:15:24 +00002545 strm.PutChar(text.front());
2546 --chars_left;
2547 text = text.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002548 }
2549 }
2550
2551 strm.EOL();
2552 strm.IndentLess(indent_size);
2553}
2554
2555void CommandInterpreter::FindCommandsForApropos(
Zachary Turner067d1db2016-11-16 21:45:04 +00002556 llvm::StringRef search_word, StringList &commands_found,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002557 StringList &commands_help, CommandObject::CommandMap &command_map) {
2558 CommandObject::CommandMap::const_iterator pos;
2559
2560 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
Zachary Turner067d1db2016-11-16 21:45:04 +00002561 llvm::StringRef command_name = pos->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002562 CommandObject *cmd_obj = pos->second.get();
2563
2564 const bool search_short_help = true;
2565 const bool search_long_help = false;
2566 const bool search_syntax = false;
2567 const bool search_options = false;
Zachary Turner067d1db2016-11-16 21:45:04 +00002568 if (command_name.contains_lower(search_word) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002569 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2570 search_long_help, search_syntax,
2571 search_options)) {
2572 commands_found.AppendString(cmd_obj->GetCommandName());
2573 commands_help.AppendString(cmd_obj->GetHelp());
2574 }
2575
2576 if (cmd_obj->IsMultiwordObject()) {
2577 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2578 FindCommandsForApropos(search_word, commands_found, commands_help,
2579 cmd_multiword->GetSubcommandDictionary());
2580 }
2581 }
2582}
2583
Zachary Turner067d1db2016-11-16 21:45:04 +00002584void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002585 StringList &commands_found,
2586 StringList &commands_help,
2587 bool search_builtin_commands,
2588 bool search_user_commands,
2589 bool search_alias_commands) {
2590 CommandObject::CommandMap::const_iterator pos;
2591
2592 if (search_builtin_commands)
2593 FindCommandsForApropos(search_word, commands_found, commands_help,
2594 m_command_dict);
2595
2596 if (search_user_commands)
2597 FindCommandsForApropos(search_word, commands_found, commands_help,
2598 m_user_dict);
2599
2600 if (search_alias_commands)
2601 FindCommandsForApropos(search_word, commands_found, commands_help,
2602 m_alias_dict);
2603}
2604
2605void CommandInterpreter::UpdateExecutionContext(
2606 ExecutionContext *override_context) {
2607 if (override_context != nullptr) {
2608 m_exe_ctx_ref = *override_context;
2609 } else {
2610 const bool adopt_selected = true;
2611 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2612 adopt_selected);
2613 }
2614}
2615
Pavel Labatha9d58432019-07-31 12:06:50 +00002616void CommandInterpreter::GetProcessOutput() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002617 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
Pavel Labatha9d58432019-07-31 12:06:50 +00002618 if (!target_sp)
2619 return;
2620
2621 if (ProcessSP process_sp = target_sp->GetProcessSP())
2622 m_debugger.FlushProcessOutput(*process_sp, /*flush_stdout*/ true,
2623 /*flush_stderr*/ true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002624}
2625
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002626void CommandInterpreter::StartHandlingCommand() {
2627 auto idle_state = CommandHandlingState::eIdle;
2628 if (m_command_state.compare_exchange_strong(
2629 idle_state, CommandHandlingState::eInProgress))
2630 lldbassert(m_iohandler_nesting_level == 0);
2631 else
2632 lldbassert(m_iohandler_nesting_level > 0);
2633 ++m_iohandler_nesting_level;
2634}
2635
2636void CommandInterpreter::FinishHandlingCommand() {
2637 lldbassert(m_iohandler_nesting_level > 0);
2638 if (--m_iohandler_nesting_level == 0) {
2639 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2640 lldbassert(prev_state != CommandHandlingState::eIdle);
2641 }
2642}
2643
2644bool CommandInterpreter::InterruptCommand() {
2645 auto in_progress = CommandHandlingState::eInProgress;
2646 return m_command_state.compare_exchange_strong(
2647 in_progress, CommandHandlingState::eInterrupted);
2648}
2649
2650bool CommandInterpreter::WasInterrupted() const {
2651 bool was_interrupted =
2652 (m_command_state == CommandHandlingState::eInterrupted);
2653 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2654 return was_interrupted;
2655}
2656
2657void CommandInterpreter::PrintCommandOutput(Stream &stream,
2658 llvm::StringRef str) {
2659 // Split the output into lines and poll for interrupt requests
2660 const char *data = str.data();
2661 size_t size = str.size();
2662 while (size > 0 && !WasInterrupted()) {
2663 size_t chunk_size = 0;
2664 for (; chunk_size < size; ++chunk_size) {
2665 lldbassert(data[chunk_size] != '\0');
2666 if (data[chunk_size] == '\n') {
2667 ++chunk_size;
2668 break;
2669 }
2670 }
2671 chunk_size = stream.Write(data, chunk_size);
2672 lldbassert(size >= chunk_size);
2673 data += chunk_size;
2674 size -= chunk_size;
2675 }
2676 if (size > 0) {
2677 stream.Printf("\n... Interrupted.\n");
2678 }
2679}
2680
Stefan Granitzc678ed72018-10-05 16:49:47 +00002681bool CommandInterpreter::EchoCommandNonInteractive(
2682 llvm::StringRef line, const Flags &io_handler_flags) const {
2683 if (!io_handler_flags.Test(eHandleCommandFlagEchoCommand))
2684 return false;
2685
2686 llvm::StringRef command = line.trim();
2687 if (command.empty())
2688 return true;
2689
2690 if (command.front() == m_comment_char)
2691 return io_handler_flags.Test(eHandleCommandFlagEchoCommentCommand);
2692
2693 return true;
2694}
2695
Kate Stoneb9c1b512016-09-06 20:57:50 +00002696void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2697 std::string &line) {
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002698 // If we were interrupted, bail out...
2699 if (WasInterrupted())
2700 return;
2701
Kate Stoneb9c1b512016-09-06 20:57:50 +00002702 const bool is_interactive = io_handler.GetIsInteractive();
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002703 if (!is_interactive) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002704 // When we are not interactive, don't execute blank lines. This will happen
2705 // sourcing a commands file. We don't want blank lines to repeat the
Adrian Prantl05097242018-04-30 16:49:04 +00002706 // previous command and cause any errors to occur (like redefining an
2707 // alias, get an error and stop parsing the commands file).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002708 if (line.empty())
2709 return;
2710
2711 // When using a non-interactive file handle (like when sourcing commands
Adrian Prantl05097242018-04-30 16:49:04 +00002712 // from a file) we need to echo the command out so we don't just see the
2713 // command output and no command...
Stefan Granitzc678ed72018-10-05 16:49:47 +00002714 if (EchoCommandNonInteractive(line, io_handler.GetFlags()))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002715 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2716 line.c_str());
2717 }
2718
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002719 StartHandlingCommand();
2720
Kate Stoneb9c1b512016-09-06 20:57:50 +00002721 lldb_private::CommandReturnObject result;
2722 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2723
2724 // Now emit the command output text from the command we just executed
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002725 if ((result.Succeeded() &&
2726 io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) ||
2727 io_handler.GetFlags().Test(eHandleCommandFlagPrintErrors)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002728 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2729 GetProcessOutput();
2730
2731 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002732 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002733 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002734 }
2735
2736 // Now emit the command error text from the command we just executed
2737 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002738 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002739 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002740 }
2741 }
2742
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002743 FinishHandlingCommand();
2744
Kate Stoneb9c1b512016-09-06 20:57:50 +00002745 switch (result.GetStatus()) {
2746 case eReturnStatusInvalid:
2747 case eReturnStatusSuccessFinishNoResult:
2748 case eReturnStatusSuccessFinishResult:
2749 case eReturnStatusStarted:
2750 break;
2751
2752 case eReturnStatusSuccessContinuingNoResult:
2753 case eReturnStatusSuccessContinuingResult:
2754 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2755 io_handler.SetIsDone(true);
2756 break;
2757
2758 case eReturnStatusFailed:
2759 m_num_errors++;
2760 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2761 io_handler.SetIsDone(true);
2762 break;
2763
2764 case eReturnStatusQuit:
2765 m_quit_requested = true;
2766 io_handler.SetIsDone(true);
2767 break;
2768 }
2769
2770 // Finally, if we're going to stop on crash, check that here:
2771 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2772 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2773 bool should_stop = false;
2774 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2775 if (target_sp) {
2776 ProcessSP process_sp(target_sp->GetProcessSP());
2777 if (process_sp) {
2778 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2779 StopReason reason = thread_sp->GetStopReason();
2780 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2781 reason == eStopReasonInstrumentation) &&
2782 !result.GetAbnormalStopWasExpected()) {
2783 should_stop = true;
2784 break;
2785 }
2786 }
2787 }
2788 }
2789 if (should_stop) {
2790 io_handler.SetIsDone(true);
2791 m_stopped_for_crash = true;
2792 }
2793 }
2794}
2795
2796bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2797 ExecutionContext exe_ctx(GetExecutionContext());
2798 Process *process = exe_ctx.GetProcessPtr();
2799
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002800 if (InterruptCommand())
2801 return true;
2802
Kate Stoneb9c1b512016-09-06 20:57:50 +00002803 if (process) {
2804 StateType state = process->GetState();
2805 if (StateIsRunningState(state)) {
2806 process->Halt();
2807 return true; // Don't do any updating when we are running
2808 }
2809 }
2810
Jonas Devlieghere2b29b432019-04-26 22:43:16 +00002811 ScriptInterpreter *script_interpreter =
2812 m_debugger.GetScriptInterpreter(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002813 if (script_interpreter) {
2814 if (script_interpreter->Interrupt())
2815 return true;
2816 }
2817 return false;
2818}
2819
2820void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2821 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2822 void *baton) {
2823 Debugger &debugger = GetDebugger();
2824 IOHandlerSP io_handler_sp(
2825 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2826 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002827 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2828 llvm::StringRef(), // Continuation prompt
2829 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002830 debugger.GetUseColor(),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002831 0, // Don't show line numbers
2832 delegate, // IOHandlerDelegate
2833 nullptr)); // FileShadowCollector
Kate Stoneb9c1b512016-09-06 20:57:50 +00002834
2835 if (io_handler_sp) {
2836 io_handler_sp->SetUserData(baton);
2837 if (asynchronously)
2838 debugger.PushIOHandler(io_handler_sp);
2839 else
2840 debugger.RunIOHandler(io_handler_sp);
2841 }
2842}
2843
2844void CommandInterpreter::GetPythonCommandsFromIOHandler(
2845 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2846 void *baton) {
2847 Debugger &debugger = GetDebugger();
2848 IOHandlerSP io_handler_sp(
2849 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2850 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002851 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2852 llvm::StringRef(), // Continuation prompt
2853 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002854 debugger.GetUseColor(),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002855 0, // Don't show line numbers
2856 delegate, // IOHandlerDelegate
2857 nullptr)); // FileShadowCollector
Kate Stoneb9c1b512016-09-06 20:57:50 +00002858
2859 if (io_handler_sp) {
2860 io_handler_sp->SetUserData(baton);
2861 if (asynchronously)
2862 debugger.PushIOHandler(io_handler_sp);
2863 else
2864 debugger.RunIOHandler(io_handler_sp);
2865 }
2866}
2867
2868bool CommandInterpreter::IsActive() {
2869 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2870}
2871
2872lldb::IOHandlerSP
2873CommandInterpreter::GetIOHandler(bool force_create,
2874 CommandInterpreterRunOptions *options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002875 // Always re-create the IOHandlerEditline in case the input changed. The old
2876 // instance might have had a non-interactive input and now it does or vice
2877 // versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002878 if (force_create || !m_command_io_handler_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002879 // Always re-create the IOHandlerEditline in case the input changed. The
2880 // old instance might have had a non-interactive input and now it does or
2881 // vice versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002882 uint32_t flags = 0;
2883
2884 if (options) {
2885 if (options->m_stop_on_continue == eLazyBoolYes)
2886 flags |= eHandleCommandFlagStopOnContinue;
2887 if (options->m_stop_on_error == eLazyBoolYes)
2888 flags |= eHandleCommandFlagStopOnError;
2889 if (options->m_stop_on_crash == eLazyBoolYes)
2890 flags |= eHandleCommandFlagStopOnCrash;
2891 if (options->m_echo_commands != eLazyBoolNo)
2892 flags |= eHandleCommandFlagEchoCommand;
Stefan Granitzc678ed72018-10-05 16:49:47 +00002893 if (options->m_echo_comment_commands != eLazyBoolNo)
2894 flags |= eHandleCommandFlagEchoCommentCommand;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002895 if (options->m_print_results != eLazyBoolNo)
2896 flags |= eHandleCommandFlagPrintResult;
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002897 if (options->m_print_errors != eLazyBoolNo)
2898 flags |= eHandleCommandFlagPrintErrors;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002899 } else {
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002900 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult |
2901 eHandleCommandFlagPrintErrors;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002902 }
2903
Jonas Devlieghere796ac802019-02-11 23:13:08 +00002904 m_command_io_handler_sp = std::make_shared<IOHandlerEditline>(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002905 m_debugger, IOHandler::Type::CommandInterpreter,
2906 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2907 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002908 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002909 false, // Don't enable multiple line input, just single line commands
2910 m_debugger.GetUseColor(),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002911 0, // Don't show line numbers
2912 *this, // IOHandlerDelegate
2913 GetDebugger().GetInputRecorder());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002914 }
2915 return m_command_io_handler_sp;
2916}
2917
2918void CommandInterpreter::RunCommandInterpreter(
2919 bool auto_handle_events, bool spawn_thread,
2920 CommandInterpreterRunOptions &options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002921 // Always re-create the command interpreter when we run it in case any file
2922 // handles have changed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002923 bool force_create = true;
2924 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2925 m_stopped_for_crash = false;
2926
2927 if (auto_handle_events)
2928 m_debugger.StartEventHandlerThread();
2929
2930 if (spawn_thread) {
2931 m_debugger.StartIOHandlerThread();
2932 } else {
2933 m_debugger.ExecuteIOHandlers();
2934
2935 if (auto_handle_events)
2936 m_debugger.StopEventHandlerThread();
2937 }
2938}
2939
2940CommandObject *
2941CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2942 CommandReturnObject &result) {
2943 std::string scratch_command(command_line); // working copy so we don't modify
2944 // command_line unless we succeed
2945 CommandObject *cmd_obj = nullptr;
2946 StreamString revised_command_line;
2947 bool wants_raw_input = false;
2948 size_t actual_cmd_name_len = 0;
2949 std::string next_word;
2950 StringList matches;
2951 bool done = false;
2952 while (!done) {
2953 char quote_char = '\0';
2954 std::string suffix;
2955 ExtractCommand(scratch_command, next_word, suffix, quote_char);
2956 if (cmd_obj == nullptr) {
2957 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002958 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00002959 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002960 bool is_real_command =
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002961 (!is_alias) || (cmd_obj != nullptr && !cmd_obj->IsAlias());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002962 if (!is_real_command) {
2963 matches.Clear();
2964 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002965 cmd_obj =
2966 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002967 revised_command_line.Printf("%s", alias_result.c_str());
2968 if (cmd_obj) {
2969 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00002970 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002971 }
2972 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002973 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00002974 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
2975 actual_cmd_name_len += cmd_name.size();
2976 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002977 wants_raw_input = cmd_obj->WantsRawCommandString();
2978 } else {
2979 revised_command_line.Printf("%s", next_word.c_str());
2980 }
2981 }
2982 } else {
2983 if (cmd_obj->IsMultiwordObject()) {
2984 CommandObject *sub_cmd_obj =
2985 cmd_obj->GetSubcommandObject(next_word.c_str());
2986 if (sub_cmd_obj) {
Adrian Prantl05097242018-04-30 16:49:04 +00002987 // The subcommand's name includes the parent command's name, so
2988 // restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00002989 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
2990 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002991 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00002992 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002993 cmd_obj = sub_cmd_obj;
2994 wants_raw_input = cmd_obj->WantsRawCommandString();
2995 } else {
2996 if (quote_char)
2997 revised_command_line.Printf(" %c%s%s%c", quote_char,
2998 next_word.c_str(), suffix.c_str(),
2999 quote_char);
3000 else
3001 revised_command_line.Printf(" %s%s", next_word.c_str(),
3002 suffix.c_str());
3003 done = true;
3004 }
3005 } else {
3006 if (quote_char)
3007 revised_command_line.Printf(" %c%s%s%c", quote_char,
3008 next_word.c_str(), suffix.c_str(),
3009 quote_char);
3010 else
3011 revised_command_line.Printf(" %s%s", next_word.c_str(),
3012 suffix.c_str());
3013 done = true;
3014 }
3015 }
3016
3017 if (cmd_obj == nullptr) {
3018 const size_t num_matches = matches.GetSize();
3019 if (matches.GetSize() > 1) {
3020 StreamString error_msg;
3021 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3022 next_word.c_str());
3023
3024 for (uint32_t i = 0; i < num_matches; ++i) {
3025 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3026 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003027 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003028 } else {
3029 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003030 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003031 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3032 next_word.c_str());
3033 }
3034 result.SetStatus(eReturnStatusFailed);
3035 return nullptr;
3036 }
3037
3038 if (cmd_obj->IsMultiwordObject()) {
3039 if (!suffix.empty()) {
3040 result.AppendErrorWithFormat(
3041 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3042 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003043 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003044 next_word.empty() ? "" : next_word.c_str(),
3045 next_word.empty() ? " -- " : " ", suffix.c_str());
3046 result.SetStatus(eReturnStatusFailed);
3047 return nullptr;
3048 }
3049 } else {
3050 // If we found a normal command, we are done
3051 done = true;
3052 if (!suffix.empty()) {
3053 switch (suffix[0]) {
3054 case '/':
3055 // GDB format suffixes
3056 {
3057 Options *command_options = cmd_obj->GetOptions();
3058 if (command_options &&
3059 command_options->SupportsLongOption("gdb-format")) {
3060 std::string gdb_format_option("--gdb-format=");
3061 gdb_format_option += (suffix.c_str() + 1);
3062
Zachary Turnerc1564272016-11-16 21:15:24 +00003063 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003064 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3065 if (arg_terminator_idx != std::string::npos) {
3066 // Insert the gdb format option before the "--" that terminates
3067 // options
3068 gdb_format_option.append(1, ' ');
3069 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003070 revised_command_line.Clear();
3071 revised_command_line.PutCString(cmd);
3072 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003073 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3074
3075 if (wants_raw_input &&
3076 FindArgumentTerminator(cmd) == std::string::npos)
3077 revised_command_line.PutCString(" --");
3078 } else {
3079 result.AppendErrorWithFormat(
3080 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003081 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003082 result.SetStatus(eReturnStatusFailed);
3083 return nullptr;
3084 }
3085 }
3086 break;
3087
3088 default:
3089 result.AppendErrorWithFormat(
3090 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3091 result.SetStatus(eReturnStatusFailed);
3092 return nullptr;
3093 }
3094 }
3095 }
3096 if (scratch_command.empty())
3097 done = true;
3098 }
3099
3100 if (!scratch_command.empty())
3101 revised_command_line.Printf(" %s", scratch_command.c_str());
3102
Konrad Kleine248a1302019-05-23 11:14:47 +00003103 if (cmd_obj != nullptr)
Zachary Turnerc1564272016-11-16 21:15:24 +00003104 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003105
3106 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003107}