blob: e84fe5721cbe6bfe1bd7efd1d6535d4fbc5db355 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner30fdc8d2010-06-08 16:52:24 +00006//
7//===----------------------------------------------------------------------===//
8
Jonas Devlieghere796ac802019-02-11 23:13:08 +00009#include <memory>
Kate Stoneb9c1b512016-09-06 20:57:50 +000010#include <stdlib.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000011#include <string>
Caroline Tice4ab31c92010-10-12 21:57:09 +000012#include <vector>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013
Greg Clayton4a33d312011-06-23 17:59:56 +000014#include "CommandObjectScript.h"
Peter Collingbourne08405b62011-06-23 20:37:26 +000015#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000016
James Y Knight2ad48212018-05-22 22:53:50 +000017#include "Commands/CommandObjectApropos.h"
18#include "Commands/CommandObjectBreakpoint.h"
19#include "Commands/CommandObjectBugreport.h"
20#include "Commands/CommandObjectCommands.h"
21#include "Commands/CommandObjectDisassemble.h"
22#include "Commands/CommandObjectExpression.h"
23#include "Commands/CommandObjectFrame.h"
24#include "Commands/CommandObjectGUI.h"
25#include "Commands/CommandObjectHelp.h"
26#include "Commands/CommandObjectLanguage.h"
27#include "Commands/CommandObjectLog.h"
28#include "Commands/CommandObjectMemory.h"
29#include "Commands/CommandObjectPlatform.h"
30#include "Commands/CommandObjectPlugin.h"
31#include "Commands/CommandObjectProcess.h"
32#include "Commands/CommandObjectQuit.h"
33#include "Commands/CommandObjectRegister.h"
Jonas Devlieghere9e046f02018-11-13 19:18:16 +000034#include "Commands/CommandObjectReproducer.h"
James Y Knight2ad48212018-05-22 22:53:50 +000035#include "Commands/CommandObjectSettings.h"
36#include "Commands/CommandObjectSource.h"
37#include "Commands/CommandObjectStats.h"
38#include "Commands/CommandObjectTarget.h"
39#include "Commands/CommandObjectThread.h"
40#include "Commands/CommandObjectType.h"
41#include "Commands/CommandObjectVersion.h"
42#include "Commands/CommandObjectWatchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044#include "lldb/Core/Debugger.h"
Zachary Turner2c1f46d2015-07-30 20:28:07 +000045#include "lldb/Core/PluginManager.h"
Greg Clayton44d93782014-01-27 23:43:24 +000046#include "lldb/Core/StreamFile.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000047#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000048#include "lldb/Utility/State.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000049#include "lldb/Utility/Stream.h"
Pavel Labath38d06322017-06-29 14:32:17 +000050#include "lldb/Utility/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000051
Todd Fialacacde7d2014-09-27 16:54:22 +000052#ifndef LLDB_DISABLE_LIBEDIT
Greg Clayton44d93782014-01-27 23:43:24 +000053#include "lldb/Host/Editline.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000054#endif
Greg Clayton7fb56d02011-02-01 01:31:41 +000055#include "lldb/Host/Host.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000056#include "lldb/Host/HostInfo.h"
Enrico Granatab5887262012-10-29 21:18:03 +000057
Greg Clayton7d2ef162013-03-29 17:03:23 +000058#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000059#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000060#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000061#include "lldb/Interpreter/OptionValueProperties.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000062#include "lldb/Interpreter/Options.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000063#include "lldb/Interpreter/Property.h"
Pavel Labath145d95c2018-04-17 18:53:35 +000064#include "lldb/Utility/Args.h"
Enrico Granatab5887262012-10-29 21:18:03 +000065
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000067#include "lldb/Target/TargetList.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000068#include "lldb/Target/Thread.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000069
Saleem Abdulrasool28606952014-06-27 05:17:41 +000070#include "llvm/ADT/STLExtras.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000071#include "llvm/ADT/SmallString.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000072#include "llvm/Support/Path.h"
Sean Callanan237c3ed2016-12-14 21:31:31 +000073#include "llvm/Support/PrettyStackTrace.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000074
Chris Lattner30fdc8d2010-06-08 16:52:24 +000075using namespace lldb;
76using namespace lldb_private;
77
Adrian McCarthy2304b6f2015-04-23 20:00:25 +000078static const char *k_white_space = " \t\v";
Greg Clayton754a9362012-08-23 00:22:02 +000079
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +000080static constexpr const char *InitFileWarning =
81 "There is a .lldbinit file in the current directory which is not being "
82 "read.\n"
83 "To silence this warning without sourcing in the local .lldbinit,\n"
84 "add the following to the lldbinit file in your home directory:\n"
85 " settings set target.load-cwd-lldbinit false\n"
86 "To allow lldb to source .lldbinit files in the current working "
87 "directory,\n"
88 "set the value of this variable to true. Only do so if you understand "
89 "and\n"
90 "accept the security risk.";
Stefan Granitzc678ed72018-10-05 16:49:47 +000091
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000092static constexpr PropertyDefinition g_properties[] = {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +000093#define LLDB_PROPERTIES_commandinterpreter
94#include "lldb/Core/Properties.inc"
95};
Kate Stoneb9c1b512016-09-06 20:57:50 +000096
97enum {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +000098#define LLDB_PROPERTIES_commandinterpreter
99#include "lldb/Core/PropertiesEnum.inc"
Greg Clayton754a9362012-08-23 00:22:02 +0000100};
101
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102ConstString &CommandInterpreter::GetStaticBroadcasterClass() {
103 static ConstString class_name("lldb.commandInterpreter");
104 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000105}
106
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107CommandInterpreter::CommandInterpreter(Debugger &debugger,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000108 bool synchronous_execution)
109 : Broadcaster(debugger.GetBroadcasterManager(),
110 CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
111 Properties(OptionValuePropertiesSP(
112 new OptionValueProperties(ConstString("interpreter")))),
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000113 IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114 m_debugger(debugger), m_synchronous_execution(synchronous_execution),
115 m_skip_lldbinit_files(false), m_skip_app_init_files(false),
Jonas Devlieghere2b29b432019-04-26 22:43:16 +0000116 m_command_io_handler_sp(), m_comment_char('#'),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 m_batch_command_mode(false), m_truncation_warning(eNoTruncation),
118 m_command_source_depth(0), m_num_errors(0), m_quit_requested(false),
119 m_stopped_for_crash(false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120 SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit");
121 SetEventName(eBroadcastBitResetPrompt, "reset-prompt");
122 SetEventName(eBroadcastBitQuitCommandReceived, "quit");
123 CheckInWithManager();
124 m_collection_sp->Initialize(g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000125}
126
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127bool CommandInterpreter::GetExpandRegexAliases() const {
128 const uint32_t idx = ePropertyExpandRegexAliases;
129 return m_collection_sp->GetPropertyAtIndexAsBoolean(
130 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000131}
132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133bool CommandInterpreter::GetPromptOnQuit() const {
134 const uint32_t idx = ePropertyPromptOnQuit;
135 return m_collection_sp->GetPropertyAtIndexAsBoolean(
136 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000137}
Greg Clayton754a9362012-08-23 00:22:02 +0000138
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139void CommandInterpreter::SetPromptOnQuit(bool b) {
140 const uint32_t idx = ePropertyPromptOnQuit;
141 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ilia Kacf28be2015-03-23 22:45:13 +0000142}
143
Stefan Granitzc678ed72018-10-05 16:49:47 +0000144bool CommandInterpreter::GetEchoCommands() const {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000145 const uint32_t idx = ePropertyEchoCommands;
Stefan Granitzc678ed72018-10-05 16:49:47 +0000146 return m_collection_sp->GetPropertyAtIndexAsBoolean(
147 nullptr, idx, g_properties[idx].default_uint_value != 0);
148}
149
150void CommandInterpreter::SetEchoCommands(bool b) {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000151 const uint32_t idx = ePropertyEchoCommands;
Stefan Granitzc678ed72018-10-05 16:49:47 +0000152 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
153}
154
155bool CommandInterpreter::GetEchoCommentCommands() const {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000156 const uint32_t idx = ePropertyEchoCommentCommands;
Stefan Granitzc678ed72018-10-05 16:49:47 +0000157 return m_collection_sp->GetPropertyAtIndexAsBoolean(
158 nullptr, idx, g_properties[idx].default_uint_value != 0);
159}
160
161void CommandInterpreter::SetEchoCommentCommands(bool b) {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000162 const uint32_t idx = ePropertyEchoCommentCommands;
Stefan Granitzc678ed72018-10-05 16:49:47 +0000163 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
164}
165
Raphael Isemannc094d232018-07-11 17:18:01 +0000166void CommandInterpreter::AllowExitCodeOnQuit(bool allow) {
167 m_allow_exit_code = allow;
168 if (!allow)
169 m_quit_exit_code.reset();
170}
171
172bool CommandInterpreter::SetQuitExitCode(int exit_code) {
173 if (!m_allow_exit_code)
174 return false;
175 m_quit_exit_code = exit_code;
176 return true;
177}
178
179int CommandInterpreter::GetQuitExitCode(bool &exited) const {
180 exited = m_quit_exit_code.hasValue();
181 if (exited)
182 return *m_quit_exit_code;
183 return 0;
184}
185
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186void CommandInterpreter::ResolveCommand(const char *command_line,
187 CommandReturnObject &result) {
188 std::string command = command_line;
189 if (ResolveCommandImpl(command, result) != nullptr) {
190 result.AppendMessageWithFormat("%s", command.c_str());
191 result.SetStatus(eReturnStatusSuccessFinishResult);
192 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000193}
194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195bool CommandInterpreter::GetStopCmdSourceOnError() const {
196 const uint32_t idx = ePropertyStopCmdSourceOnError;
197 return m_collection_sp->GetPropertyAtIndexAsBoolean(
198 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000199}
200
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201bool CommandInterpreter::GetSpaceReplPrompts() const {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000202 const uint32_t idx = ePropertySpaceReplPrompts;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203 return m_collection_sp->GetPropertyAtIndexAsBoolean(
204 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callanan66810412015-10-19 23:11:07 +0000205}
206
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207void CommandInterpreter::Initialize() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000208 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
209 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000210
Kate Stoneb9c1b512016-09-06 20:57:50 +0000211 CommandReturnObject result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000212
Kate Stoneb9c1b512016-09-06 20:57:50 +0000213 LoadCommandDictionary();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000214
Kate Stoneb9c1b512016-09-06 20:57:50 +0000215 // An alias arguments vector to reuse - reset it before use...
216 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
217
218 // Set up some initial aliases.
219 CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
220 if (cmd_obj_sp) {
221 AddAlias("q", cmd_obj_sp);
222 AddAlias("exit", cmd_obj_sp);
223 }
224
225 cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
226 if (cmd_obj_sp)
227 AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
228
229 cmd_obj_sp = GetCommandSPExact("process detach", false);
230 if (cmd_obj_sp) {
231 AddAlias("detach", cmd_obj_sp);
232 }
233
234 cmd_obj_sp = GetCommandSPExact("process continue", false);
235 if (cmd_obj_sp) {
236 AddAlias("c", cmd_obj_sp);
237 AddAlias("continue", cmd_obj_sp);
238 }
239
240 cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
241 if (cmd_obj_sp)
242 AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
243
244 cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
245 if (cmd_obj_sp)
246 AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
247
248 cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
249 if (cmd_obj_sp) {
250 AddAlias("stepi", cmd_obj_sp);
251 AddAlias("si", cmd_obj_sp);
252 }
253
254 cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
255 if (cmd_obj_sp) {
256 AddAlias("nexti", cmd_obj_sp);
257 AddAlias("ni", cmd_obj_sp);
258 }
259
260 cmd_obj_sp = GetCommandSPExact("thread step-in", false);
261 if (cmd_obj_sp) {
262 AddAlias("s", cmd_obj_sp);
263 AddAlias("step", cmd_obj_sp);
264 CommandAlias *sif_alias = AddAlias(
265 "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
266 if (sif_alias) {
267 sif_alias->SetHelp("Step through the current block, stopping if you step "
268 "directly into a function whose name matches the "
269 "TargetFunctionName.");
270 sif_alias->SetSyntax("sif <TargetFunctionName>");
Caroline Ticeca90c472011-05-06 21:37:15 +0000271 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000273
Kate Stoneb9c1b512016-09-06 20:57:50 +0000274 cmd_obj_sp = GetCommandSPExact("thread step-over", false);
275 if (cmd_obj_sp) {
276 AddAlias("n", cmd_obj_sp);
277 AddAlias("next", cmd_obj_sp);
278 }
279
280 cmd_obj_sp = GetCommandSPExact("thread step-out", false);
281 if (cmd_obj_sp) {
282 AddAlias("finish", cmd_obj_sp);
283 }
284
285 cmd_obj_sp = GetCommandSPExact("frame select", false);
286 if (cmd_obj_sp) {
287 AddAlias("f", cmd_obj_sp);
288 }
289
290 cmd_obj_sp = GetCommandSPExact("thread select", false);
291 if (cmd_obj_sp) {
292 AddAlias("t", cmd_obj_sp);
293 }
294
295 cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
296 if (cmd_obj_sp) {
297 AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
298 AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
299 }
300
301 cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
302 if (cmd_obj_sp) {
303 AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
304 AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
305 }
306
307 cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
308 if (cmd_obj_sp)
309 AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
310
311 cmd_obj_sp = GetCommandSPExact("memory read", false);
312 if (cmd_obj_sp)
313 AddAlias("x", cmd_obj_sp);
314
315 cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
316 if (cmd_obj_sp)
317 AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
318
319 cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
320 if (cmd_obj_sp)
321 AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
322
323 cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
324 if (cmd_obj_sp)
325 AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
326
327 cmd_obj_sp = GetCommandSPExact("disassemble", false);
328 if (cmd_obj_sp)
329 AddAlias("dis", cmd_obj_sp);
330
331 cmd_obj_sp = GetCommandSPExact("disassemble", false);
332 if (cmd_obj_sp)
333 AddAlias("di", cmd_obj_sp);
334
335 cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
336 if (cmd_obj_sp)
337 AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
338
339 cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
340 if (cmd_obj_sp)
341 AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
342
343 cmd_obj_sp = GetCommandSPExact("target create", false);
344 if (cmd_obj_sp)
345 AddAlias("file", cmd_obj_sp);
346
347 cmd_obj_sp = GetCommandSPExact("target modules", false);
348 if (cmd_obj_sp)
349 AddAlias("image", cmd_obj_sp);
350
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000351 alias_arguments_vector_sp = std::make_shared<OptionArgVector>();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352
353 cmd_obj_sp = GetCommandSPExact("expression", false);
354 if (cmd_obj_sp) {
355 AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
356 AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
357 AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
358 if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
359 po->SetHelp("Evaluate an expression on the current thread. Displays any "
360 "returned value with formatting "
361 "controlled by the type's author.");
362 po->SetHelpLong("");
Johnny Chen6d675242012-08-24 18:15:45 +0000363 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
365 AddAlias("poarray", cmd_obj_sp,
366 "--object-description --element-count %1 --")
367 ->SetHelpLong("");
368 }
Johnny Chen6d675242012-08-24 18:15:45 +0000369
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370 cmd_obj_sp = GetCommandSPExact("process kill", false);
371 if (cmd_obj_sp) {
372 AddAlias("kill", cmd_obj_sp);
373 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000374
Kate Stoneb9c1b512016-09-06 20:57:50 +0000375 cmd_obj_sp = GetCommandSPExact("process launch", false);
376 if (cmd_obj_sp) {
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000377 alias_arguments_vector_sp = std::make_shared<OptionArgVector>();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
379 AddAlias("r", cmd_obj_sp, "--");
380 AddAlias("run", cmd_obj_sp, "--");
Jason Molenda85da3122012-07-06 02:46:23 +0000381#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382#if defined(__APPLE__)
383 std::string shell_option;
384 shell_option.append("--shell-expand-args");
385 shell_option.append(" true");
386 shell_option.append(" --");
387 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
388 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
389#else
390 StreamString defaultshell;
391 defaultshell.Printf("--shell=%s --",
392 HostInfo::GetDefaultShell().GetPath().c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +0000393 AddAlias("r", cmd_obj_sp, defaultshell.GetString());
394 AddAlias("run", cmd_obj_sp, defaultshell.GetString());
Jason Molenda85da3122012-07-06 02:46:23 +0000395#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396#endif
397 }
398
399 cmd_obj_sp = GetCommandSPExact("target symbols add", false);
400 if (cmd_obj_sp) {
401 AddAlias("add-dsym", cmd_obj_sp);
402 }
403
404 cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
405 if (cmd_obj_sp) {
406 AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
407 }
Jim Ingham285ae0c2018-10-10 00:51:30 +0000408
409 cmd_obj_sp = GetCommandSPExact("frame variable", false);
410 if (cmd_obj_sp) {
Jim Ingham9082c1c2018-10-12 18:46:02 +0000411 AddAlias("v", cmd_obj_sp);
Jim Ingham285ae0c2018-10-10 00:51:30 +0000412 AddAlias("var", cmd_obj_sp);
413 AddAlias("vo", cmd_obj_sp, "--object-description");
414 }
Jonas Devliegheree5f7d602019-05-03 20:37:09 +0000415
416 cmd_obj_sp = GetCommandSPExact("register", false);
417 if (cmd_obj_sp) {
418 AddAlias("re", cmd_obj_sp);
419 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000420}
421
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422void CommandInterpreter::Clear() {
423 m_command_io_handler_sp.reset();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000424}
425
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
427 // This function has not yet been implemented.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000428
Kate Stoneb9c1b512016-09-06 20:57:50 +0000429 // Look for any embedded script command
430 // If found,
431 // get interpreter object from the command dictionary,
432 // call execute_one_command on it,
433 // get the results as a string,
434 // substitute that string for current stuff.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000435
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 return arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000437}
438
Kate Stoneb9c1b512016-09-06 20:57:50 +0000439void CommandInterpreter::LoadCommandDictionary() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000440 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
441 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000442
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000444
Kate Stoneb9c1b512016-09-06 20:57:50 +0000445 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
446 m_command_dict["breakpoint"] =
447 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
448 m_command_dict["bugreport"] =
449 CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
450 m_command_dict["command"] =
451 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
452 m_command_dict["disassemble"] =
453 CommandObjectSP(new CommandObjectDisassemble(*this));
454 m_command_dict["expression"] =
455 CommandObjectSP(new CommandObjectExpression(*this));
456 m_command_dict["frame"] =
457 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
458 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
459 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
460 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
461 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
462 m_command_dict["platform"] =
463 CommandObjectSP(new CommandObjectPlatform(*this));
464 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
465 m_command_dict["process"] =
466 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
467 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
468 m_command_dict["register"] =
469 CommandObjectSP(new CommandObjectRegister(*this));
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000470 m_command_dict["reproducer"] =
471 CommandObjectSP(new CommandObjectReproducer(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000472 m_command_dict["script"] =
473 CommandObjectSP(new CommandObjectScript(*this, script_language));
474 m_command_dict["settings"] =
475 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
476 m_command_dict["source"] =
477 CommandObjectSP(new CommandObjectMultiwordSource(*this));
Davide Italiano24fff242018-04-13 18:02:39 +0000478 m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000479 m_command_dict["target"] =
480 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
481 m_command_dict["thread"] =
482 CommandObjectSP(new CommandObjectMultiwordThread(*this));
483 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
484 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
485 m_command_dict["watchpoint"] =
486 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
487 m_command_dict["language"] =
488 CommandObjectSP(new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000489
Kate Stoneb9c1b512016-09-06 20:57:50 +0000490 const char *break_regexes[][2] = {
491 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
492 "breakpoint set --file '%1' --line %2"},
493 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
494 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
495 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
496 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
497 "breakpoint set --name '%1'"},
498 {"^(-.*)$", "breakpoint set %1"},
499 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
500 "breakpoint set --name '%2' --shlib '%1'"},
501 {"^\\&(.*[^[:space:]])[[:space:]]*$",
502 "breakpoint set --name '%1' --skip-prologue=0"},
503 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
504 "breakpoint set --name '%1'"}};
Kate Stone7428a182016-07-14 22:03:10 +0000505
Kate Stoneb9c1b512016-09-06 20:57:50 +0000506 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000507
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000508 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509 new CommandObjectRegexCommand(
510 *this, "_regexp-break",
Raphael Isemann129fe892018-07-30 21:41:13 +0000511 "Set a breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000512 "\n"
513 "_regexp-break <filename>:<linenum>\n"
514 " main.c:12 // Break at line 12 of "
515 "main.c\n\n"
516 "_regexp-break <linenum>\n"
517 " 12 // Break at line 12 of current "
518 "file\n\n"
519 "_regexp-break 0x<address>\n"
520 " 0x1234000 // Break at address "
521 "0x1234000\n\n"
522 "_regexp-break <name>\n"
523 " main // Break in 'main' after the "
524 "prologue\n\n"
525 "_regexp-break &<name>\n"
526 " &main // Break at first instruction "
527 "in 'main'\n\n"
528 "_regexp-break <module>`<name>\n"
529 " libc.so`malloc // Break in 'malloc' from "
530 "'libc.so'\n\n"
531 "_regexp-break /<source-regex>/\n"
532 " /break here/ // Break on source lines in "
533 "current file\n"
534 " // containing text 'break "
535 "here'.\n",
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000536 2,
537 CommandCompletions::eSymbolCompletion |
538 CommandCompletions::eSourceFileCompletion,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000540
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000541 if (break_regex_cmd_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000542 bool success = true;
543 for (size_t i = 0; i < num_regexes; i++) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000544 success = break_regex_cmd_up->AddRegexCommand(break_regexes[i][0],
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545 break_regexes[i][1]);
546 if (!success)
547 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000548 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000549 success =
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000550 break_regex_cmd_up->AddRegexCommand("^$", "breakpoint list --full");
Jim Inghamffba2292011-03-22 02:29:32 +0000551
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 if (success) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000553 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
Jim Inghamca36cd12012-10-05 19:16:31 +0000555 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 }
Jim Inghamca36cd12012-10-05 19:16:31 +0000557
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000558 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559 new CommandObjectRegexCommand(
560 *this, "_regexp-tbreak",
Raphael Isemann129fe892018-07-30 21:41:13 +0000561 "Set a one-shot breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 "\n"
563 "_regexp-break <filename>:<linenum>\n"
564 " main.c:12 // Break at line 12 of "
565 "main.c\n\n"
566 "_regexp-break <linenum>\n"
567 " 12 // Break at line 12 of current "
568 "file\n\n"
569 "_regexp-break 0x<address>\n"
570 " 0x1234000 // Break at address "
571 "0x1234000\n\n"
572 "_regexp-break <name>\n"
573 " main // Break in 'main' after the "
574 "prologue\n\n"
575 "_regexp-break &<name>\n"
576 " &main // Break at first instruction "
577 "in 'main'\n\n"
578 "_regexp-break <module>`<name>\n"
579 " libc.so`malloc // Break in 'malloc' from "
580 "'libc.so'\n\n"
581 "_regexp-break /<source-regex>/\n"
582 " /break here/ // Break on source lines in "
583 "current file\n"
584 " // containing text 'break "
585 "here'.\n",
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000586 2,
587 CommandCompletions::eSymbolCompletion |
588 CommandCompletions::eSourceFileCompletion,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589 false));
590
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000591 if (tbreak_regex_cmd_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592 bool success = true;
593 for (size_t i = 0; i < num_regexes; i++) {
594 // If you add a resultant command string longer than 1024 characters be
595 // sure to increase the size of this buffer.
596 char buffer[1024];
597 int num_printed =
Frederic Riss49c9d8b2018-06-18 04:34:33 +0000598 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1");
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000599 lldbassert(num_printed < 1024);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600 UNUSED_IF_ASSERT_DISABLED(num_printed);
601 success =
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000602 tbreak_regex_cmd_up->AddRegexCommand(break_regexes[i][0], buffer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000603 if (!success)
604 break;
Johnny Chen6d675242012-08-24 18:15:45 +0000605 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000606 success =
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000607 tbreak_regex_cmd_up->AddRegexCommand("^$", "breakpoint list --full");
Kate Stone7428a182016-07-14 22:03:10 +0000608
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609 if (success) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000610 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000611 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
612 tbreak_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000613 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614 }
Kate Stone7428a182016-07-14 22:03:10 +0000615
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000616 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000617 new CommandObjectRegexCommand(
618 *this, "_regexp-attach", "Attach to process by ID or name.",
619 "_regexp-attach <pid> | <process-name>", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000620 if (attach_regex_cmd_up) {
621 if (attach_regex_cmd_up->AddRegexCommand("^([0-9]+)[[:space:]]*$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000622 "process attach --pid %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000623 attach_regex_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000624 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
625 // specified get passed to
626 // 'process attach'
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000627 attach_regex_cmd_up->AddRegexCommand("^(.+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628 "process attach --name '%1'") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000629 attach_regex_cmd_up->AddRegexCommand("^$", "process attach")) {
630 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000631 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
632 attach_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000633 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000634 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000635
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000636 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000637 new CommandObjectRegexCommand(*this, "_regexp-down",
638 "Select a newer stack frame. Defaults to "
639 "moving one frame, a numeric argument can "
640 "specify an arbitrary number.",
641 "_regexp-down [<count>]", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000642 if (down_regex_cmd_up) {
643 if (down_regex_cmd_up->AddRegexCommand("^$", "frame select -r -1") &&
644 down_regex_cmd_up->AddRegexCommand("^([0-9]+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000645 "frame select -r -%1")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000646 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000647 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000648 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000650
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000651 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000652 new CommandObjectRegexCommand(
653 *this, "_regexp-up",
654 "Select an older stack frame. Defaults to moving one "
655 "frame, a numeric argument can specify an arbitrary number.",
656 "_regexp-up [<count>]", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000657 if (up_regex_cmd_up) {
658 if (up_regex_cmd_up->AddRegexCommand("^$", "frame select -r 1") &&
659 up_regex_cmd_up->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
660 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000662 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000664
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000665 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000666 new CommandObjectRegexCommand(
667 *this, "_regexp-display",
668 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
669 "_regexp-display expression", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000670 if (display_regex_cmd_up) {
671 if (display_regex_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000673 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000674 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
675 display_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000676 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000677 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000678
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000679 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_up(
680 new CommandObjectRegexCommand(*this, "_regexp-undisplay",
681 "Stop displaying expression at every "
682 "stop (specified by stop-hook index.)",
683 "_regexp-undisplay stop-hook-number", 2, 0,
684 false));
685 if (undisplay_regex_cmd_up) {
686 if (undisplay_regex_cmd_up->AddRegexCommand("^([0-9]+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000687 "target stop-hook delete %1")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000688 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000689 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
690 undisplay_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000691 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000693
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000694 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 new CommandObjectRegexCommand(
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000696 *this, "gdb-remote",
697 "Connect to a process via remote GDB server. "
698 "If no host is specifed, localhost is assumed.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000700 if (connect_gdb_remote_cmd_up) {
701 if (connect_gdb_remote_cmd_up->AddRegexCommand(
Chris Bieneman51978f52017-04-27 16:13:58 +0000702 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
703 "process connect --plugin gdb-remote connect://%1:%2") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000704 connect_gdb_remote_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 "^([[:digit:]]+)$",
706 "process connect --plugin gdb-remote connect://localhost:%1")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000707 CommandObjectSP command_sp(connect_gdb_remote_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000708 m_command_dict[command_sp->GetCommandName()] = command_sp;
Jason Molenda4cddfed2012-10-05 05:29:32 +0000709 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710 }
Jason Molenda4cddfed2012-10-05 05:29:32 +0000711
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000712 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000713 new CommandObjectRegexCommand(
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000714 *this, "kdp-remote",
715 "Connect to a process via remote KDP server. "
716 "If no UDP port is specified, port 41139 is "
717 "assumed.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000719 if (connect_kdp_remote_cmd_up) {
720 if (connect_kdp_remote_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000721 "^([^:]+:[[:digit:]]+)$",
722 "process connect --plugin kdp-remote udp://%1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000723 connect_kdp_remote_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000724 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000725 CommandObjectSP command_sp(connect_kdp_remote_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000726 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Clayton6bade322013-02-01 23:33:03 +0000727 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000728 }
Greg Clayton6bade322013-02-01 23:33:03 +0000729
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000730 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000731 new CommandObjectRegexCommand(
732 *this, "_regexp-bt",
733 "Show the current thread's call stack. Any numeric argument "
734 "displays at most that many "
Jim Inghame91ad7d2019-05-02 02:14:08 +0000735 "frames. The argument 'all' displays all threads. Use 'settings"
736 " set frame-format' to customize the printing of individual frames "
737 "and 'settings set thread-format' to customize the thread header.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738 "bt [<digit> | all]", 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000739 if (bt_regex_cmd_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000740 // accept but don't document "bt -c <number>" -- before bt was a regex
Adrian Prantl05097242018-04-30 16:49:04 +0000741 // command if you wanted to backtrace three frames you would do "bt -c 3"
742 // but the intention is to have this emulate the gdb "bt" command and so
743 // now "bt 3" is the preferred form, in line with gdb.
Stella Stamenova5bac7062019-05-17 18:52:42 +0000744 if (bt_regex_cmd_up->AddRegexCommand("^([[:digit:]]+)[[:space:]]*$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000745 "thread backtrace -c %1") &&
Stella Stamenova5bac7062019-05-17 18:52:42 +0000746 bt_regex_cmd_up->AddRegexCommand("^-c ([[:digit:]]+)[[:space:]]*$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000747 "thread backtrace -c %1") &&
Stella Stamenova5bac7062019-05-17 18:52:42 +0000748 bt_regex_cmd_up->AddRegexCommand("^all[[:space:]]*$", "thread backtrace all") &&
749 bt_regex_cmd_up->AddRegexCommand("^[[:space:]]*$", "thread backtrace")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000750 CommandObjectSP command_sp(bt_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000751 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Claytonef5651d2013-02-12 18:52:24 +0000752 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 }
Greg Claytonef5651d2013-02-12 18:52:24 +0000754
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000755 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756 new CommandObjectRegexCommand(
757 *this, "_regexp-list",
758 "List relevant source code using one of several shorthand formats.",
759 "\n"
760 "_regexp-list <file>:<line> // List around specific file/line\n"
761 "_regexp-list <line> // List current file around specified "
762 "line\n"
763 "_regexp-list <function-name> // List specified function\n"
764 "_regexp-list 0x<address> // List around specified address\n"
765 "_regexp-list -[<count>] // List previous <count> lines\n"
766 "_regexp-list // List subsequent lines",
767 2, CommandCompletions::eSourceFileCompletion, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000768 if (list_regex_cmd_up) {
769 if (list_regex_cmd_up->AddRegexCommand("^([0-9]+)[[:space:]]*$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000770 "source list --line %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000771 list_regex_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
773 "]*$",
774 "source list --file '%1' --line %2") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000775 list_regex_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
777 "source list --address %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000778 list_regex_cmd_up->AddRegexCommand("^-[[:space:]]*$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000779 "source list --reverse") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000780 list_regex_cmd_up->AddRegexCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781 "^-([[:digit:]]+)[[:space:]]*$",
782 "source list --reverse --count %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000783 list_regex_cmd_up->AddRegexCommand("^(.+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000784 "source list --name \"%1\"") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000785 list_regex_cmd_up->AddRegexCommand("^$", "source list")) {
786 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
Richard Mittonf86248d2013-09-12 02:20:34 +0000788 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000789 }
Richard Mittonf86248d2013-09-12 02:20:34 +0000790
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000791 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000792 new CommandObjectRegexCommand(
793 *this, "_regexp-env",
794 "Shorthand for viewing and setting environment variables.",
795 "\n"
Adrian McCarthy17c18a92019-06-25 23:13:16 +0000796 "_regexp-env // Show environment\n"
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 "_regexp-env <name>=<value> // Set an environment variable",
798 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000799 if (env_regex_cmd_up) {
800 if (env_regex_cmd_up->AddRegexCommand("^$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801 "settings show target.env-vars") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000802 env_regex_cmd_up->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000803 "settings set target.env-vars %1")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000804 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000805 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
806 }
807 }
808
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000809 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000810 new CommandObjectRegexCommand(
811 *this, "_regexp-jump", "Set the program counter to a new address.",
812 "\n"
813 "_regexp-jump <line>\n"
814 "_regexp-jump +<line-offset> | -<line-offset>\n"
815 "_regexp-jump <file>:<line>\n"
816 "_regexp-jump *<addr>\n",
817 2, 0, false));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000818 if (jump_regex_cmd_up) {
819 if (jump_regex_cmd_up->AddRegexCommand("^\\*(.*)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000820 "thread jump --addr %1") &&
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 --line %1") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000823 jump_regex_cmd_up->AddRegexCommand("^([^:]+):([0-9]+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000824 "thread jump --file %1 --line %2") &&
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000825 jump_regex_cmd_up->AddRegexCommand("^([+\\-][0-9]+)$",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000826 "thread jump --by %1")) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000827 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
829 }
830 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000831}
832
Kate Stoneb9c1b512016-09-06 20:57:50 +0000833int CommandInterpreter::GetCommandNamesMatchingPartialString(
Raphael Isemann7f888292018-09-13 21:26:00 +0000834 const char *cmd_str, bool include_aliases, StringList &matches,
835 StringList &descriptions) {
836 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches,
837 &descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000838
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 if (include_aliases) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000840 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches,
841 &descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000843
Kate Stoneb9c1b512016-09-06 20:57:50 +0000844 return matches.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000845}
846
Raphael Isemann7f888292018-09-13 21:26:00 +0000847CommandObjectSP
848CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases,
849 bool exact, StringList *matches,
850 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000852
Zachary Turnera4496982016-10-05 21:14:38 +0000853 std::string cmd = cmd_str;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000854
Kate Stoneb9c1b512016-09-06 20:57:50 +0000855 if (HasCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000856 auto pos = m_command_dict.find(cmd);
Greg Claytonb5472782015-01-09 19:08:20 +0000857 if (pos != m_command_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000858 command_sp = pos->second;
859 }
860
861 if (include_aliases && HasAliases()) {
862 auto alias_pos = m_alias_dict.find(cmd);
863 if (alias_pos != m_alias_dict.end())
864 command_sp = alias_pos->second;
865 }
866
867 if (HasUserCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000868 auto pos = m_user_dict.find(cmd);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000869 if (pos != m_user_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000870 command_sp = pos->second;
871 }
872
873 if (!exact && !command_sp) {
874 // We will only get into here if we didn't find any exact matches.
875
876 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
877
878 StringList local_matches;
879 if (matches == nullptr)
880 matches = &local_matches;
881
882 unsigned int num_cmd_matches = 0;
883 unsigned int num_alias_matches = 0;
884 unsigned int num_user_matches = 0;
885
886 // Look through the command dictionaries one by one, and if we get only one
Adrian Prantl05097242018-04-30 16:49:04 +0000887 // match from any of them in toto, then return that, otherwise return an
888 // empty CommandObjectSP and the list of matches.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000889
890 if (HasCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000891 num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str,
892 *matches, descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000893 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000894
895 if (num_cmd_matches == 1) {
896 cmd.assign(matches->GetStringAtIndex(0));
Zachary Turnera4496982016-10-05 21:14:38 +0000897 auto pos = m_command_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000898 if (pos != m_command_dict.end())
899 real_match_sp = pos->second;
900 }
901
902 if (include_aliases && HasAliases()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000903 num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str,
904 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000905 }
906
907 if (num_alias_matches == 1) {
908 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
909 auto alias_pos = m_alias_dict.find(cmd);
910 if (alias_pos != m_alias_dict.end())
911 alias_match_sp = alias_pos->second;
912 }
913
914 if (HasUserCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000915 num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str,
916 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000917 }
918
919 if (num_user_matches == 1) {
920 cmd.assign(
921 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
922
Zachary Turnera4496982016-10-05 21:14:38 +0000923 auto pos = m_user_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 if (pos != m_user_dict.end())
925 user_match_sp = pos->second;
926 }
927
928 // If we got exactly one match, return that, otherwise return the match
929 // list.
930
931 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
932 if (num_cmd_matches)
933 return real_match_sp;
934 else if (num_alias_matches)
935 return alias_match_sp;
936 else
937 return user_match_sp;
938 }
939 } else if (matches && command_sp) {
Zachary Turnera4496982016-10-05 21:14:38 +0000940 matches->AppendString(cmd_str);
Raphael Isemann7f888292018-09-13 21:26:00 +0000941 if (descriptions)
942 descriptions->AppendString(command_sp->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000943 }
944
945 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000946}
947
Zachary Turnera4496982016-10-05 21:14:38 +0000948bool CommandInterpreter::AddCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949 const lldb::CommandObjectSP &cmd_sp,
950 bool can_replace) {
951 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000952 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
953 "tried to add a CommandObject from a different interpreter");
Kate Stonea487aa42015-01-15 00:52:41 +0000954
Zachary Turnera4496982016-10-05 21:14:38 +0000955 if (name.empty())
956 return false;
957
958 std::string name_sstr(name);
959 auto name_iter = m_command_dict.find(name_sstr);
960 if (name_iter != m_command_dict.end()) {
961 if (!can_replace || !name_iter->second->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000962 return false;
Zachary Turnera4496982016-10-05 21:14:38 +0000963 name_iter->second = cmd_sp;
964 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000965 m_command_dict[name_sstr] = cmd_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000966 }
Zachary Turnera4496982016-10-05 21:14:38 +0000967 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000968}
969
Zachary Turnera483f572016-10-05 21:14:49 +0000970bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 const lldb::CommandObjectSP &cmd_sp,
972 bool can_replace) {
973 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000974 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
975 "tried to add a CommandObject from a different interpreter");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000976
Kate Stoneb9c1b512016-09-06 20:57:50 +0000977 if (!name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978 // do not allow replacement of internal commands
Zachary Turnera483f572016-10-05 21:14:49 +0000979 if (CommandExists(name)) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000980 if (!can_replace)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 return false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000982 if (!m_command_dict[name]->IsRemovable())
Greg Clayton5a314712011-10-14 07:41:33 +0000983 return false;
984 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000985
Zachary Turnera483f572016-10-05 21:14:49 +0000986 if (UserCommandExists(name)) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000987 if (!can_replace)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000988 return false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000989 if (!m_user_dict[name]->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990 return false;
Caroline Tice844d2302010-12-09 22:52:49 +0000991 }
992
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993 m_user_dict[name] = cmd_sp;
994 return true;
995 }
996 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000997}
998
Zachary Turnera4496982016-10-05 21:14:38 +0000999CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
1000 bool include_aliases) const {
1001 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002 // it's a multi-word command.
1003 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001004
Zachary Turnera4496982016-10-05 21:14:38 +00001005 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001006 return ret_val;
1007
1008 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +00001009 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001010 else {
1011 // We have a multi-word command (seemingly), so we need to do more work.
1012 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +00001013 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001014 include_aliases, true, nullptr);
1015 if (cmd_obj_sp.get() != nullptr) {
Adrian Prantl05097242018-04-30 16:49:04 +00001016 // Loop through the rest of the words in the command (everything passed
1017 // in was supposed to be part of a command name), and find the
1018 // appropriate sub-command SP for each command word....
Kate Stoneb9c1b512016-09-06 20:57:50 +00001019 size_t end = cmd_words.GetArgumentCount();
1020 for (size_t j = 1; j < end; ++j) {
1021 if (cmd_obj_sp->IsMultiwordObject()) {
1022 cmd_obj_sp =
1023 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
1024 if (cmd_obj_sp.get() == nullptr)
1025 // The sub-command name was invalid. Fail and return the empty
1026 // 'ret_val'.
1027 return ret_val;
1028 } else
1029 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +00001030 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001031 return ret_val;
1032 }
1033 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +00001034 // command objects for them. Assign the last object retrieved to
1035 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001037 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001038 }
1039 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001040}
1041
Raphael Isemann7f888292018-09-13 21:26:00 +00001042CommandObject *
1043CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
1044 StringList *matches,
1045 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001046 CommandObject *command_obj =
Raphael Isemann7f888292018-09-13 21:26:00 +00001047 GetCommandSP(cmd_str, false, true, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001048
Kate Stoneb9c1b512016-09-06 20:57:50 +00001049 // If we didn't find an exact match to the command string in the commands,
Adrian Prantl05097242018-04-30 16:49:04 +00001050 // look in the aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001051
1052 if (command_obj)
1053 return command_obj;
1054
Raphael Isemann7f888292018-09-13 21:26:00 +00001055 command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001056
1057 if (command_obj)
1058 return command_obj;
1059
1060 // If there wasn't an exact match then look for an inexact one in just the
1061 // commands
Zachary Turnera4496982016-10-05 21:14:38 +00001062 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063
1064 // Finally, if there wasn't an inexact match among the commands, look for an
Adrian Prantl05097242018-04-30 16:49:04 +00001065 // inexact match in both the commands and aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001066
1067 if (command_obj) {
1068 if (matches)
1069 matches->AppendString(command_obj->GetCommandName());
Raphael Isemann7f888292018-09-13 21:26:00 +00001070 if (descriptions)
1071 descriptions->AppendString(command_obj->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001072 return command_obj;
1073 }
1074
Raphael Isemann7f888292018-09-13 21:26:00 +00001075 return GetCommandSP(cmd_str, true, false, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001076}
1077
Zachary Turnera483f572016-10-05 21:14:49 +00001078bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001079 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001080}
1081
Zachary Turnera483f572016-10-05 21:14:49 +00001082bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1083 std::string &full_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001084 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1085 if (exact_match) {
1086 full_name.assign(cmd);
1087 return exact_match;
1088 } else {
1089 StringList matches;
1090 size_t num_alias_matches;
1091 num_alias_matches =
1092 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1093 if (num_alias_matches == 1) {
1094 // Make sure this isn't shadowing a command in the regular command space:
1095 StringList regular_matches;
1096 const bool include_aliases = false;
1097 const bool exact = false;
1098 CommandObjectSP cmd_obj_sp(
1099 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1100 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1101 return false;
1102 else {
1103 full_name.assign(matches.GetStringAtIndex(0));
1104 return true;
1105 }
1106 } else
1107 return false;
1108 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001109}
1110
Zachary Turnera483f572016-10-05 21:14:49 +00001111bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001112 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001113}
1114
Zachary Turnera483f572016-10-05 21:14:49 +00001115bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001116 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001117}
1118
Kate Stoneb9c1b512016-09-06 20:57:50 +00001119CommandAlias *
Zachary Turnera483f572016-10-05 21:14:49 +00001120CommandInterpreter::AddAlias(llvm::StringRef alias_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001121 lldb::CommandObjectSP &command_obj_sp,
Zachary Turnera483f572016-10-05 21:14:49 +00001122 llvm::StringRef args_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123 if (command_obj_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001124 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1125 "tried to add a CommandObject from a different interpreter");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001126
1127 std::unique_ptr<CommandAlias> command_alias_up(
1128 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1129
1130 if (command_alias_up && command_alias_up->IsValid()) {
1131 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1132 return command_alias_up.release();
1133 }
1134
1135 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001136}
1137
Zachary Turnera483f572016-10-05 21:14:49 +00001138bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139 auto pos = m_alias_dict.find(alias_name);
1140 if (pos != m_alias_dict.end()) {
1141 m_alias_dict.erase(pos);
1142 return true;
1143 }
1144 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001145}
1146
Zachary Turnera483f572016-10-05 21:14:49 +00001147bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001148 auto pos = m_command_dict.find(cmd);
1149 if (pos != m_command_dict.end()) {
1150 if (pos->second->IsRemovable()) {
1151 // Only regular expression objects or python commands are removable
1152 m_command_dict.erase(pos);
1153 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001154 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001155 }
1156 return false;
1157}
Zachary Turnera483f572016-10-05 21:14:49 +00001158bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001159 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1160 if (pos != m_user_dict.end()) {
1161 m_user_dict.erase(pos);
1162 return true;
1163 }
1164 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001165}
1166
Kate Stoneb9c1b512016-09-06 20:57:50 +00001167void CommandInterpreter::GetHelp(CommandReturnObject &result,
1168 uint32_t cmd_types) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001169 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1170 if (!help_prologue.empty()) {
1171 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1172 help_prologue);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001174
Kate Stoneb9c1b512016-09-06 20:57:50 +00001175 CommandObject::CommandMap::const_iterator pos;
1176 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001177
Kate Stoneb9c1b512016-09-06 20:57:50 +00001178 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1179 result.AppendMessage("Debugger commands:");
1180 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001181
Kate Stoneb9c1b512016-09-06 20:57:50 +00001182 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1183 if (!(cmd_types & eCommandTypesHidden) &&
1184 (pos->first.compare(0, 1, "_") == 0))
1185 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001186
Zachary Turner0ac5f982016-11-08 04:12:42 +00001187 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1188 pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001189 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190 result.AppendMessage("");
1191 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001192
Kate Stoneb9c1b512016-09-06 20:57:50 +00001193 if (!m_alias_dict.empty() &&
1194 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1195 result.AppendMessageWithFormat(
1196 "Current command abbreviations "
1197 "(type '%shelp command alias' for more info):\n",
1198 GetCommandPrefix());
1199 result.AppendMessage("");
1200 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001201
Kate Stoneb9c1b512016-09-06 20:57:50 +00001202 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1203 ++alias_pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001204 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
Kate Stoneb9c1b512016-09-06 20:57:50 +00001205 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001206 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001207 result.AppendMessage("");
1208 }
Greg Clayton14a35512011-09-11 00:01:44 +00001209
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 if (!m_user_dict.empty() &&
1211 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1212 result.AppendMessage("Current user-defined commands:");
1213 result.AppendMessage("");
1214 max_len = FindLongestCommandWord(m_user_dict);
1215 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001216 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1217 pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001218 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001219 result.AppendMessage("");
1220 }
Greg Clayton14a35512011-09-11 00:01:44 +00001221
Kate Stoneb9c1b512016-09-06 20:57:50 +00001222 result.AppendMessageWithFormat(
1223 "For more information on any command, type '%shelp <command-name>'.\n",
1224 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001225}
1226
Zachary Turnera01bccd2016-10-05 21:14:56 +00001227CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1228 llvm::StringRef &command_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229 // This function finds the final, lowest-level, alias-resolved command object
Adrian Prantl05097242018-04-30 16:49:04 +00001230 // whose 'Execute' function will eventually be invoked by the given command
1231 // line.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001232
1233 CommandObject *cmd_obj = nullptr;
1234 size_t start = command_string.find_first_not_of(k_white_space);
1235 size_t end = 0;
1236 bool done = false;
1237 while (!done) {
1238 if (start != std::string::npos) {
1239 // Get the next word from command_string.
1240 end = command_string.find_first_of(k_white_space, start);
1241 if (end == std::string::npos)
1242 end = command_string.size();
1243 std::string cmd_word = command_string.substr(start, end - start);
1244
1245 if (cmd_obj == nullptr)
1246 // Since cmd_obj is NULL we are on our first time through this loop.
Zachary Turnera01bccd2016-10-05 21:14:56 +00001247 // Check to see if cmd_word is a valid command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001248 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001249 else if (cmd_obj->IsMultiwordObject()) {
1250 // Our current object is a multi-word object; see if the cmd_word is a
1251 // valid sub-command for our object.
1252 CommandObject *sub_cmd_obj =
1253 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1254 if (sub_cmd_obj)
1255 cmd_obj = sub_cmd_obj;
1256 else // cmd_word was not a valid sub-command word, so we are done
1257 done = true;
1258 } else
1259 // We have a cmd_obj and it is not a multi-word object, so we are done.
1260 done = true;
1261
1262 // If we didn't find a valid command object, or our command object is not
Zachary Turnera01bccd2016-10-05 21:14:56 +00001263 // a multi-word object, or we are at the end of the command_string, then
1264 // we are done. Otherwise, find the start of the next word.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265
1266 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1267 end >= command_string.size())
1268 done = true;
1269 else
1270 start = command_string.find_first_not_of(k_white_space, end);
1271 } else
1272 // Unable to find any more words.
1273 done = true;
1274 }
1275
Zachary Turnera01bccd2016-10-05 21:14:56 +00001276 command_string = command_string.substr(end);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001277 return cmd_obj;
1278}
1279
1280static const char *k_valid_command_chars =
1281 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1282static void StripLeadingSpaces(std::string &s) {
1283 if (!s.empty()) {
1284 size_t pos = s.find_first_not_of(k_white_space);
1285 if (pos == std::string::npos)
1286 s.clear();
1287 else if (pos == 0)
1288 return;
1289 s.erase(0, pos);
1290 }
1291}
1292
1293static size_t FindArgumentTerminator(const std::string &s) {
1294 const size_t s_len = s.size();
1295 size_t offset = 0;
1296 while (offset < s_len) {
1297 size_t pos = s.find("--", offset);
1298 if (pos == std::string::npos)
1299 break;
1300 if (pos > 0) {
1301 if (isspace(s[pos - 1])) {
Adrian Prantl05097242018-04-30 16:49:04 +00001302 // Check if the string ends "\s--" (where \s is a space character) or
1303 // if we have "\s--\s".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1305 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001306 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001307 }
1308 }
1309 offset = pos + 2;
1310 }
1311 return std::string::npos;
1312}
1313
1314static bool ExtractCommand(std::string &command_string, std::string &command,
1315 std::string &suffix, char &quote_char) {
1316 command.clear();
1317 suffix.clear();
1318 StripLeadingSpaces(command_string);
1319
1320 bool result = false;
1321 quote_char = '\0';
1322
1323 if (!command_string.empty()) {
1324 const char first_char = command_string[0];
1325 if (first_char == '\'' || first_char == '"') {
1326 quote_char = first_char;
1327 const size_t end_quote_pos = command_string.find(quote_char, 1);
1328 if (end_quote_pos == std::string::npos) {
1329 command.swap(command_string);
1330 command_string.erase();
1331 } else {
1332 command.assign(command_string, 1, end_quote_pos - 1);
1333 if (end_quote_pos + 1 < command_string.size())
1334 command_string.erase(0, command_string.find_first_not_of(
1335 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001336 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001337 command_string.erase();
1338 }
1339 } else {
1340 const size_t first_space_pos =
1341 command_string.find_first_of(k_white_space);
1342 if (first_space_pos == std::string::npos) {
1343 command.swap(command_string);
1344 command_string.erase();
1345 } else {
1346 command.assign(command_string, 0, first_space_pos);
1347 command_string.erase(0, command_string.find_first_not_of(
1348 k_white_space, first_space_pos));
1349 }
1350 }
1351 result = true;
1352 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001353
Kate Stoneb9c1b512016-09-06 20:57:50 +00001354 if (!command.empty()) {
1355 // actual commands can't start with '-' or '_'
1356 if (command[0] != '-' && command[0] != '_') {
1357 size_t pos = command.find_first_not_of(k_valid_command_chars);
1358 if (pos > 0 && pos != std::string::npos) {
1359 suffix.assign(command.begin() + pos, command.end());
1360 command.erase(pos);
1361 }
1362 }
1363 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001364
Kate Stoneb9c1b512016-09-06 20:57:50 +00001365 return result;
1366}
1367
1368CommandObject *CommandInterpreter::BuildAliasResult(
Zachary Turnera483f572016-10-05 21:14:49 +00001369 llvm::StringRef alias_name, std::string &raw_input_string,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001370 std::string &alias_result, CommandReturnObject &result) {
1371 CommandObject *alias_cmd_obj = nullptr;
1372 Args cmd_args(raw_input_string);
1373 alias_cmd_obj = GetCommandObject(alias_name);
1374 StreamString result_str;
1375
Zachary Turner5c28c662016-10-03 23:20:36 +00001376 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1377 alias_result.clear();
1378 return alias_cmd_obj;
1379 }
1380 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1381 ((CommandAlias *)alias_cmd_obj)->Desugar();
1382 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1383 alias_cmd_obj = desugared.first.get();
1384 std::string alias_name_str = alias_name;
1385 if ((cmd_args.GetArgumentCount() == 0) ||
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001386 (alias_name_str != cmd_args.GetArgumentAtIndex(0)))
Zachary Turner5c28c662016-10-03 23:20:36 +00001387 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001388
Zachary Turnera4496982016-10-05 21:14:38 +00001389 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001390
Zachary Turner5c28c662016-10-03 23:20:36 +00001391 if (!option_arg_vector_sp.get()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001392 alias_result = result_str.GetString();
Zachary Turner5c28c662016-10-03 23:20:36 +00001393 return alias_cmd_obj;
1394 }
1395 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001396
Zachary Turner5c28c662016-10-03 23:20:36 +00001397 int value_type;
1398 std::string option;
1399 std::string value;
1400 for (const auto &entry : *option_arg_vector) {
1401 std::tie(option, value_type, value) = entry;
1402 if (option == "<argument>") {
1403 result_str.Printf(" %s", value.c_str());
1404 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001405 }
1406
Zachary Turner5c28c662016-10-03 23:20:36 +00001407 result_str.Printf(" %s", option.c_str());
1408 if (value_type == OptionParser::eNoArgument)
1409 continue;
1410
1411 if (value_type != OptionParser::eOptionalArgument)
1412 result_str.Printf(" ");
1413 int index = GetOptionArgumentPosition(value.c_str());
1414 if (index == 0)
1415 result_str.Printf("%s", value.c_str());
1416 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1417
1418 result.AppendErrorWithFormat("Not enough arguments provided; you "
1419 "need at least %d arguments to use "
1420 "this alias.\n",
1421 index);
1422 result.SetStatus(eReturnStatusFailed);
1423 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001424 } else {
1425 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1426 if (strpos != std::string::npos)
1427 raw_input_string = raw_input_string.erase(
1428 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1429 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001430 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001431 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001432
Zachary Turnerc1564272016-11-16 21:15:24 +00001433 alias_result = result_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001434 return alias_cmd_obj;
1435}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001436
Zachary Turner97206d52017-05-12 04:51:55 +00001437Status CommandInterpreter::PreprocessCommand(std::string &command) {
Adrian Prantl05097242018-04-30 16:49:04 +00001438 // The command preprocessor needs to do things to the command line before any
1439 // parsing of arguments or anything else is done. The only current stuff that
1440 // gets preprocessed is anything enclosed in backtick ('`') characters is
1441 // evaluated as an expression and the result of the expression must be a
1442 // scalar that can be substituted into the command. An example would be:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 // (lldb) memory read `$rsp + 20`
Zachary Turner97206d52017-05-12 04:51:55 +00001444 Status error; // Status for any expressions that might not evaluate
Kate Stoneb9c1b512016-09-06 20:57:50 +00001445 size_t start_backtick;
1446 size_t pos = 0;
1447 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001448 // Stop if an error was encountered during the previous iteration.
1449 if (error.Fail())
1450 break;
1451
Kate Stoneb9c1b512016-09-06 20:57:50 +00001452 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
Adrian Prantl05097242018-04-30 16:49:04 +00001453 // The backtick was preceded by a '\' character, remove the slash and
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001454 // don't treat the backtick as the start of an expression.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001455 command.erase(start_backtick - 1, 1);
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001456 // No need to add one to start_backtick since we just deleted a char.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001457 pos = start_backtick;
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001458 continue;
1459 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001460
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001461 const size_t expr_content_start = start_backtick + 1;
1462 const size_t end_backtick = command.find('`', expr_content_start);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001463
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001464 if (end_backtick == std::string::npos) {
1465 // Stop if there's no end backtick.
1466 break;
1467 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001468
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001469 if (end_backtick == expr_content_start) {
1470 // Skip over empty expression. (two backticks in a row)
1471 command.erase(start_backtick, 2);
1472 continue;
1473 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001474
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001475 std::string expr_str(command, expr_content_start,
1476 end_backtick - expr_content_start);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001477
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001478 ExecutionContext exe_ctx(GetExecutionContext());
1479 Target *target = exe_ctx.GetTargetPtr();
1480
1481 // Get a dummy target to allow for calculator mode while processing
1482 // backticks. This also helps break the infinite loop caused when target is
1483 // null.
1484 if (!target)
1485 target = m_debugger.GetDummyTarget();
1486
1487 if (!target)
1488 continue;
1489
1490 ValueObjectSP expr_result_valobj_sp;
1491
1492 EvaluateExpressionOptions options;
1493 options.SetCoerceToId(false);
1494 options.SetUnwindOnError(true);
1495 options.SetIgnoreBreakpoints(true);
1496 options.SetKeepInMemory(false);
1497 options.SetTryAllThreads(true);
1498 options.SetTimeout(llvm::None);
1499
1500 ExpressionResults expr_result =
1501 target->EvaluateExpression(expr_str.c_str(), exe_ctx.GetFramePtr(),
1502 expr_result_valobj_sp, options);
1503
1504 if (expr_result == eExpressionCompleted) {
1505 Scalar scalar;
1506 if (expr_result_valobj_sp)
1507 expr_result_valobj_sp =
1508 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1509 expr_result_valobj_sp->GetDynamicValueType(), true);
1510 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1511 command.erase(start_backtick, end_backtick - start_backtick + 1);
1512 StreamString value_strm;
1513 const bool show_type = false;
1514 scalar.GetValue(&value_strm, show_type);
1515 size_t value_string_size = value_strm.GetSize();
1516 if (value_string_size) {
1517 command.insert(start_backtick, value_strm.GetString());
1518 pos = start_backtick + value_string_size;
1519 continue;
1520 } else {
1521 error.SetErrorStringWithFormat("expression value didn't result "
1522 "in a scalar value for the "
1523 "expression '%s'",
1524 expr_str.c_str());
1525 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001526 }
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001527 } else {
1528 error.SetErrorStringWithFormat("expression value didn't result "
1529 "in a scalar value for the "
1530 "expression '%s'",
1531 expr_str.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001532 break;
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001533 }
1534
1535 continue;
1536 }
1537
1538 if (expr_result_valobj_sp)
1539 error = expr_result_valobj_sp->GetError();
1540
1541 if (error.Success()) {
1542 switch (expr_result) {
1543 case eExpressionSetupError:
1544 error.SetErrorStringWithFormat(
1545 "expression setup error for the expression '%s'", expr_str.c_str());
1546 break;
1547 case eExpressionParseError:
1548 error.SetErrorStringWithFormat(
1549 "expression parse error for the expression '%s'", expr_str.c_str());
1550 break;
1551 case eExpressionResultUnavailable:
1552 error.SetErrorStringWithFormat(
1553 "expression error fetching result for the expression '%s'",
1554 expr_str.c_str());
1555 break;
1556 case eExpressionCompleted:
1557 break;
1558 case eExpressionDiscarded:
1559 error.SetErrorStringWithFormat(
1560 "expression discarded for the expression '%s'", expr_str.c_str());
1561 break;
1562 case eExpressionInterrupted:
1563 error.SetErrorStringWithFormat(
1564 "expression interrupted for the expression '%s'", expr_str.c_str());
1565 break;
1566 case eExpressionHitBreakpoint:
1567 error.SetErrorStringWithFormat(
1568 "expression hit breakpoint for the expression '%s'",
1569 expr_str.c_str());
1570 break;
1571 case eExpressionTimedOut:
1572 error.SetErrorStringWithFormat(
1573 "expression timed out for the expression '%s'", expr_str.c_str());
1574 break;
1575 case eExpressionStoppedForDebug:
1576 error.SetErrorStringWithFormat("expression stop at entry point "
1577 "for debugging for the "
1578 "expression '%s'",
1579 expr_str.c_str());
1580 break;
1581 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001582 }
1583 }
1584 return error;
1585}
1586
1587bool CommandInterpreter::HandleCommand(const char *command_line,
1588 LazyBool lazy_add_to_history,
1589 CommandReturnObject &result,
1590 ExecutionContext *override_context,
1591 bool repeat_on_empty_command,
1592 bool no_context_switching)
1593
1594{
1595
1596 std::string command_string(command_line);
1597 std::string original_command_string(command_line);
1598
1599 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
Jim Ingham8f7db522016-12-15 00:30:30 +00001600 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
Sean Callanan237c3ed2016-12-14 21:31:31 +00001601 command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001602
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001603 LLDB_LOGF(log, "Processing command: %s", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001604
Pavel Labathf9d16472017-05-15 13:02:37 +00001605 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1606 Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001607
1608 if (!no_context_switching)
1609 UpdateExecutionContext(override_context);
1610
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001611 if (WasInterrupted()) {
1612 result.AppendError("interrupted");
1613 result.SetStatus(eReturnStatusFailed);
1614 return false;
1615 }
1616
Kate Stoneb9c1b512016-09-06 20:57:50 +00001617 bool add_to_history;
1618 if (lazy_add_to_history == eLazyBoolCalculate)
1619 add_to_history = (m_command_source_depth == 0);
1620 else
1621 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1622
1623 bool empty_command = false;
1624 bool comment_command = false;
1625 if (command_string.empty())
1626 empty_command = true;
1627 else {
1628 const char *k_space_characters = "\t\n\v\f\r ";
1629
1630 size_t non_space = command_string.find_first_not_of(k_space_characters);
Adrian Prantl05097242018-04-30 16:49:04 +00001631 // Check for empty line or comment line (lines whose first non-space
1632 // character is the comment character for this interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001633 if (non_space == std::string::npos)
1634 empty_command = true;
1635 else if (command_string[non_space] == m_comment_char)
1636 comment_command = true;
1637 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001638 llvm::StringRef search_str(command_string);
1639 search_str = search_str.drop_front(non_space);
1640 if (auto hist_str = m_command_history.FindString(search_str)) {
1641 add_to_history = false;
1642 command_string = *hist_str;
1643 original_command_string = *hist_str;
1644 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001645 result.AppendErrorWithFormat("Could not find entry: %s in history",
1646 command_string.c_str());
1647 result.SetStatus(eReturnStatusFailed);
1648 return false;
1649 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001650 }
1651 }
1652
1653 if (empty_command) {
1654 if (repeat_on_empty_command) {
1655 if (m_command_history.IsEmpty()) {
1656 result.AppendError("empty command");
1657 result.SetStatus(eReturnStatusFailed);
1658 return false;
1659 } else {
1660 command_line = m_repeat_command.c_str();
1661 command_string = command_line;
1662 original_command_string = command_line;
1663 if (m_repeat_command.empty()) {
1664 result.AppendErrorWithFormat("No auto repeat.\n");
1665 result.SetStatus(eReturnStatusFailed);
1666 return false;
1667 }
1668 }
1669 add_to_history = false;
1670 } else {
1671 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1672 return true;
1673 }
1674 } else if (comment_command) {
1675 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1676 return true;
1677 }
1678
Zachary Turner97206d52017-05-12 04:51:55 +00001679 Status error(PreprocessCommand(command_string));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001680
1681 if (error.Fail()) {
1682 result.AppendError(error.AsCString());
1683 result.SetStatus(eReturnStatusFailed);
1684 return false;
1685 }
1686
1687 // Phase 1.
1688
1689 // Before we do ANY kind of argument processing, we need to figure out what
1690 // the real/final command object is for the specified command. This gets
1691 // complicated by the fact that the user could have specified an alias, and,
1692 // in translating the alias, there may also be command options and/or even
1693 // data (including raw text strings) that need to be found and inserted into
1694 // the command line as part of the translation. So this first step is plain
1695 // look-up and replacement, resulting in:
1696 // 1. the command object whose Execute method will actually be called
1697 // 2. a revised command string, with all substitutions and replacements
1698 // taken care of
1699 // From 1 above, we can determine whether the Execute function wants raw
1700 // input or not.
1701
1702 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1703
1704 // Although the user may have abbreviated the command, the command_string now
Adrian Prantl05097242018-04-30 16:49:04 +00001705 // has the command expanded to the full name. For example, if the input was
1706 // "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001707 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001708 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001709 LLDB_LOGF(log, "HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
1710 LLDB_LOGF(log, "HandleCommand, (revised) command_string: '%s'",
1711 command_string.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001712 const bool wants_raw_input =
Konrad Kleine248a1302019-05-23 11:14:47 +00001713 (cmd_obj != nullptr) ? cmd_obj->WantsRawCommandString() : false;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001714 LLDB_LOGF(log, "HandleCommand, wants_raw_input:'%s'",
1715 wants_raw_input ? "True" : "False");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001716 }
1717
1718 // Phase 2.
1719 // Take care of things like setting up the history command & calling the
Adrian Prantl05097242018-04-30 16:49:04 +00001720 // appropriate Execute method on the CommandObject, with the appropriate
1721 // arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001722
1723 if (cmd_obj != nullptr) {
1724 if (add_to_history) {
1725 Args command_args(command_string);
1726 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1727 if (repeat_command != nullptr)
1728 m_repeat_command.assign(repeat_command);
1729 else
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001730 m_repeat_command.assign(original_command_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001731
1732 m_command_history.AppendString(original_command_string);
1733 }
1734
1735 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001736 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001737 if (actual_cmd_name_len < command_string.length())
1738 remainder = command_string.substr(actual_cmd_name_len);
1739
1740 // Remove any initial spaces
1741 size_t pos = remainder.find_first_not_of(k_white_space);
1742 if (pos != 0 && pos != std::string::npos)
1743 remainder.erase(0, pos);
1744
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001745 LLDB_LOGF(
1746 log, "HandleCommand, command line after removing command name(s): '%s'",
1747 remainder.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001748
1749 cmd_obj->Execute(remainder.c_str(), result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001750 }
1751
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001752 LLDB_LOGF(log, "HandleCommand, command %s",
1753 (result.Succeeded() ? "succeeded" : "did not succeed"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001754
1755 return result.Succeeded();
1756}
1757
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001758int CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001759 int num_command_matches = 0;
1760 bool look_for_subcommand = false;
1761
1762 // For any of the command completions a unique match will be a complete word.
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001763 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001764
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001765 if (request.GetCursorIndex() == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001766 // We got nothing on the command line, so return the list of commands
1767 bool include_aliases = true;
Raphael Isemann7f888292018-09-13 21:26:00 +00001768 StringList new_matches, descriptions;
1769 num_command_matches = GetCommandNamesMatchingPartialString(
1770 "", include_aliases, new_matches, descriptions);
1771 request.AddCompletions(new_matches, descriptions);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001772 } else if (request.GetCursorIndex() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001773 // The cursor is in the first argument, so just do a lookup in the
1774 // dictionary.
Raphael Isemann7f888292018-09-13 21:26:00 +00001775 StringList new_matches, new_descriptions;
1776 CommandObject *cmd_obj =
1777 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0),
1778 &new_matches, &new_descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001779
1780 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001781 new_matches.GetStringAtIndex(0) != nullptr &&
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001782 strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001783 new_matches.GetStringAtIndex(0)) == 0) {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001784 if (request.GetParsedLine().GetArgumentCount() == 1) {
1785 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001786 } else {
1787 look_for_subcommand = true;
1788 num_command_matches = 0;
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001789 new_matches.DeleteStringAtIndex(0);
Raphael Isemann7f888292018-09-13 21:26:00 +00001790 new_descriptions.DeleteStringAtIndex(0);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001791 request.GetParsedLine().AppendArgument(llvm::StringRef());
1792 request.SetCursorIndex(request.GetCursorIndex() + 1);
1793 request.SetCursorCharPosition(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001794 }
1795 }
Raphael Isemann7f888292018-09-13 21:26:00 +00001796 request.AddCompletions(new_matches, new_descriptions);
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001797 num_command_matches = request.GetNumberOfMatches();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001798 }
1799
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001800 if (request.GetCursorIndex() > 0 || look_for_subcommand) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001801 // We are completing further on into a commands arguments, so find the
Adrian Prantl05097242018-04-30 16:49:04 +00001802 // command and tell it to complete the command. First see if there is a
1803 // matching initial command:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001804 CommandObject *command_object =
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001805 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001806 if (command_object == nullptr) {
1807 return 0;
1808 } else {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001809 request.GetParsedLine().Shift();
1810 request.SetCursorIndex(request.GetCursorIndex() - 1);
1811 num_command_matches = command_object->HandleCompletion(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001812 }
1813 }
1814
1815 return num_command_matches;
1816}
1817
1818int CommandInterpreter::HandleCompletion(
1819 const char *current_line, const char *cursor, const char *last_char,
Raphael Isemann7f888292018-09-13 21:26:00 +00001820 int match_start_point, int max_return_elements, StringList &matches,
1821 StringList &descriptions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001822
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001823 llvm::StringRef command_line(current_line, last_char - current_line);
Raphael Isemann7f888292018-09-13 21:26:00 +00001824 CompletionResult result;
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001825 CompletionRequest request(command_line, cursor - current_line,
Raphael Isemann7f888292018-09-13 21:26:00 +00001826 match_start_point, max_return_elements, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001827 // Don't complete comments, and if the line we are completing is just the
Adrian Prantl05097242018-04-30 16:49:04 +00001828 // history repeat character, substitute the appropriate history line.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001829 const char *first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001830 if (first_arg) {
1831 if (first_arg[0] == m_comment_char)
1832 return 0;
1833 else if (first_arg[0] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001834 if (auto hist_str = m_command_history.FindString(first_arg)) {
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001835 matches.InsertStringAtIndex(0, *hist_str);
Raphael Isemann7f888292018-09-13 21:26:00 +00001836 descriptions.InsertStringAtIndex(0, "Previous command history event");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001837 return -2;
1838 } else
1839 return 0;
1840 }
1841 }
1842
Kate Stoneb9c1b512016-09-06 20:57:50 +00001843 // Only max_return_elements == -1 is supported at present:
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001844 lldbassert(max_return_elements == -1);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001845
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001846 int num_command_matches = HandleCompletionMatches(request);
Raphael Isemann7f888292018-09-13 21:26:00 +00001847 result.GetMatches(matches);
1848 result.GetDescriptions(descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001849
1850 if (num_command_matches <= 0)
1851 return num_command_matches;
1852
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001853 if (request.GetParsedLine().GetArgumentCount() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001854 // If we got an empty string, insert nothing.
1855 matches.InsertStringAtIndex(0, "");
Raphael Isemann7f888292018-09-13 21:26:00 +00001856 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001857 } else {
1858 // Now figure out if there is a common substring, and if so put that in
Adrian Prantl05097242018-04-30 16:49:04 +00001859 // element 0, otherwise put an empty string in element 0.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001860 std::string command_partial_str = request.GetCursorArgumentPrefix().str();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001861
1862 std::string common_prefix;
1863 matches.LongestCommonPrefix(common_prefix);
1864 const size_t partial_name_len = command_partial_str.size();
1865 common_prefix.erase(0, partial_name_len);
1866
Adrian Prantl05097242018-04-30 16:49:04 +00001867 // If we matched a unique single command, add a space... Only do this if
1868 // the completer told us this was a complete word, however...
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001869 if (num_command_matches == 1 && request.GetWordComplete()) {
1870 char quote_char = request.GetParsedLine()[request.GetCursorIndex()].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001871 common_prefix =
1872 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1873 if (quote_char != '\0')
1874 common_prefix.push_back(quote_char);
1875 common_prefix.push_back(' ');
1876 }
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001877 matches.InsertStringAtIndex(0, common_prefix.c_str());
Raphael Isemann7f888292018-09-13 21:26:00 +00001878 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001879 }
1880 return num_command_matches;
1881}
1882
1883CommandInterpreter::~CommandInterpreter() {}
1884
Zachary Turner514d8cd2016-09-23 18:06:53 +00001885void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001886 EventSP prompt_change_event_sp(
1887 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1888 ;
1889 BroadcastEvent(prompt_change_event_sp);
1890 if (m_command_io_handler_sp)
1891 m_command_io_handler_sp->SetPrompt(new_prompt);
1892}
1893
Zachary Turner7a120c82016-11-13 03:05:58 +00001894bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001895 // Check AutoConfirm first:
1896 if (m_debugger.GetAutoConfirm())
1897 return default_answer;
1898
1899 IOHandlerConfirm *confirm =
1900 new IOHandlerConfirm(m_debugger, message, default_answer);
1901 IOHandlerSP io_handler_sp(confirm);
1902 m_debugger.RunIOHandler(io_handler_sp);
1903 return confirm->GetResponse();
1904}
1905
Zachary Turnera483f572016-10-05 21:14:49 +00001906const CommandAlias *
1907CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001908 OptionArgVectorSP ret_val;
1909
Zachary Turnera483f572016-10-05 21:14:49 +00001910 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001911 if (pos != m_alias_dict.end())
1912 return (CommandAlias *)pos->second.get();
1913
1914 return nullptr;
1915}
1916
Zachary Turnera4496982016-10-05 21:14:38 +00001917bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001918
Zachary Turnera4496982016-10-05 21:14:38 +00001919bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001920
Zachary Turnera4496982016-10-05 21:14:38 +00001921bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001922
Zachary Turnera4496982016-10-05 21:14:38 +00001923bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001924
1925void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1926 const char *alias_name,
1927 Args &cmd_args,
1928 std::string &raw_input_string,
1929 CommandReturnObject &result) {
1930 OptionArgVectorSP option_arg_vector_sp =
1931 GetAlias(alias_name)->GetOptionArguments();
1932
1933 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1934
1935 // Make sure that the alias name is the 0th element in cmd_args
1936 std::string alias_name_str = alias_name;
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001937 if (alias_name_str != cmd_args.GetArgumentAtIndex(0))
Zachary Turner5c725f32016-09-19 21:56:59 +00001938 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001939
1940 Args new_args(alias_cmd_obj->GetCommandName());
1941 if (new_args.GetArgumentCount() == 2)
1942 new_args.Shift();
1943
1944 if (option_arg_vector_sp.get()) {
1945 if (wants_raw_input) {
1946 // We have a command that both has command options and takes raw input.
Adrian Prantl05097242018-04-30 16:49:04 +00001947 // Make *sure* it has a " -- " in the right place in the
1948 // raw_input_string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001949 size_t pos = raw_input_string.find(" -- ");
1950 if (pos == std::string::npos) {
1951 // None found; assume it goes at the beginning of the raw input string
1952 raw_input_string.insert(0, " -- ");
1953 }
1954 }
1955
1956 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1957 const size_t old_size = cmd_args.GetArgumentCount();
1958 std::vector<bool> used(old_size + 1, false);
1959
1960 used[0] = true;
1961
Zachary Turner5c28c662016-10-03 23:20:36 +00001962 int value_type;
1963 std::string option;
1964 std::string value;
1965 for (const auto &option_entry : *option_arg_vector) {
1966 std::tie(option, value_type, value) = option_entry;
1967 if (option == "<argument>") {
1968 if (!wants_raw_input || (value != "--")) {
1969 // Since we inserted this above, make sure we don't insert it twice
1970 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001971 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001972 continue;
1973 }
1974
1975 if (value_type != OptionParser::eOptionalArgument)
1976 new_args.AppendArgument(option);
1977
1978 if (value == "<no-argument>")
1979 continue;
1980
1981 int index = GetOptionArgumentPosition(value.c_str());
1982 if (index == 0) {
1983 // value was NOT a positional argument; must be a real value
1984 if (value_type != OptionParser::eOptionalArgument)
1985 new_args.AppendArgument(value);
1986 else {
1987 char buffer[255];
1988 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1989 value.c_str());
1990 new_args.AppendArgument(llvm::StringRef(buffer));
1991 }
1992
1993 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1994 result.AppendErrorWithFormat("Not enough arguments provided; you "
1995 "need at least %d arguments to use "
1996 "this alias.\n",
1997 index);
1998 result.SetStatus(eReturnStatusFailed);
1999 return;
2000 } else {
2001 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2002 size_t strpos =
2003 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
2004 if (strpos != std::string::npos) {
2005 raw_input_string = raw_input_string.erase(
2006 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2007 }
2008
2009 if (value_type != OptionParser::eOptionalArgument)
2010 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2011 else {
2012 char buffer[255];
2013 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2014 cmd_args.GetArgumentAtIndex(index));
2015 new_args.AppendArgument(buffer);
2016 }
2017 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002018 }
2019 }
2020
Zachary Turner97d2c402016-10-05 23:40:23 +00002021 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00002022 if (!used[entry.index()] && !wants_raw_input)
2023 new_args.AppendArgument(entry.value().ref);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002024 }
2025
2026 cmd_args.Clear();
2027 cmd_args.SetArguments(new_args.GetArgumentCount(),
2028 new_args.GetConstArgumentVector());
2029 } else {
2030 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2031 // This alias was not created with any options; nothing further needs to be
Adrian Prantl05097242018-04-30 16:49:04 +00002032 // done, unless it is a command that wants raw input, in which case we need
2033 // to clear the rest of the data from cmd_args, since its in the raw input
2034 // string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002035 if (wants_raw_input) {
2036 cmd_args.Clear();
2037 cmd_args.SetArguments(new_args.GetArgumentCount(),
2038 new_args.GetConstArgumentVector());
2039 }
2040 return;
2041 }
2042
2043 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2044 return;
2045}
2046
2047int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2048 int position = 0; // Any string that isn't an argument position, i.e. '%'
2049 // followed by an integer, gets a position
2050 // of zero.
2051
2052 const char *cptr = in_string;
2053
2054 // Does it start with '%'
2055 if (cptr[0] == '%') {
2056 ++cptr;
2057
2058 // Is the rest of it entirely digits?
2059 if (isdigit(cptr[0])) {
2060 const char *start = cptr;
2061 while (isdigit(cptr[0]))
2062 ++cptr;
2063
Adrian Prantl05097242018-04-30 16:49:04 +00002064 // We've gotten to the end of the digits; are we at the end of the
2065 // string?
Kate Stoneb9c1b512016-09-06 20:57:50 +00002066 if (cptr[0] == '\0')
2067 position = atoi(start);
2068 }
2069 }
2070
2071 return position;
2072}
2073
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002074static void GetHomeInitFile(llvm::SmallVectorImpl<char> &init_file,
2075 llvm::StringRef suffix = {}) {
2076 std::string init_file_name = ".lldbinit";
2077 if (!suffix.empty()) {
2078 init_file_name.append("-");
2079 init_file_name.append(suffix.str());
2080 }
2081
2082 llvm::sys::path::home_directory(init_file);
2083 llvm::sys::path::append(init_file, init_file_name);
2084
2085 FileSystem::Instance().Resolve(init_file);
2086}
2087
2088static void GetCwdInitFile(llvm::SmallVectorImpl<char> &init_file) {
2089 llvm::StringRef s = ".lldbinit";
2090 init_file.assign(s.begin(), s.end());
2091 FileSystem::Instance().Resolve(init_file);
2092}
2093
2094static LoadCWDlldbinitFile ShouldLoadCwdInitFile() {
2095 lldb::TargetPropertiesSP properties = Target::GetGlobalProperties();
2096 if (!properties)
2097 return eLoadCWDlldbinitFalse;
2098 return properties->GetLoadCWDlldbinitFile();
2099}
2100
2101void CommandInterpreter::SourceInitFile(FileSpec file,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002102 CommandReturnObject &result) {
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002103 assert(!m_skip_lldbinit_files);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002104
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002105 if (!FileSystem::Instance().Exists(file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002106 result.SetStatus(eReturnStatusSuccessFinishNoResult);
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002107 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002108 }
Jonas Devlieghere2fc6b022019-05-17 22:53:04 +00002109
2110 // Use HandleCommand to 'source' the given file; this will do the actual
2111 // broadcasting of the commands back to any appropriate listener (see
2112 // CommandObjectSource::Execute for more details).
2113 const bool saved_batch = SetBatchCommandMode(true);
2114 ExecutionContext *ctx = nullptr;
2115 CommandInterpreterRunOptions options;
2116 options.SetSilent(true);
2117 options.SetPrintErrors(true);
2118 options.SetStopOnError(false);
2119 options.SetStopOnContinue(true);
2120 HandleCommandsFromFile(file, ctx, options, result);
2121 SetBatchCommandMode(saved_batch);
2122}
2123
2124void CommandInterpreter::SourceInitFileCwd(CommandReturnObject &result) {
2125 if (m_skip_lldbinit_files) {
2126 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2127 return;
2128 }
2129
2130 llvm::SmallString<128> init_file;
2131 GetCwdInitFile(init_file);
2132 if (!FileSystem::Instance().Exists(init_file)) {
2133 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2134 return;
2135 }
2136
2137 LoadCWDlldbinitFile should_load = ShouldLoadCwdInitFile();
2138
2139 switch (should_load) {
2140 case eLoadCWDlldbinitFalse:
2141 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2142 break;
2143 case eLoadCWDlldbinitTrue:
2144 SourceInitFile(FileSpec(init_file.str()), result);
2145 break;
2146 case eLoadCWDlldbinitWarn: {
2147 llvm::SmallString<128> home_init_file;
2148 GetHomeInitFile(home_init_file);
2149 if (llvm::sys::path::parent_path(init_file) ==
2150 llvm::sys::path::parent_path(home_init_file)) {
2151 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2152 } else {
2153 result.AppendErrorWithFormat(InitFileWarning);
2154 result.SetStatus(eReturnStatusFailed);
2155 }
2156 }
2157 }
2158}
2159
2160/// We will first see if there is an application specific ".lldbinit" file
2161/// whose name is "~/.lldbinit" followed by a "-" and the name of the program.
2162/// If this file doesn't exist, we fall back to just the "~/.lldbinit" file.
2163void CommandInterpreter::SourceInitFileHome(CommandReturnObject &result) {
2164 if (m_skip_lldbinit_files) {
2165 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2166 return;
2167 }
2168
2169 llvm::SmallString<128> init_file;
2170 GetHomeInitFile(init_file);
2171
2172 if (!m_skip_app_init_files) {
2173 llvm::StringRef program_name =
2174 HostInfo::GetProgramFileSpec().GetFilename().GetStringRef();
2175 llvm::SmallString<128> program_init_file;
2176 GetHomeInitFile(program_init_file, program_name);
2177 if (FileSystem::Instance().Exists(program_init_file))
2178 init_file = program_init_file;
2179 }
2180
2181 SourceInitFile(FileSpec(init_file.str()), result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002182}
2183
2184const char *CommandInterpreter::GetCommandPrefix() {
2185 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
Konrad Kleine248a1302019-05-23 11:14:47 +00002186 return prefix == nullptr ? "" : prefix;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002187}
2188
2189PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2190 PlatformSP platform_sp;
2191 if (prefer_target_platform) {
2192 ExecutionContext exe_ctx(GetExecutionContext());
2193 Target *target = exe_ctx.GetTargetPtr();
2194 if (target)
2195 platform_sp = target->GetPlatform();
2196 }
2197
2198 if (!platform_sp)
2199 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2200 return platform_sp;
2201}
2202
2203void CommandInterpreter::HandleCommands(const StringList &commands,
2204 ExecutionContext *override_context,
2205 CommandInterpreterRunOptions &options,
2206 CommandReturnObject &result) {
2207 size_t num_lines = commands.GetSize();
2208
2209 // If we are going to continue past a "continue" then we need to run the
Adrian Prantl05097242018-04-30 16:49:04 +00002210 // commands synchronously. Make sure you reset this value anywhere you return
2211 // from the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002212
2213 bool old_async_execution = m_debugger.GetAsyncExecution();
2214
2215 // If we've been given an execution context, set it at the start, but don't
Adrian Prantl05097242018-04-30 16:49:04 +00002216 // keep resetting it or we will cause series of commands that change the
2217 // context, then do an operation that relies on that context to fail.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002218
2219 if (override_context != nullptr)
2220 UpdateExecutionContext(override_context);
2221
2222 if (!options.GetStopOnContinue()) {
2223 m_debugger.SetAsyncExecution(false);
2224 }
2225
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002226 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002227 const char *cmd = commands.GetStringAtIndex(idx);
2228 if (cmd[0] == '\0')
2229 continue;
2230
2231 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002232 // TODO: Add Stream support.
2233 result.AppendMessageWithFormat("%s %s\n",
2234 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 }
2236
2237 CommandReturnObject tmp_result;
2238 // If override_context is not NULL, pass no_context_switching = true for
2239 // HandleCommand() since we updated our context already.
2240
2241 // We might call into a regex or alias command, in which case the
Adrian Prantl05097242018-04-30 16:49:04 +00002242 // add_to_history will get lost. This m_command_source_depth dingus is the
2243 // way we turn off adding to the history in that case, so set it up here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002244 if (!options.GetAddToHistory())
2245 m_command_source_depth++;
2246 bool success =
2247 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2248 nullptr, /* override_context */
2249 true, /* repeat_on_empty_command */
2250 override_context != nullptr /* no_context_switching */);
2251 if (!options.GetAddToHistory())
2252 m_command_source_depth--;
2253
2254 if (options.GetPrintResults()) {
2255 if (tmp_result.Succeeded())
Zachary Turner03c9f362016-11-14 23:23:31 +00002256 result.AppendMessage(tmp_result.GetOutputData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002257 }
2258
2259 if (!success || !tmp_result.Succeeded()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002260 llvm::StringRef error_msg = tmp_result.GetErrorData();
2261 if (error_msg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002262 error_msg = "<unknown error>.\n";
2263 if (options.GetStopOnError()) {
2264 result.AppendErrorWithFormat(
2265 "Aborting reading of commands after command #%" PRIu64
2266 ": '%s' failed with %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00002267 (uint64_t)idx, cmd, error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002268 result.SetStatus(eReturnStatusFailed);
2269 m_debugger.SetAsyncExecution(old_async_execution);
2270 return;
2271 } else if (options.GetPrintResults()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002272 result.AppendMessageWithFormat(
2273 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2274 error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002275 }
2276 }
2277
2278 if (result.GetImmediateOutputStream())
2279 result.GetImmediateOutputStream()->Flush();
2280
2281 if (result.GetImmediateErrorStream())
2282 result.GetImmediateErrorStream()->Flush();
2283
Adrian Prantl05097242018-04-30 16:49:04 +00002284 // N.B. Can't depend on DidChangeProcessState, because the state coming
2285 // into the command execution could be running (for instance in Breakpoint
2286 // Commands. So we check the return value to see if it is has running in
2287 // it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002288 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2289 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2290 if (options.GetStopOnContinue()) {
2291 // If we caused the target to proceed, and we're going to stop in that
Adrian Prantl05097242018-04-30 16:49:04 +00002292 // case, set the status in our real result before returning. This is
2293 // an error if the continue was not the last command in the set of
2294 // commands to be run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002295 if (idx != num_lines - 1)
2296 result.AppendErrorWithFormat(
2297 "Aborting reading of commands after command #%" PRIu64
2298 ": '%s' continued the target.\n",
2299 (uint64_t)idx + 1, cmd);
2300 else
2301 result.AppendMessageWithFormat("Command #%" PRIu64
2302 " '%s' continued the target.\n",
2303 (uint64_t)idx + 1, cmd);
2304
2305 result.SetStatus(tmp_result.GetStatus());
2306 m_debugger.SetAsyncExecution(old_async_execution);
2307
2308 return;
2309 }
2310 }
2311
2312 // Also check for "stop on crash here:
2313 bool should_stop = false;
2314 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2315 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2316 if (target_sp) {
2317 ProcessSP process_sp(target_sp->GetProcessSP());
2318 if (process_sp) {
2319 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2320 StopReason reason = thread_sp->GetStopReason();
2321 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2322 reason == eStopReasonInstrumentation) {
2323 should_stop = true;
2324 break;
2325 }
2326 }
2327 }
2328 }
2329 if (should_stop) {
2330 if (idx != num_lines - 1)
2331 result.AppendErrorWithFormat(
2332 "Aborting reading of commands after command #%" PRIu64
2333 ": '%s' stopped with a signal or exception.\n",
2334 (uint64_t)idx + 1, cmd);
2335 else
2336 result.AppendMessageWithFormat(
2337 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2338 (uint64_t)idx + 1, cmd);
2339
2340 result.SetStatus(tmp_result.GetStatus());
2341 m_debugger.SetAsyncExecution(old_async_execution);
2342
2343 return;
2344 }
2345 }
2346 }
2347
2348 result.SetStatus(eReturnStatusSuccessFinishResult);
2349 m_debugger.SetAsyncExecution(old_async_execution);
2350
2351 return;
2352}
2353
2354// Make flags that we can pass into the IOHandler so our delegates can do the
2355// right thing
2356enum {
2357 eHandleCommandFlagStopOnContinue = (1u << 0),
2358 eHandleCommandFlagStopOnError = (1u << 1),
2359 eHandleCommandFlagEchoCommand = (1u << 2),
Stefan Granitzc678ed72018-10-05 16:49:47 +00002360 eHandleCommandFlagEchoCommentCommand = (1u << 3),
2361 eHandleCommandFlagPrintResult = (1u << 4),
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002362 eHandleCommandFlagPrintErrors = (1u << 5),
2363 eHandleCommandFlagStopOnCrash = (1u << 6)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002364};
2365
2366void CommandInterpreter::HandleCommandsFromFile(
2367 FileSpec &cmd_file, ExecutionContext *context,
2368 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002369 if (!FileSystem::Instance().Exists(cmd_file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002370 result.AppendErrorWithFormat(
2371 "Error reading commands from file %s - file not found.\n",
2372 cmd_file.GetFilename().AsCString("<Unknown>"));
2373 result.SetStatus(eReturnStatusFailed);
2374 return;
2375 }
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002376
2377 StreamFileSP input_file_sp(new StreamFile());
2378 std::string cmd_file_path = cmd_file.GetPath();
2379 Status error = FileSystem::Instance().Open(input_file_sp->GetFile(), cmd_file,
2380 File::eOpenOptionRead);
2381
2382 if (error.Fail()) {
2383 result.AppendErrorWithFormat(
2384 "error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(),
2385 error.AsCString());
2386 result.SetStatus(eReturnStatusFailed);
2387 return;
2388 }
2389
2390 Debugger &debugger = GetDebugger();
2391
2392 uint32_t flags = 0;
2393
2394 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2395 if (m_command_source_flags.empty()) {
2396 // Stop on continue by default
2397 flags |= eHandleCommandFlagStopOnContinue;
2398 } else if (m_command_source_flags.back() &
2399 eHandleCommandFlagStopOnContinue) {
2400 flags |= eHandleCommandFlagStopOnContinue;
2401 }
2402 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2403 flags |= eHandleCommandFlagStopOnContinue;
2404 }
2405
2406 if (options.m_stop_on_error == eLazyBoolCalculate) {
2407 if (m_command_source_flags.empty()) {
2408 if (GetStopCmdSourceOnError())
2409 flags |= eHandleCommandFlagStopOnError;
2410 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) {
2411 flags |= eHandleCommandFlagStopOnError;
2412 }
2413 } else if (options.m_stop_on_error == eLazyBoolYes) {
2414 flags |= eHandleCommandFlagStopOnError;
2415 }
2416
2417 // stop-on-crash can only be set, if it is present in all levels of
2418 // pushed flag sets.
2419 if (options.GetStopOnCrash()) {
2420 if (m_command_source_flags.empty()) {
2421 flags |= eHandleCommandFlagStopOnCrash;
2422 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) {
2423 flags |= eHandleCommandFlagStopOnCrash;
2424 }
2425 }
2426
2427 if (options.m_echo_commands == eLazyBoolCalculate) {
2428 if (m_command_source_flags.empty()) {
2429 // Echo command by default
2430 flags |= eHandleCommandFlagEchoCommand;
2431 } else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) {
2432 flags |= eHandleCommandFlagEchoCommand;
2433 }
2434 } else if (options.m_echo_commands == eLazyBoolYes) {
2435 flags |= eHandleCommandFlagEchoCommand;
2436 }
2437
2438 // We will only ever ask for this flag, if we echo commands in general.
2439 if (options.m_echo_comment_commands == eLazyBoolCalculate) {
2440 if (m_command_source_flags.empty()) {
2441 // Echo comments by default
2442 flags |= eHandleCommandFlagEchoCommentCommand;
2443 } else if (m_command_source_flags.back() &
2444 eHandleCommandFlagEchoCommentCommand) {
2445 flags |= eHandleCommandFlagEchoCommentCommand;
2446 }
2447 } else if (options.m_echo_comment_commands == eLazyBoolYes) {
2448 flags |= eHandleCommandFlagEchoCommentCommand;
2449 }
2450
2451 if (options.m_print_results == eLazyBoolCalculate) {
2452 if (m_command_source_flags.empty()) {
2453 // Print output by default
2454 flags |= eHandleCommandFlagPrintResult;
2455 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) {
2456 flags |= eHandleCommandFlagPrintResult;
2457 }
2458 } else if (options.m_print_results == eLazyBoolYes) {
2459 flags |= eHandleCommandFlagPrintResult;
2460 }
2461
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002462 if (options.m_print_errors == eLazyBoolCalculate) {
2463 if (m_command_source_flags.empty()) {
2464 // Print output by default
2465 flags |= eHandleCommandFlagPrintErrors;
2466 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintErrors) {
2467 flags |= eHandleCommandFlagPrintErrors;
2468 }
2469 } else if (options.m_print_errors == eLazyBoolYes) {
2470 flags |= eHandleCommandFlagPrintErrors;
2471 }
2472
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002473 if (flags & eHandleCommandFlagPrintResult) {
2474 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2475 cmd_file_path.c_str());
2476 }
2477
2478 // Used for inheriting the right settings when "command source" might
2479 // have nested "command source" commands
2480 lldb::StreamFileSP empty_stream_sp;
2481 m_command_source_flags.push_back(flags);
2482 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2483 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2484 empty_stream_sp, // Pass in an empty stream so we inherit the top
2485 // input reader output stream
2486 empty_stream_sp, // Pass in an empty stream so we inherit the top
2487 // input reader error stream
2488 flags,
2489 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2490 // or written
2491 debugger.GetPrompt(), llvm::StringRef(),
2492 false, // Not multi-line
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002493 debugger.GetUseColor(), 0, *this, nullptr));
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002494 const bool old_async_execution = debugger.GetAsyncExecution();
2495
2496 // Set synchronous execution if we are not stopping on continue
2497 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2498 debugger.SetAsyncExecution(false);
2499
2500 m_command_source_depth++;
2501
2502 debugger.RunIOHandler(io_handler_sp);
2503 if (!m_command_source_flags.empty())
2504 m_command_source_flags.pop_back();
2505 m_command_source_depth--;
2506 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2507 debugger.SetAsyncExecution(old_async_execution);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002508}
2509
Kate Stoneb9c1b512016-09-06 20:57:50 +00002510bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2511
2512void CommandInterpreter::SetSynchronous(bool value) {
2513 m_synchronous_execution = value;
2514}
2515
2516void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002517 llvm::StringRef prefix,
2518 llvm::StringRef help_text) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002519 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002520
Zachary Turner0ac5f982016-11-08 04:12:42 +00002521 size_t line_width_max = max_columns - prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002522 if (line_width_max < 16)
Zachary Turner0ac5f982016-11-08 04:12:42 +00002523 line_width_max = help_text.size() + prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002524
Zachary Turner0ac5f982016-11-08 04:12:42 +00002525 strm.IndentMore(prefix.size());
2526 bool prefixed_yet = false;
2527 while (!help_text.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002528 // Prefix the first line, indent subsequent lines to line up
Zachary Turner0ac5f982016-11-08 04:12:42 +00002529 if (!prefixed_yet) {
2530 strm << prefix;
2531 prefixed_yet = true;
2532 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002533 strm.Indent();
Zachary Turner0ac5f982016-11-08 04:12:42 +00002534
2535 // Never print more than the maximum on one line.
2536 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2537
2538 // Always break on an explicit newline.
2539 std::size_t first_newline = this_line.find_first_of("\n");
2540
2541 // Don't break on space/tab unless the text is too long to fit on one line.
2542 std::size_t last_space = llvm::StringRef::npos;
2543 if (this_line.size() != help_text.size())
2544 last_space = this_line.find_last_of(" \t");
2545
2546 // Break at whichever condition triggered first.
2547 this_line = this_line.substr(0, std::min(first_newline, last_space));
2548 strm.PutCString(this_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002549 strm.EOL();
2550
Zachary Turner0ac5f982016-11-08 04:12:42 +00002551 // Remove whitespace / newlines after breaking.
2552 help_text = help_text.drop_front(this_line.size()).ltrim();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002553 }
Zachary Turner0ac5f982016-11-08 04:12:42 +00002554 strm.IndentLess(prefix.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002555}
2556
2557void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002558 llvm::StringRef word_text,
2559 llvm::StringRef separator,
2560 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002561 size_t max_word_len) {
2562 StreamString prefix_stream;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002563 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2564 (int)separator.size(), separator.data());
Zachary Turnerc1564272016-11-16 21:15:24 +00002565 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2566}
2567
Zachary Turner0ac5f982016-11-08 04:12:42 +00002568void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2569 llvm::StringRef separator,
2570 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002571 uint32_t max_word_len) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00002572 int indent_size = max_word_len + separator.size() + 2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002573
2574 strm.IndentMore(indent_size);
2575
2576 StreamString text_strm;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002577 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2578 text_strm << separator << " " << help_text;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002579
2580 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2581
Zachary Turnerc1564272016-11-16 21:15:24 +00002582 llvm::StringRef text = text_strm.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002583
2584 uint32_t chars_left = max_columns;
2585
Davide Italianocf8a8292017-04-14 22:36:08 +00002586 auto nextWordLength = [](llvm::StringRef S) {
Jonas Devliegherec712bac2019-03-28 18:10:14 +00002587 size_t pos = S.find(' ');
Davide Italianocf8a8292017-04-14 22:36:08 +00002588 return pos == llvm::StringRef::npos ? S.size() : pos;
2589 };
2590
Zachary Turnerc1564272016-11-16 21:15:24 +00002591 while (!text.empty()) {
2592 if (text.front() == '\n' ||
Jim Inghama81bd7f2017-07-27 00:18:18 +00002593 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002594 strm.EOL();
2595 strm.Indent();
Zachary Turnerc1564272016-11-16 21:15:24 +00002596 chars_left = max_columns - indent_size;
2597 if (text.front() == '\n')
2598 text = text.drop_front();
2599 else
2600 text = text.ltrim(' ');
Kate Stoneb9c1b512016-09-06 20:57:50 +00002601 } else {
Zachary Turnerc1564272016-11-16 21:15:24 +00002602 strm.PutChar(text.front());
2603 --chars_left;
2604 text = text.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002605 }
2606 }
2607
2608 strm.EOL();
2609 strm.IndentLess(indent_size);
2610}
2611
2612void CommandInterpreter::FindCommandsForApropos(
Zachary Turner067d1db2016-11-16 21:45:04 +00002613 llvm::StringRef search_word, StringList &commands_found,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002614 StringList &commands_help, CommandObject::CommandMap &command_map) {
2615 CommandObject::CommandMap::const_iterator pos;
2616
2617 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
Zachary Turner067d1db2016-11-16 21:45:04 +00002618 llvm::StringRef command_name = pos->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002619 CommandObject *cmd_obj = pos->second.get();
2620
2621 const bool search_short_help = true;
2622 const bool search_long_help = false;
2623 const bool search_syntax = false;
2624 const bool search_options = false;
Zachary Turner067d1db2016-11-16 21:45:04 +00002625 if (command_name.contains_lower(search_word) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002626 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2627 search_long_help, search_syntax,
2628 search_options)) {
2629 commands_found.AppendString(cmd_obj->GetCommandName());
2630 commands_help.AppendString(cmd_obj->GetHelp());
2631 }
2632
2633 if (cmd_obj->IsMultiwordObject()) {
2634 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2635 FindCommandsForApropos(search_word, commands_found, commands_help,
2636 cmd_multiword->GetSubcommandDictionary());
2637 }
2638 }
2639}
2640
Zachary Turner067d1db2016-11-16 21:45:04 +00002641void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002642 StringList &commands_found,
2643 StringList &commands_help,
2644 bool search_builtin_commands,
2645 bool search_user_commands,
2646 bool search_alias_commands) {
2647 CommandObject::CommandMap::const_iterator pos;
2648
2649 if (search_builtin_commands)
2650 FindCommandsForApropos(search_word, commands_found, commands_help,
2651 m_command_dict);
2652
2653 if (search_user_commands)
2654 FindCommandsForApropos(search_word, commands_found, commands_help,
2655 m_user_dict);
2656
2657 if (search_alias_commands)
2658 FindCommandsForApropos(search_word, commands_found, commands_help,
2659 m_alias_dict);
2660}
2661
2662void CommandInterpreter::UpdateExecutionContext(
2663 ExecutionContext *override_context) {
2664 if (override_context != nullptr) {
2665 m_exe_ctx_ref = *override_context;
2666 } else {
2667 const bool adopt_selected = true;
2668 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2669 adopt_selected);
2670 }
2671}
2672
2673size_t CommandInterpreter::GetProcessOutput() {
2674 // The process has stuff waiting for stderr; get it and write it out to the
2675 // appropriate place.
2676 char stdio_buffer[1024];
2677 size_t len;
2678 size_t total_bytes = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002679 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002680 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2681 if (target_sp) {
2682 ProcessSP process_sp(target_sp->GetProcessSP());
2683 if (process_sp) {
2684 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2685 error)) > 0) {
2686 size_t bytes_written = len;
2687 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2688 total_bytes += len;
2689 }
2690 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2691 error)) > 0) {
2692 size_t bytes_written = len;
2693 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2694 total_bytes += len;
2695 }
2696 }
2697 }
2698 return total_bytes;
2699}
2700
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002701void CommandInterpreter::StartHandlingCommand() {
2702 auto idle_state = CommandHandlingState::eIdle;
2703 if (m_command_state.compare_exchange_strong(
2704 idle_state, CommandHandlingState::eInProgress))
2705 lldbassert(m_iohandler_nesting_level == 0);
2706 else
2707 lldbassert(m_iohandler_nesting_level > 0);
2708 ++m_iohandler_nesting_level;
2709}
2710
2711void CommandInterpreter::FinishHandlingCommand() {
2712 lldbassert(m_iohandler_nesting_level > 0);
2713 if (--m_iohandler_nesting_level == 0) {
2714 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2715 lldbassert(prev_state != CommandHandlingState::eIdle);
2716 }
2717}
2718
2719bool CommandInterpreter::InterruptCommand() {
2720 auto in_progress = CommandHandlingState::eInProgress;
2721 return m_command_state.compare_exchange_strong(
2722 in_progress, CommandHandlingState::eInterrupted);
2723}
2724
2725bool CommandInterpreter::WasInterrupted() const {
2726 bool was_interrupted =
2727 (m_command_state == CommandHandlingState::eInterrupted);
2728 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2729 return was_interrupted;
2730}
2731
2732void CommandInterpreter::PrintCommandOutput(Stream &stream,
2733 llvm::StringRef str) {
2734 // Split the output into lines and poll for interrupt requests
2735 const char *data = str.data();
2736 size_t size = str.size();
2737 while (size > 0 && !WasInterrupted()) {
2738 size_t chunk_size = 0;
2739 for (; chunk_size < size; ++chunk_size) {
2740 lldbassert(data[chunk_size] != '\0');
2741 if (data[chunk_size] == '\n') {
2742 ++chunk_size;
2743 break;
2744 }
2745 }
2746 chunk_size = stream.Write(data, chunk_size);
2747 lldbassert(size >= chunk_size);
2748 data += chunk_size;
2749 size -= chunk_size;
2750 }
2751 if (size > 0) {
2752 stream.Printf("\n... Interrupted.\n");
2753 }
2754}
2755
Stefan Granitzc678ed72018-10-05 16:49:47 +00002756bool CommandInterpreter::EchoCommandNonInteractive(
2757 llvm::StringRef line, const Flags &io_handler_flags) const {
2758 if (!io_handler_flags.Test(eHandleCommandFlagEchoCommand))
2759 return false;
2760
2761 llvm::StringRef command = line.trim();
2762 if (command.empty())
2763 return true;
2764
2765 if (command.front() == m_comment_char)
2766 return io_handler_flags.Test(eHandleCommandFlagEchoCommentCommand);
2767
2768 return true;
2769}
2770
Kate Stoneb9c1b512016-09-06 20:57:50 +00002771void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2772 std::string &line) {
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002773 // If we were interrupted, bail out...
2774 if (WasInterrupted())
2775 return;
2776
Kate Stoneb9c1b512016-09-06 20:57:50 +00002777 const bool is_interactive = io_handler.GetIsInteractive();
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002778 if (!is_interactive) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002779 // When we are not interactive, don't execute blank lines. This will happen
2780 // sourcing a commands file. We don't want blank lines to repeat the
Adrian Prantl05097242018-04-30 16:49:04 +00002781 // previous command and cause any errors to occur (like redefining an
2782 // alias, get an error and stop parsing the commands file).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002783 if (line.empty())
2784 return;
2785
2786 // When using a non-interactive file handle (like when sourcing commands
Adrian Prantl05097242018-04-30 16:49:04 +00002787 // from a file) we need to echo the command out so we don't just see the
2788 // command output and no command...
Stefan Granitzc678ed72018-10-05 16:49:47 +00002789 if (EchoCommandNonInteractive(line, io_handler.GetFlags()))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002790 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2791 line.c_str());
2792 }
2793
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002794 StartHandlingCommand();
2795
Kate Stoneb9c1b512016-09-06 20:57:50 +00002796 lldb_private::CommandReturnObject result;
2797 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2798
2799 // Now emit the command output text from the command we just executed
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002800 if ((result.Succeeded() &&
2801 io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) ||
2802 io_handler.GetFlags().Test(eHandleCommandFlagPrintErrors)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002803 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2804 GetProcessOutput();
2805
2806 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002807 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002808 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002809 }
2810
2811 // Now emit the command error text from the command we just executed
2812 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002813 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002814 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002815 }
2816 }
2817
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002818 FinishHandlingCommand();
2819
Kate Stoneb9c1b512016-09-06 20:57:50 +00002820 switch (result.GetStatus()) {
2821 case eReturnStatusInvalid:
2822 case eReturnStatusSuccessFinishNoResult:
2823 case eReturnStatusSuccessFinishResult:
2824 case eReturnStatusStarted:
2825 break;
2826
2827 case eReturnStatusSuccessContinuingNoResult:
2828 case eReturnStatusSuccessContinuingResult:
2829 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2830 io_handler.SetIsDone(true);
2831 break;
2832
2833 case eReturnStatusFailed:
2834 m_num_errors++;
2835 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2836 io_handler.SetIsDone(true);
2837 break;
2838
2839 case eReturnStatusQuit:
2840 m_quit_requested = true;
2841 io_handler.SetIsDone(true);
2842 break;
2843 }
2844
2845 // Finally, if we're going to stop on crash, check that here:
2846 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2847 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2848 bool should_stop = false;
2849 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2850 if (target_sp) {
2851 ProcessSP process_sp(target_sp->GetProcessSP());
2852 if (process_sp) {
2853 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2854 StopReason reason = thread_sp->GetStopReason();
2855 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2856 reason == eStopReasonInstrumentation) &&
2857 !result.GetAbnormalStopWasExpected()) {
2858 should_stop = true;
2859 break;
2860 }
2861 }
2862 }
2863 }
2864 if (should_stop) {
2865 io_handler.SetIsDone(true);
2866 m_stopped_for_crash = true;
2867 }
2868 }
2869}
2870
2871bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2872 ExecutionContext exe_ctx(GetExecutionContext());
2873 Process *process = exe_ctx.GetProcessPtr();
2874
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002875 if (InterruptCommand())
2876 return true;
2877
Kate Stoneb9c1b512016-09-06 20:57:50 +00002878 if (process) {
2879 StateType state = process->GetState();
2880 if (StateIsRunningState(state)) {
2881 process->Halt();
2882 return true; // Don't do any updating when we are running
2883 }
2884 }
2885
Jonas Devlieghere2b29b432019-04-26 22:43:16 +00002886 ScriptInterpreter *script_interpreter =
2887 m_debugger.GetScriptInterpreter(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002888 if (script_interpreter) {
2889 if (script_interpreter->Interrupt())
2890 return true;
2891 }
2892 return false;
2893}
2894
2895void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2896 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2897 void *baton) {
2898 Debugger &debugger = GetDebugger();
2899 IOHandlerSP io_handler_sp(
2900 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2901 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002902 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2903 llvm::StringRef(), // Continuation prompt
2904 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002905 debugger.GetUseColor(),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002906 0, // Don't show line numbers
2907 delegate, // IOHandlerDelegate
2908 nullptr)); // FileShadowCollector
Kate Stoneb9c1b512016-09-06 20:57:50 +00002909
2910 if (io_handler_sp) {
2911 io_handler_sp->SetUserData(baton);
2912 if (asynchronously)
2913 debugger.PushIOHandler(io_handler_sp);
2914 else
2915 debugger.RunIOHandler(io_handler_sp);
2916 }
2917}
2918
2919void CommandInterpreter::GetPythonCommandsFromIOHandler(
2920 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2921 void *baton) {
2922 Debugger &debugger = GetDebugger();
2923 IOHandlerSP io_handler_sp(
2924 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2925 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002926 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2927 llvm::StringRef(), // Continuation prompt
2928 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002929 debugger.GetUseColor(),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002930 0, // Don't show line numbers
2931 delegate, // IOHandlerDelegate
2932 nullptr)); // FileShadowCollector
Kate Stoneb9c1b512016-09-06 20:57:50 +00002933
2934 if (io_handler_sp) {
2935 io_handler_sp->SetUserData(baton);
2936 if (asynchronously)
2937 debugger.PushIOHandler(io_handler_sp);
2938 else
2939 debugger.RunIOHandler(io_handler_sp);
2940 }
2941}
2942
2943bool CommandInterpreter::IsActive() {
2944 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2945}
2946
2947lldb::IOHandlerSP
2948CommandInterpreter::GetIOHandler(bool force_create,
2949 CommandInterpreterRunOptions *options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002950 // Always re-create the IOHandlerEditline in case the input changed. The old
2951 // instance might have had a non-interactive input and now it does or vice
2952 // versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002953 if (force_create || !m_command_io_handler_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002954 // Always re-create the IOHandlerEditline in case the input changed. The
2955 // old instance might have had a non-interactive input and now it does or
2956 // vice versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002957 uint32_t flags = 0;
2958
2959 if (options) {
2960 if (options->m_stop_on_continue == eLazyBoolYes)
2961 flags |= eHandleCommandFlagStopOnContinue;
2962 if (options->m_stop_on_error == eLazyBoolYes)
2963 flags |= eHandleCommandFlagStopOnError;
2964 if (options->m_stop_on_crash == eLazyBoolYes)
2965 flags |= eHandleCommandFlagStopOnCrash;
2966 if (options->m_echo_commands != eLazyBoolNo)
2967 flags |= eHandleCommandFlagEchoCommand;
Stefan Granitzc678ed72018-10-05 16:49:47 +00002968 if (options->m_echo_comment_commands != eLazyBoolNo)
2969 flags |= eHandleCommandFlagEchoCommentCommand;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002970 if (options->m_print_results != eLazyBoolNo)
2971 flags |= eHandleCommandFlagPrintResult;
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002972 if (options->m_print_errors != eLazyBoolNo)
2973 flags |= eHandleCommandFlagPrintErrors;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002974 } else {
Jonas Devliegherec0b48ab2019-05-08 01:23:47 +00002975 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult |
2976 eHandleCommandFlagPrintErrors;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002977 }
2978
Jonas Devlieghere796ac802019-02-11 23:13:08 +00002979 m_command_io_handler_sp = std::make_shared<IOHandlerEditline>(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002980 m_debugger, IOHandler::Type::CommandInterpreter,
2981 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2982 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002983 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002984 false, // Don't enable multiple line input, just single line commands
2985 m_debugger.GetUseColor(),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +00002986 0, // Don't show line numbers
2987 *this, // IOHandlerDelegate
2988 GetDebugger().GetInputRecorder());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002989 }
2990 return m_command_io_handler_sp;
2991}
2992
2993void CommandInterpreter::RunCommandInterpreter(
2994 bool auto_handle_events, bool spawn_thread,
2995 CommandInterpreterRunOptions &options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002996 // Always re-create the command interpreter when we run it in case any file
2997 // handles have changed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002998 bool force_create = true;
2999 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
3000 m_stopped_for_crash = false;
3001
3002 if (auto_handle_events)
3003 m_debugger.StartEventHandlerThread();
3004
3005 if (spawn_thread) {
3006 m_debugger.StartIOHandlerThread();
3007 } else {
3008 m_debugger.ExecuteIOHandlers();
3009
3010 if (auto_handle_events)
3011 m_debugger.StopEventHandlerThread();
3012 }
3013}
3014
3015CommandObject *
3016CommandInterpreter::ResolveCommandImpl(std::string &command_line,
3017 CommandReturnObject &result) {
3018 std::string scratch_command(command_line); // working copy so we don't modify
3019 // command_line unless we succeed
3020 CommandObject *cmd_obj = nullptr;
3021 StreamString revised_command_line;
3022 bool wants_raw_input = false;
3023 size_t actual_cmd_name_len = 0;
3024 std::string next_word;
3025 StringList matches;
3026 bool done = false;
3027 while (!done) {
3028 char quote_char = '\0';
3029 std::string suffix;
3030 ExtractCommand(scratch_command, next_word, suffix, quote_char);
3031 if (cmd_obj == nullptr) {
3032 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003033 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00003034 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003035 bool is_real_command =
Jonas Devliegherea6682a42018-12-15 00:15:33 +00003036 (!is_alias) || (cmd_obj != nullptr && !cmd_obj->IsAlias());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003037 if (!is_real_command) {
3038 matches.Clear();
3039 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003040 cmd_obj =
3041 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003042 revised_command_line.Printf("%s", alias_result.c_str());
3043 if (cmd_obj) {
3044 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00003045 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003046 }
3047 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003048 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00003049 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
3050 actual_cmd_name_len += cmd_name.size();
3051 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003052 wants_raw_input = cmd_obj->WantsRawCommandString();
3053 } else {
3054 revised_command_line.Printf("%s", next_word.c_str());
3055 }
3056 }
3057 } else {
3058 if (cmd_obj->IsMultiwordObject()) {
3059 CommandObject *sub_cmd_obj =
3060 cmd_obj->GetSubcommandObject(next_word.c_str());
3061 if (sub_cmd_obj) {
Adrian Prantl05097242018-04-30 16:49:04 +00003062 // The subcommand's name includes the parent command's name, so
3063 // restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00003064 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3065 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003066 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00003067 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003068 cmd_obj = sub_cmd_obj;
3069 wants_raw_input = cmd_obj->WantsRawCommandString();
3070 } else {
3071 if (quote_char)
3072 revised_command_line.Printf(" %c%s%s%c", quote_char,
3073 next_word.c_str(), suffix.c_str(),
3074 quote_char);
3075 else
3076 revised_command_line.Printf(" %s%s", next_word.c_str(),
3077 suffix.c_str());
3078 done = true;
3079 }
3080 } else {
3081 if (quote_char)
3082 revised_command_line.Printf(" %c%s%s%c", quote_char,
3083 next_word.c_str(), suffix.c_str(),
3084 quote_char);
3085 else
3086 revised_command_line.Printf(" %s%s", next_word.c_str(),
3087 suffix.c_str());
3088 done = true;
3089 }
3090 }
3091
3092 if (cmd_obj == nullptr) {
3093 const size_t num_matches = matches.GetSize();
3094 if (matches.GetSize() > 1) {
3095 StreamString error_msg;
3096 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3097 next_word.c_str());
3098
3099 for (uint32_t i = 0; i < num_matches; ++i) {
3100 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3101 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003102 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003103 } else {
3104 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003105 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003106 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3107 next_word.c_str());
3108 }
3109 result.SetStatus(eReturnStatusFailed);
3110 return nullptr;
3111 }
3112
3113 if (cmd_obj->IsMultiwordObject()) {
3114 if (!suffix.empty()) {
3115 result.AppendErrorWithFormat(
3116 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3117 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003118 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003119 next_word.empty() ? "" : next_word.c_str(),
3120 next_word.empty() ? " -- " : " ", suffix.c_str());
3121 result.SetStatus(eReturnStatusFailed);
3122 return nullptr;
3123 }
3124 } else {
3125 // If we found a normal command, we are done
3126 done = true;
3127 if (!suffix.empty()) {
3128 switch (suffix[0]) {
3129 case '/':
3130 // GDB format suffixes
3131 {
3132 Options *command_options = cmd_obj->GetOptions();
3133 if (command_options &&
3134 command_options->SupportsLongOption("gdb-format")) {
3135 std::string gdb_format_option("--gdb-format=");
3136 gdb_format_option += (suffix.c_str() + 1);
3137
Zachary Turnerc1564272016-11-16 21:15:24 +00003138 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3140 if (arg_terminator_idx != std::string::npos) {
3141 // Insert the gdb format option before the "--" that terminates
3142 // options
3143 gdb_format_option.append(1, ' ');
3144 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003145 revised_command_line.Clear();
3146 revised_command_line.PutCString(cmd);
3147 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003148 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3149
3150 if (wants_raw_input &&
3151 FindArgumentTerminator(cmd) == std::string::npos)
3152 revised_command_line.PutCString(" --");
3153 } else {
3154 result.AppendErrorWithFormat(
3155 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003156 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003157 result.SetStatus(eReturnStatusFailed);
3158 return nullptr;
3159 }
3160 }
3161 break;
3162
3163 default:
3164 result.AppendErrorWithFormat(
3165 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3166 result.SetStatus(eReturnStatusFailed);
3167 return nullptr;
3168 }
3169 }
3170 }
3171 if (scratch_command.empty())
3172 done = true;
3173 }
3174
3175 if (!scratch_command.empty())
3176 revised_command_line.Printf(" %s", scratch_command.c_str());
3177
Konrad Kleine248a1302019-05-23 11:14:47 +00003178 if (cmd_obj != nullptr)
Zachary Turnerc1564272016-11-16 21:15:24 +00003179 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003180
3181 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003182}