blob: 2ec59565438d182fade779cb4b90c52d5db26ed0 [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
Stefan Granitzc678ed72018-10-05 16:49:47 +000080static constexpr bool NoGlobalSetting = true;
81static constexpr uintptr_t DefaultValueTrue = true;
82static constexpr uintptr_t DefaultValueFalse = false;
83static constexpr const char *NoCStrDefault = nullptr;
84
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000085static constexpr PropertyDefinition g_properties[] = {
Stefan Granitzc678ed72018-10-05 16:49:47 +000086 {"expand-regex-aliases", OptionValue::eTypeBoolean, NoGlobalSetting,
87 DefaultValueFalse, NoCStrDefault, {},
88 "If true, regular expression alias commands will show the "
89 "expanded command that will be executed. This can be used to "
90 "debug new regular expression alias commands."},
91 {"prompt-on-quit", OptionValue::eTypeBoolean, NoGlobalSetting,
92 DefaultValueTrue, NoCStrDefault, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +000093 "If true, LLDB will prompt you before quitting if there are any live "
94 "processes being debugged. If false, LLDB will quit without asking in any "
95 "case."},
Stefan Granitzc678ed72018-10-05 16:49:47 +000096 {"stop-command-source-on-error", OptionValue::eTypeBoolean, NoGlobalSetting,
97 DefaultValueTrue, NoCStrDefault, {},
98 "If true, LLDB will stop running a 'command source' "
99 "script upon encountering an error."},
100 {"space-repl-prompts", OptionValue::eTypeBoolean, NoGlobalSetting,
101 DefaultValueFalse, NoCStrDefault, {},
102 "If true, blank lines will be printed between between REPL submissions."},
103 {"echo-commands", OptionValue::eTypeBoolean, NoGlobalSetting,
104 DefaultValueTrue, NoCStrDefault, {},
105 "If true, commands will be echoed before they are evaluated."},
106 {"echo-comment-commands", OptionValue::eTypeBoolean, NoGlobalSetting,
107 DefaultValueTrue, NoCStrDefault, {},
108 "If true, commands will be echoed even if they are pure comment lines."}};
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109
110enum {
111 ePropertyExpandRegexAliases = 0,
112 ePropertyPromptOnQuit = 1,
113 ePropertyStopCmdSourceOnError = 2,
Stefan Granitzc678ed72018-10-05 16:49:47 +0000114 eSpaceReplPrompts = 3,
115 eEchoCommands = 4,
116 eEchoCommentCommands = 5
Greg Clayton754a9362012-08-23 00:22:02 +0000117};
118
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119ConstString &CommandInterpreter::GetStaticBroadcasterClass() {
120 static ConstString class_name("lldb.commandInterpreter");
121 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000122}
123
Kate Stoneb9c1b512016-09-06 20:57:50 +0000124CommandInterpreter::CommandInterpreter(Debugger &debugger,
125 ScriptLanguage script_language,
126 bool synchronous_execution)
127 : Broadcaster(debugger.GetBroadcasterManager(),
128 CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
129 Properties(OptionValuePropertiesSP(
130 new OptionValueProperties(ConstString("interpreter")))),
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000131 IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132 m_debugger(debugger), m_synchronous_execution(synchronous_execution),
133 m_skip_lldbinit_files(false), m_skip_app_init_files(false),
134 m_script_interpreter_sp(), m_command_io_handler_sp(), m_comment_char('#'),
135 m_batch_command_mode(false), m_truncation_warning(eNoTruncation),
136 m_command_source_depth(0), m_num_errors(0), m_quit_requested(false),
137 m_stopped_for_crash(false) {
138 debugger.SetScriptLanguage(script_language);
139 SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit");
140 SetEventName(eBroadcastBitResetPrompt, "reset-prompt");
141 SetEventName(eBroadcastBitQuitCommandReceived, "quit");
142 CheckInWithManager();
143 m_collection_sp->Initialize(g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000144}
145
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146bool CommandInterpreter::GetExpandRegexAliases() const {
147 const uint32_t idx = ePropertyExpandRegexAliases;
148 return m_collection_sp->GetPropertyAtIndexAsBoolean(
149 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000150}
151
Kate Stoneb9c1b512016-09-06 20:57:50 +0000152bool CommandInterpreter::GetPromptOnQuit() const {
153 const uint32_t idx = ePropertyPromptOnQuit;
154 return m_collection_sp->GetPropertyAtIndexAsBoolean(
155 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000156}
Greg Clayton754a9362012-08-23 00:22:02 +0000157
Kate Stoneb9c1b512016-09-06 20:57:50 +0000158void CommandInterpreter::SetPromptOnQuit(bool b) {
159 const uint32_t idx = ePropertyPromptOnQuit;
160 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ilia Kacf28be2015-03-23 22:45:13 +0000161}
162
Stefan Granitzc678ed72018-10-05 16:49:47 +0000163bool CommandInterpreter::GetEchoCommands() const {
164 const uint32_t idx = eEchoCommands;
165 return m_collection_sp->GetPropertyAtIndexAsBoolean(
166 nullptr, idx, g_properties[idx].default_uint_value != 0);
167}
168
169void CommandInterpreter::SetEchoCommands(bool b) {
170 const uint32_t idx = eEchoCommands;
171 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
172}
173
174bool CommandInterpreter::GetEchoCommentCommands() const {
175 const uint32_t idx = eEchoCommentCommands;
176 return m_collection_sp->GetPropertyAtIndexAsBoolean(
177 nullptr, idx, g_properties[idx].default_uint_value != 0);
178}
179
180void CommandInterpreter::SetEchoCommentCommands(bool b) {
181 const uint32_t idx = eEchoCommentCommands;
182 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
183}
184
Raphael Isemannc094d232018-07-11 17:18:01 +0000185void CommandInterpreter::AllowExitCodeOnQuit(bool allow) {
186 m_allow_exit_code = allow;
187 if (!allow)
188 m_quit_exit_code.reset();
189}
190
191bool CommandInterpreter::SetQuitExitCode(int exit_code) {
192 if (!m_allow_exit_code)
193 return false;
194 m_quit_exit_code = exit_code;
195 return true;
196}
197
198int CommandInterpreter::GetQuitExitCode(bool &exited) const {
199 exited = m_quit_exit_code.hasValue();
200 if (exited)
201 return *m_quit_exit_code;
202 return 0;
203}
204
Kate Stoneb9c1b512016-09-06 20:57:50 +0000205void CommandInterpreter::ResolveCommand(const char *command_line,
206 CommandReturnObject &result) {
207 std::string command = command_line;
208 if (ResolveCommandImpl(command, result) != nullptr) {
209 result.AppendMessageWithFormat("%s", command.c_str());
210 result.SetStatus(eReturnStatusSuccessFinishResult);
211 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000212}
213
Kate Stoneb9c1b512016-09-06 20:57:50 +0000214bool CommandInterpreter::GetStopCmdSourceOnError() const {
215 const uint32_t idx = ePropertyStopCmdSourceOnError;
216 return m_collection_sp->GetPropertyAtIndexAsBoolean(
217 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000218}
219
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220bool CommandInterpreter::GetSpaceReplPrompts() const {
221 const uint32_t idx = eSpaceReplPrompts;
222 return m_collection_sp->GetPropertyAtIndexAsBoolean(
223 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callanan66810412015-10-19 23:11:07 +0000224}
225
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226void CommandInterpreter::Initialize() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000227 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
228 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000229
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230 CommandReturnObject result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000231
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232 LoadCommandDictionary();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000233
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234 // An alias arguments vector to reuse - reset it before use...
235 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
236
237 // Set up some initial aliases.
238 CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
239 if (cmd_obj_sp) {
240 AddAlias("q", cmd_obj_sp);
241 AddAlias("exit", cmd_obj_sp);
242 }
243
244 cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
245 if (cmd_obj_sp)
246 AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
247
248 cmd_obj_sp = GetCommandSPExact("process detach", false);
249 if (cmd_obj_sp) {
250 AddAlias("detach", cmd_obj_sp);
251 }
252
253 cmd_obj_sp = GetCommandSPExact("process continue", false);
254 if (cmd_obj_sp) {
255 AddAlias("c", cmd_obj_sp);
256 AddAlias("continue", cmd_obj_sp);
257 }
258
259 cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
260 if (cmd_obj_sp)
261 AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
262
263 cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
264 if (cmd_obj_sp)
265 AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
266
267 cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
268 if (cmd_obj_sp) {
269 AddAlias("stepi", cmd_obj_sp);
270 AddAlias("si", cmd_obj_sp);
271 }
272
273 cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
274 if (cmd_obj_sp) {
275 AddAlias("nexti", cmd_obj_sp);
276 AddAlias("ni", cmd_obj_sp);
277 }
278
279 cmd_obj_sp = GetCommandSPExact("thread step-in", false);
280 if (cmd_obj_sp) {
281 AddAlias("s", cmd_obj_sp);
282 AddAlias("step", cmd_obj_sp);
283 CommandAlias *sif_alias = AddAlias(
284 "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
285 if (sif_alias) {
286 sif_alias->SetHelp("Step through the current block, stopping if you step "
287 "directly into a function whose name matches the "
288 "TargetFunctionName.");
289 sif_alias->SetSyntax("sif <TargetFunctionName>");
Caroline Ticeca90c472011-05-06 21:37:15 +0000290 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000291 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000292
Kate Stoneb9c1b512016-09-06 20:57:50 +0000293 cmd_obj_sp = GetCommandSPExact("thread step-over", false);
294 if (cmd_obj_sp) {
295 AddAlias("n", cmd_obj_sp);
296 AddAlias("next", cmd_obj_sp);
297 }
298
299 cmd_obj_sp = GetCommandSPExact("thread step-out", false);
300 if (cmd_obj_sp) {
301 AddAlias("finish", cmd_obj_sp);
302 }
303
304 cmd_obj_sp = GetCommandSPExact("frame select", false);
305 if (cmd_obj_sp) {
306 AddAlias("f", cmd_obj_sp);
307 }
308
309 cmd_obj_sp = GetCommandSPExact("thread select", false);
310 if (cmd_obj_sp) {
311 AddAlias("t", cmd_obj_sp);
312 }
313
314 cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
315 if (cmd_obj_sp) {
316 AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
317 AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
318 }
319
320 cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
321 if (cmd_obj_sp) {
322 AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
323 AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
324 }
325
326 cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
327 if (cmd_obj_sp)
328 AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
329
330 cmd_obj_sp = GetCommandSPExact("memory read", false);
331 if (cmd_obj_sp)
332 AddAlias("x", cmd_obj_sp);
333
334 cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
335 if (cmd_obj_sp)
336 AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
337
338 cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
339 if (cmd_obj_sp)
340 AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
341
342 cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
343 if (cmd_obj_sp)
344 AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
345
346 cmd_obj_sp = GetCommandSPExact("disassemble", false);
347 if (cmd_obj_sp)
348 AddAlias("dis", cmd_obj_sp);
349
350 cmd_obj_sp = GetCommandSPExact("disassemble", false);
351 if (cmd_obj_sp)
352 AddAlias("di", cmd_obj_sp);
353
354 cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
355 if (cmd_obj_sp)
356 AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
357
358 cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
359 if (cmd_obj_sp)
360 AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
361
362 cmd_obj_sp = GetCommandSPExact("target create", false);
363 if (cmd_obj_sp)
364 AddAlias("file", cmd_obj_sp);
365
366 cmd_obj_sp = GetCommandSPExact("target modules", false);
367 if (cmd_obj_sp)
368 AddAlias("image", cmd_obj_sp);
369
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000370 alias_arguments_vector_sp = std::make_shared<OptionArgVector>();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371
372 cmd_obj_sp = GetCommandSPExact("expression", false);
373 if (cmd_obj_sp) {
374 AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
375 AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
376 AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
377 if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
378 po->SetHelp("Evaluate an expression on the current thread. Displays any "
379 "returned value with formatting "
380 "controlled by the type's author.");
381 po->SetHelpLong("");
Johnny Chen6d675242012-08-24 18:15:45 +0000382 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000383 AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
384 AddAlias("poarray", cmd_obj_sp,
385 "--object-description --element-count %1 --")
386 ->SetHelpLong("");
387 }
Johnny Chen6d675242012-08-24 18:15:45 +0000388
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389 cmd_obj_sp = GetCommandSPExact("process kill", false);
390 if (cmd_obj_sp) {
391 AddAlias("kill", cmd_obj_sp);
392 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000393
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 cmd_obj_sp = GetCommandSPExact("process launch", false);
395 if (cmd_obj_sp) {
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000396 alias_arguments_vector_sp = std::make_shared<OptionArgVector>();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
398 AddAlias("r", cmd_obj_sp, "--");
399 AddAlias("run", cmd_obj_sp, "--");
Jason Molenda85da3122012-07-06 02:46:23 +0000400#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401#if defined(__APPLE__)
402 std::string shell_option;
403 shell_option.append("--shell-expand-args");
404 shell_option.append(" true");
405 shell_option.append(" --");
406 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
407 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
408#else
409 StreamString defaultshell;
410 defaultshell.Printf("--shell=%s --",
411 HostInfo::GetDefaultShell().GetPath().c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +0000412 AddAlias("r", cmd_obj_sp, defaultshell.GetString());
413 AddAlias("run", cmd_obj_sp, defaultshell.GetString());
Jason Molenda85da3122012-07-06 02:46:23 +0000414#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415#endif
416 }
417
418 cmd_obj_sp = GetCommandSPExact("target symbols add", false);
419 if (cmd_obj_sp) {
420 AddAlias("add-dsym", cmd_obj_sp);
421 }
422
423 cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
424 if (cmd_obj_sp) {
425 AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
426 }
Jim Ingham285ae0c2018-10-10 00:51:30 +0000427
428 cmd_obj_sp = GetCommandSPExact("frame variable", false);
429 if (cmd_obj_sp) {
Jim Ingham9082c1c2018-10-12 18:46:02 +0000430 AddAlias("v", cmd_obj_sp);
Jim Ingham285ae0c2018-10-10 00:51:30 +0000431 AddAlias("var", cmd_obj_sp);
432 AddAlias("vo", cmd_obj_sp, "--object-description");
433 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000434}
435
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436void CommandInterpreter::Clear() {
437 m_command_io_handler_sp.reset();
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000438
Kate Stoneb9c1b512016-09-06 20:57:50 +0000439 if (m_script_interpreter_sp)
440 m_script_interpreter_sp->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000441}
442
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
444 // This function has not yet been implemented.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000445
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446 // Look for any embedded script command
447 // If found,
448 // get interpreter object from the command dictionary,
449 // call execute_one_command on it,
450 // get the results as a string,
451 // substitute that string for current stuff.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000452
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453 return arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000454}
455
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456void CommandInterpreter::LoadCommandDictionary() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000457 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
458 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000459
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000461
Kate Stoneb9c1b512016-09-06 20:57:50 +0000462 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
463 m_command_dict["breakpoint"] =
464 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
465 m_command_dict["bugreport"] =
466 CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
467 m_command_dict["command"] =
468 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
469 m_command_dict["disassemble"] =
470 CommandObjectSP(new CommandObjectDisassemble(*this));
471 m_command_dict["expression"] =
472 CommandObjectSP(new CommandObjectExpression(*this));
473 m_command_dict["frame"] =
474 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
475 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
476 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
477 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
478 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
479 m_command_dict["platform"] =
480 CommandObjectSP(new CommandObjectPlatform(*this));
481 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
482 m_command_dict["process"] =
483 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
484 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
485 m_command_dict["register"] =
486 CommandObjectSP(new CommandObjectRegister(*this));
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000487 m_command_dict["reproducer"] =
488 CommandObjectSP(new CommandObjectReproducer(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 m_command_dict["script"] =
490 CommandObjectSP(new CommandObjectScript(*this, script_language));
491 m_command_dict["settings"] =
492 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
493 m_command_dict["source"] =
494 CommandObjectSP(new CommandObjectMultiwordSource(*this));
Davide Italiano24fff242018-04-13 18:02:39 +0000495 m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000496 m_command_dict["target"] =
497 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
498 m_command_dict["thread"] =
499 CommandObjectSP(new CommandObjectMultiwordThread(*this));
500 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
501 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
502 m_command_dict["watchpoint"] =
503 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
504 m_command_dict["language"] =
505 CommandObjectSP(new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000506
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507 const char *break_regexes[][2] = {
508 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
509 "breakpoint set --file '%1' --line %2"},
510 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
511 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
512 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
513 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
514 "breakpoint set --name '%1'"},
515 {"^(-.*)$", "breakpoint set %1"},
516 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
517 "breakpoint set --name '%2' --shlib '%1'"},
518 {"^\\&(.*[^[:space:]])[[:space:]]*$",
519 "breakpoint set --name '%1' --skip-prologue=0"},
520 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
521 "breakpoint set --name '%1'"}};
Kate Stone7428a182016-07-14 22:03:10 +0000522
Kate Stoneb9c1b512016-09-06 20:57:50 +0000523 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000524
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap(
526 new CommandObjectRegexCommand(
527 *this, "_regexp-break",
Raphael Isemann129fe892018-07-30 21:41:13 +0000528 "Set a breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000529 "\n"
530 "_regexp-break <filename>:<linenum>\n"
531 " main.c:12 // Break at line 12 of "
532 "main.c\n\n"
533 "_regexp-break <linenum>\n"
534 " 12 // Break at line 12 of current "
535 "file\n\n"
536 "_regexp-break 0x<address>\n"
537 " 0x1234000 // Break at address "
538 "0x1234000\n\n"
539 "_regexp-break <name>\n"
540 " main // Break in 'main' after the "
541 "prologue\n\n"
542 "_regexp-break &<name>\n"
543 " &main // Break at first instruction "
544 "in 'main'\n\n"
545 "_regexp-break <module>`<name>\n"
546 " libc.so`malloc // Break in 'malloc' from "
547 "'libc.so'\n\n"
548 "_regexp-break /<source-regex>/\n"
549 " /break here/ // Break on source lines in "
550 "current file\n"
551 " // containing text 'break "
552 "here'.\n",
553 2, CommandCompletions::eSymbolCompletion |
554 CommandCompletions::eSourceFileCompletion,
555 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000556
Kate Stoneb9c1b512016-09-06 20:57:50 +0000557 if (break_regex_cmd_ap.get()) {
558 bool success = true;
559 for (size_t i = 0; i < num_regexes; i++) {
560 success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0],
561 break_regexes[i][1]);
562 if (!success)
563 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000564 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565 success =
566 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Jim Inghamffba2292011-03-22 02:29:32 +0000567
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 if (success) {
569 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
570 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
Jim Inghamca36cd12012-10-05 19:16:31 +0000571 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000572 }
Jim Inghamca36cd12012-10-05 19:16:31 +0000573
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap(
575 new CommandObjectRegexCommand(
576 *this, "_regexp-tbreak",
Raphael Isemann129fe892018-07-30 21:41:13 +0000577 "Set a one-shot breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000578 "\n"
579 "_regexp-break <filename>:<linenum>\n"
580 " main.c:12 // Break at line 12 of "
581 "main.c\n\n"
582 "_regexp-break <linenum>\n"
583 " 12 // Break at line 12 of current "
584 "file\n\n"
585 "_regexp-break 0x<address>\n"
586 " 0x1234000 // Break at address "
587 "0x1234000\n\n"
588 "_regexp-break <name>\n"
589 " main // Break in 'main' after the "
590 "prologue\n\n"
591 "_regexp-break &<name>\n"
592 " &main // Break at first instruction "
593 "in 'main'\n\n"
594 "_regexp-break <module>`<name>\n"
595 " libc.so`malloc // Break in 'malloc' from "
596 "'libc.so'\n\n"
597 "_regexp-break /<source-regex>/\n"
598 " /break here/ // Break on source lines in "
599 "current file\n"
600 " // containing text 'break "
601 "here'.\n",
602 2, CommandCompletions::eSymbolCompletion |
603 CommandCompletions::eSourceFileCompletion,
604 false));
605
606 if (tbreak_regex_cmd_ap.get()) {
607 bool success = true;
608 for (size_t i = 0; i < num_regexes; i++) {
609 // If you add a resultant command string longer than 1024 characters be
610 // sure to increase the size of this buffer.
611 char buffer[1024];
612 int num_printed =
Frederic Riss49c9d8b2018-06-18 04:34:33 +0000613 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1");
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000614 lldbassert(num_printed < 1024);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615 UNUSED_IF_ASSERT_DISABLED(num_printed);
616 success =
617 tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer);
618 if (!success)
619 break;
Johnny Chen6d675242012-08-24 18:15:45 +0000620 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000621 success =
622 tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Kate Stone7428a182016-07-14 22:03:10 +0000623
Kate Stoneb9c1b512016-09-06 20:57:50 +0000624 if (success) {
625 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
626 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
627 tbreak_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000628 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629 }
Kate Stone7428a182016-07-14 22:03:10 +0000630
Kate Stoneb9c1b512016-09-06 20:57:50 +0000631 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap(
632 new CommandObjectRegexCommand(
633 *this, "_regexp-attach", "Attach to process by ID or name.",
634 "_regexp-attach <pid> | <process-name>", 2, 0, false));
635 if (attach_regex_cmd_ap.get()) {
636 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
637 "process attach --pid %1") &&
638 attach_regex_cmd_ap->AddRegexCommand(
639 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
640 // specified get passed to
641 // 'process attach'
642 attach_regex_cmd_ap->AddRegexCommand("^(.+)$",
643 "process attach --name '%1'") &&
644 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) {
645 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
646 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
647 attach_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000648 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000650
Kate Stoneb9c1b512016-09-06 20:57:50 +0000651 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap(
652 new CommandObjectRegexCommand(*this, "_regexp-down",
653 "Select a newer stack frame. Defaults to "
654 "moving one frame, a numeric argument can "
655 "specify an arbitrary number.",
656 "_regexp-down [<count>]", 2, 0, false));
657 if (down_regex_cmd_ap.get()) {
658 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
659 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
660 "frame select -r -%1")) {
661 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
662 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000663 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000665
Kate Stoneb9c1b512016-09-06 20:57:50 +0000666 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap(
667 new CommandObjectRegexCommand(
668 *this, "_regexp-up",
669 "Select an older stack frame. Defaults to moving one "
670 "frame, a numeric argument can specify an arbitrary number.",
671 "_regexp-up [<count>]", 2, 0, false));
672 if (up_regex_cmd_ap.get()) {
673 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
674 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
675 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
676 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000677 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000678 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000679
Kate Stoneb9c1b512016-09-06 20:57:50 +0000680 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap(
681 new CommandObjectRegexCommand(
682 *this, "_regexp-display",
683 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
684 "_regexp-display expression", 2, 0, false));
685 if (display_regex_cmd_ap.get()) {
686 if (display_regex_cmd_ap->AddRegexCommand(
687 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
688 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
689 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
690 display_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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000694 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap(
695 new CommandObjectRegexCommand(
696 *this, "_regexp-undisplay", "Stop displaying expression at every "
697 "stop (specified by stop-hook index.)",
698 "_regexp-undisplay stop-hook-number", 2, 0, false));
699 if (undisplay_regex_cmd_ap.get()) {
700 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
701 "target stop-hook delete %1")) {
702 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
703 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
704 undisplay_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000705 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000706 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000707
Kate Stoneb9c1b512016-09-06 20:57:50 +0000708 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap(
709 new CommandObjectRegexCommand(
710 *this, "gdb-remote", "Connect to a process via remote GDB server. "
711 "If no host is specifed, localhost is assumed.",
712 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
713 if (connect_gdb_remote_cmd_ap.get()) {
714 if (connect_gdb_remote_cmd_ap->AddRegexCommand(
Chris Bieneman51978f52017-04-27 16:13:58 +0000715 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
716 "process connect --plugin gdb-remote connect://%1:%2") &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717 connect_gdb_remote_cmd_ap->AddRegexCommand(
718 "^([[:digit:]]+)$",
719 "process connect --plugin gdb-remote connect://localhost:%1")) {
720 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
721 m_command_dict[command_sp->GetCommandName()] = command_sp;
Jason Molenda4cddfed2012-10-05 05:29:32 +0000722 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000723 }
Jason Molenda4cddfed2012-10-05 05:29:32 +0000724
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap(
726 new CommandObjectRegexCommand(
727 *this, "kdp-remote", "Connect to a process via remote KDP server. "
728 "If no UDP port is specified, port 41139 is "
729 "assumed.",
730 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
731 if (connect_kdp_remote_cmd_ap.get()) {
732 if (connect_kdp_remote_cmd_ap->AddRegexCommand(
733 "^([^:]+:[[:digit:]]+)$",
734 "process connect --plugin kdp-remote udp://%1") &&
735 connect_kdp_remote_cmd_ap->AddRegexCommand(
736 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
737 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
738 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Clayton6bade322013-02-01 23:33:03 +0000739 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000740 }
Greg Clayton6bade322013-02-01 23:33:03 +0000741
Kate Stoneb9c1b512016-09-06 20:57:50 +0000742 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap(
743 new CommandObjectRegexCommand(
744 *this, "_regexp-bt",
745 "Show the current thread's call stack. Any numeric argument "
746 "displays at most that many "
747 "frames. The argument 'all' displays all threads.",
748 "bt [<digit> | all]", 2, 0, false));
749 if (bt_regex_cmd_ap.get()) {
750 // accept but don't document "bt -c <number>" -- before bt was a regex
Adrian Prantl05097242018-04-30 16:49:04 +0000751 // command if you wanted to backtrace three frames you would do "bt -c 3"
752 // but the intention is to have this emulate the gdb "bt" command and so
753 // now "bt 3" is the preferred form, in line with gdb.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000754 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$",
755 "thread backtrace -c %1") &&
756 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$",
757 "thread backtrace -c %1") &&
758 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
759 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) {
760 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
761 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Claytonef5651d2013-02-12 18:52:24 +0000762 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763 }
Greg Claytonef5651d2013-02-12 18:52:24 +0000764
Kate Stoneb9c1b512016-09-06 20:57:50 +0000765 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap(
766 new CommandObjectRegexCommand(
767 *this, "_regexp-list",
768 "List relevant source code using one of several shorthand formats.",
769 "\n"
770 "_regexp-list <file>:<line> // List around specific file/line\n"
771 "_regexp-list <line> // List current file around specified "
772 "line\n"
773 "_regexp-list <function-name> // List specified function\n"
774 "_regexp-list 0x<address> // List around specified address\n"
775 "_regexp-list -[<count>] // List previous <count> lines\n"
776 "_regexp-list // List subsequent lines",
777 2, CommandCompletions::eSourceFileCompletion, false));
778 if (list_regex_cmd_ap.get()) {
779 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
780 "source list --line %1") &&
781 list_regex_cmd_ap->AddRegexCommand(
782 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
783 "]*$",
784 "source list --file '%1' --line %2") &&
785 list_regex_cmd_ap->AddRegexCommand(
786 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
787 "source list --address %1") &&
788 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$",
789 "source list --reverse") &&
790 list_regex_cmd_ap->AddRegexCommand(
791 "^-([[:digit:]]+)[[:space:]]*$",
792 "source list --reverse --count %1") &&
793 list_regex_cmd_ap->AddRegexCommand("^(.+)$",
794 "source list --name \"%1\"") &&
795 list_regex_cmd_ap->AddRegexCommand("^$", "source list")) {
796 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
797 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
Richard Mittonf86248d2013-09-12 02:20:34 +0000798 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799 }
Richard Mittonf86248d2013-09-12 02:20:34 +0000800
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap(
802 new CommandObjectRegexCommand(
803 *this, "_regexp-env",
804 "Shorthand for viewing and setting environment variables.",
805 "\n"
806 "_regexp-env // Show enrivonment\n"
807 "_regexp-env <name>=<value> // Set an environment variable",
808 2, 0, false));
809 if (env_regex_cmd_ap.get()) {
810 if (env_regex_cmd_ap->AddRegexCommand("^$",
811 "settings show target.env-vars") &&
812 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
813 "settings set target.env-vars %1")) {
814 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
815 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
816 }
817 }
818
819 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap(
820 new CommandObjectRegexCommand(
821 *this, "_regexp-jump", "Set the program counter to a new address.",
822 "\n"
823 "_regexp-jump <line>\n"
824 "_regexp-jump +<line-offset> | -<line-offset>\n"
825 "_regexp-jump <file>:<line>\n"
826 "_regexp-jump *<addr>\n",
827 2, 0, false));
828 if (jump_regex_cmd_ap.get()) {
829 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$",
830 "thread jump --addr %1") &&
831 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
832 "thread jump --line %1") &&
833 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$",
834 "thread jump --file %1 --line %2") &&
835 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$",
836 "thread jump --by %1")) {
837 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
838 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
839 }
840 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000841}
842
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843int CommandInterpreter::GetCommandNamesMatchingPartialString(
Raphael Isemann7f888292018-09-13 21:26:00 +0000844 const char *cmd_str, bool include_aliases, StringList &matches,
845 StringList &descriptions) {
846 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches,
847 &descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000848
Kate Stoneb9c1b512016-09-06 20:57:50 +0000849 if (include_aliases) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000850 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches,
851 &descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000853
Kate Stoneb9c1b512016-09-06 20:57:50 +0000854 return matches.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000855}
856
Raphael Isemann7f888292018-09-13 21:26:00 +0000857CommandObjectSP
858CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases,
859 bool exact, StringList *matches,
860 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000861 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000862
Zachary Turnera4496982016-10-05 21:14:38 +0000863 std::string cmd = cmd_str;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000864
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865 if (HasCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000866 auto pos = m_command_dict.find(cmd);
Greg Claytonb5472782015-01-09 19:08:20 +0000867 if (pos != m_command_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868 command_sp = pos->second;
869 }
870
871 if (include_aliases && HasAliases()) {
872 auto alias_pos = m_alias_dict.find(cmd);
873 if (alias_pos != m_alias_dict.end())
874 command_sp = alias_pos->second;
875 }
876
877 if (HasUserCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000878 auto pos = m_user_dict.find(cmd);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000879 if (pos != m_user_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 command_sp = pos->second;
881 }
882
883 if (!exact && !command_sp) {
884 // We will only get into here if we didn't find any exact matches.
885
886 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
887
888 StringList local_matches;
889 if (matches == nullptr)
890 matches = &local_matches;
891
892 unsigned int num_cmd_matches = 0;
893 unsigned int num_alias_matches = 0;
894 unsigned int num_user_matches = 0;
895
896 // Look through the command dictionaries one by one, and if we get only one
Adrian Prantl05097242018-04-30 16:49:04 +0000897 // match from any of them in toto, then return that, otherwise return an
898 // empty CommandObjectSP and the list of matches.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000899
900 if (HasCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000901 num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str,
902 *matches, descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000903 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904
905 if (num_cmd_matches == 1) {
906 cmd.assign(matches->GetStringAtIndex(0));
Zachary Turnera4496982016-10-05 21:14:38 +0000907 auto pos = m_command_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908 if (pos != m_command_dict.end())
909 real_match_sp = pos->second;
910 }
911
912 if (include_aliases && HasAliases()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000913 num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str,
914 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000915 }
916
917 if (num_alias_matches == 1) {
918 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
919 auto alias_pos = m_alias_dict.find(cmd);
920 if (alias_pos != m_alias_dict.end())
921 alias_match_sp = alias_pos->second;
922 }
923
924 if (HasUserCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000925 num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str,
926 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000927 }
928
929 if (num_user_matches == 1) {
930 cmd.assign(
931 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
932
Zachary Turnera4496982016-10-05 21:14:38 +0000933 auto pos = m_user_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000934 if (pos != m_user_dict.end())
935 user_match_sp = pos->second;
936 }
937
938 // If we got exactly one match, return that, otherwise return the match
939 // list.
940
941 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
942 if (num_cmd_matches)
943 return real_match_sp;
944 else if (num_alias_matches)
945 return alias_match_sp;
946 else
947 return user_match_sp;
948 }
949 } else if (matches && command_sp) {
Zachary Turnera4496982016-10-05 21:14:38 +0000950 matches->AppendString(cmd_str);
Raphael Isemann7f888292018-09-13 21:26:00 +0000951 if (descriptions)
952 descriptions->AppendString(command_sp->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000953 }
954
955 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000956}
957
Zachary Turnera4496982016-10-05 21:14:38 +0000958bool CommandInterpreter::AddCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000959 const lldb::CommandObjectSP &cmd_sp,
960 bool can_replace) {
961 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000962 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
963 "tried to add a CommandObject from a different interpreter");
Kate Stonea487aa42015-01-15 00:52:41 +0000964
Zachary Turnera4496982016-10-05 21:14:38 +0000965 if (name.empty())
966 return false;
967
968 std::string name_sstr(name);
969 auto name_iter = m_command_dict.find(name_sstr);
970 if (name_iter != m_command_dict.end()) {
971 if (!can_replace || !name_iter->second->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000972 return false;
Zachary Turnera4496982016-10-05 21:14:38 +0000973 name_iter->second = cmd_sp;
974 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000975 m_command_dict[name_sstr] = cmd_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 }
Zachary Turnera4496982016-10-05 21:14:38 +0000977 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000978}
979
Zachary Turnera483f572016-10-05 21:14:49 +0000980bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 const lldb::CommandObjectSP &cmd_sp,
982 bool can_replace) {
983 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000984 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
985 "tried to add a CommandObject from a different interpreter");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000986
Kate Stoneb9c1b512016-09-06 20:57:50 +0000987 if (!name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000988 // do not allow replacement of internal commands
Zachary Turnera483f572016-10-05 21:14:49 +0000989 if (CommandExists(name)) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000990 if (!can_replace)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000991 return false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000992 if (!m_command_dict[name]->IsRemovable())
Greg Clayton5a314712011-10-14 07:41:33 +0000993 return false;
994 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000995
Zachary Turnera483f572016-10-05 21:14:49 +0000996 if (UserCommandExists(name)) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000997 if (!can_replace)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 return false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000999 if (!m_user_dict[name]->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 return false;
Caroline Tice844d2302010-12-09 22:52:49 +00001001 }
1002
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 m_user_dict[name] = cmd_sp;
1004 return true;
1005 }
1006 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001007}
1008
Zachary Turnera4496982016-10-05 21:14:38 +00001009CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
1010 bool include_aliases) const {
1011 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 // it's a multi-word command.
1013 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001014
Zachary Turnera4496982016-10-05 21:14:38 +00001015 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001016 return ret_val;
1017
1018 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +00001019 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001020 else {
1021 // We have a multi-word command (seemingly), so we need to do more work.
1022 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +00001023 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001024 include_aliases, true, nullptr);
1025 if (cmd_obj_sp.get() != nullptr) {
Adrian Prantl05097242018-04-30 16:49:04 +00001026 // Loop through the rest of the words in the command (everything passed
1027 // in was supposed to be part of a command name), and find the
1028 // appropriate sub-command SP for each command word....
Kate Stoneb9c1b512016-09-06 20:57:50 +00001029 size_t end = cmd_words.GetArgumentCount();
1030 for (size_t j = 1; j < end; ++j) {
1031 if (cmd_obj_sp->IsMultiwordObject()) {
1032 cmd_obj_sp =
1033 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
1034 if (cmd_obj_sp.get() == nullptr)
1035 // The sub-command name was invalid. Fail and return the empty
1036 // 'ret_val'.
1037 return ret_val;
1038 } else
1039 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +00001040 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001041 return ret_val;
1042 }
1043 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +00001044 // command objects for them. Assign the last object retrieved to
1045 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001046 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001048 }
1049 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001050}
1051
Raphael Isemann7f888292018-09-13 21:26:00 +00001052CommandObject *
1053CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
1054 StringList *matches,
1055 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001056 CommandObject *command_obj =
Raphael Isemann7f888292018-09-13 21:26:00 +00001057 GetCommandSP(cmd_str, false, true, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001058
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059 // If we didn't find an exact match to the command string in the commands,
Adrian Prantl05097242018-04-30 16:49:04 +00001060 // look in the aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001061
1062 if (command_obj)
1063 return command_obj;
1064
Raphael Isemann7f888292018-09-13 21:26:00 +00001065 command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001066
1067 if (command_obj)
1068 return command_obj;
1069
1070 // If there wasn't an exact match then look for an inexact one in just the
1071 // commands
Zachary Turnera4496982016-10-05 21:14:38 +00001072 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073
1074 // Finally, if there wasn't an inexact match among the commands, look for an
Adrian Prantl05097242018-04-30 16:49:04 +00001075 // inexact match in both the commands and aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076
1077 if (command_obj) {
1078 if (matches)
1079 matches->AppendString(command_obj->GetCommandName());
Raphael Isemann7f888292018-09-13 21:26:00 +00001080 if (descriptions)
1081 descriptions->AppendString(command_obj->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001082 return command_obj;
1083 }
1084
Raphael Isemann7f888292018-09-13 21:26:00 +00001085 return GetCommandSP(cmd_str, true, false, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001086}
1087
Zachary Turnera483f572016-10-05 21:14:49 +00001088bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001089 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001090}
1091
Zachary Turnera483f572016-10-05 21:14:49 +00001092bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1093 std::string &full_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001094 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1095 if (exact_match) {
1096 full_name.assign(cmd);
1097 return exact_match;
1098 } else {
1099 StringList matches;
1100 size_t num_alias_matches;
1101 num_alias_matches =
1102 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1103 if (num_alias_matches == 1) {
1104 // Make sure this isn't shadowing a command in the regular command space:
1105 StringList regular_matches;
1106 const bool include_aliases = false;
1107 const bool exact = false;
1108 CommandObjectSP cmd_obj_sp(
1109 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1110 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1111 return false;
1112 else {
1113 full_name.assign(matches.GetStringAtIndex(0));
1114 return true;
1115 }
1116 } else
1117 return false;
1118 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001119}
1120
Zachary Turnera483f572016-10-05 21:14:49 +00001121bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001123}
1124
Zachary Turnera483f572016-10-05 21:14:49 +00001125bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001126 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001127}
1128
Kate Stoneb9c1b512016-09-06 20:57:50 +00001129CommandAlias *
Zachary Turnera483f572016-10-05 21:14:49 +00001130CommandInterpreter::AddAlias(llvm::StringRef alias_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001131 lldb::CommandObjectSP &command_obj_sp,
Zachary Turnera483f572016-10-05 21:14:49 +00001132 llvm::StringRef args_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133 if (command_obj_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001134 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1135 "tried to add a CommandObject from a different interpreter");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001136
1137 std::unique_ptr<CommandAlias> command_alias_up(
1138 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1139
1140 if (command_alias_up && command_alias_up->IsValid()) {
1141 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1142 return command_alias_up.release();
1143 }
1144
1145 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001146}
1147
Zachary Turnera483f572016-10-05 21:14:49 +00001148bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001149 auto pos = m_alias_dict.find(alias_name);
1150 if (pos != m_alias_dict.end()) {
1151 m_alias_dict.erase(pos);
1152 return true;
1153 }
1154 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001155}
1156
Zachary Turnera483f572016-10-05 21:14:49 +00001157bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001158 auto pos = m_command_dict.find(cmd);
1159 if (pos != m_command_dict.end()) {
1160 if (pos->second->IsRemovable()) {
1161 // Only regular expression objects or python commands are removable
1162 m_command_dict.erase(pos);
1163 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001164 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001165 }
1166 return false;
1167}
Zachary Turnera483f572016-10-05 21:14:49 +00001168bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001169 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1170 if (pos != m_user_dict.end()) {
1171 m_user_dict.erase(pos);
1172 return true;
1173 }
1174 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001175}
1176
Kate Stoneb9c1b512016-09-06 20:57:50 +00001177void CommandInterpreter::GetHelp(CommandReturnObject &result,
1178 uint32_t cmd_types) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001179 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1180 if (!help_prologue.empty()) {
1181 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1182 help_prologue);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001183 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001184
Kate Stoneb9c1b512016-09-06 20:57:50 +00001185 CommandObject::CommandMap::const_iterator pos;
1186 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001187
Kate Stoneb9c1b512016-09-06 20:57:50 +00001188 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1189 result.AppendMessage("Debugger commands:");
1190 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001191
Kate Stoneb9c1b512016-09-06 20:57:50 +00001192 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1193 if (!(cmd_types & eCommandTypesHidden) &&
1194 (pos->first.compare(0, 1, "_") == 0))
1195 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001196
Zachary Turner0ac5f982016-11-08 04:12:42 +00001197 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1198 pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001199 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001200 result.AppendMessage("");
1201 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001202
Kate Stoneb9c1b512016-09-06 20:57:50 +00001203 if (!m_alias_dict.empty() &&
1204 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1205 result.AppendMessageWithFormat(
1206 "Current command abbreviations "
1207 "(type '%shelp command alias' for more info):\n",
1208 GetCommandPrefix());
1209 result.AppendMessage("");
1210 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001211
Kate Stoneb9c1b512016-09-06 20:57:50 +00001212 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1213 ++alias_pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001214 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
Kate Stoneb9c1b512016-09-06 20:57:50 +00001215 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001216 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 result.AppendMessage("");
1218 }
Greg Clayton14a35512011-09-11 00:01:44 +00001219
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220 if (!m_user_dict.empty() &&
1221 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1222 result.AppendMessage("Current user-defined commands:");
1223 result.AppendMessage("");
1224 max_len = FindLongestCommandWord(m_user_dict);
1225 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001226 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1227 pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001228 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229 result.AppendMessage("");
1230 }
Greg Clayton14a35512011-09-11 00:01:44 +00001231
Kate Stoneb9c1b512016-09-06 20:57:50 +00001232 result.AppendMessageWithFormat(
1233 "For more information on any command, type '%shelp <command-name>'.\n",
1234 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001235}
1236
Zachary Turnera01bccd2016-10-05 21:14:56 +00001237CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1238 llvm::StringRef &command_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001239 // This function finds the final, lowest-level, alias-resolved command object
Adrian Prantl05097242018-04-30 16:49:04 +00001240 // whose 'Execute' function will eventually be invoked by the given command
1241 // line.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001242
1243 CommandObject *cmd_obj = nullptr;
1244 size_t start = command_string.find_first_not_of(k_white_space);
1245 size_t end = 0;
1246 bool done = false;
1247 while (!done) {
1248 if (start != std::string::npos) {
1249 // Get the next word from command_string.
1250 end = command_string.find_first_of(k_white_space, start);
1251 if (end == std::string::npos)
1252 end = command_string.size();
1253 std::string cmd_word = command_string.substr(start, end - start);
1254
1255 if (cmd_obj == nullptr)
1256 // Since cmd_obj is NULL we are on our first time through this loop.
Zachary Turnera01bccd2016-10-05 21:14:56 +00001257 // Check to see if cmd_word is a valid command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001258 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001259 else if (cmd_obj->IsMultiwordObject()) {
1260 // Our current object is a multi-word object; see if the cmd_word is a
1261 // valid sub-command for our object.
1262 CommandObject *sub_cmd_obj =
1263 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1264 if (sub_cmd_obj)
1265 cmd_obj = sub_cmd_obj;
1266 else // cmd_word was not a valid sub-command word, so we are done
1267 done = true;
1268 } else
1269 // We have a cmd_obj and it is not a multi-word object, so we are done.
1270 done = true;
1271
1272 // If we didn't find a valid command object, or our command object is not
Zachary Turnera01bccd2016-10-05 21:14:56 +00001273 // a multi-word object, or we are at the end of the command_string, then
1274 // we are done. Otherwise, find the start of the next word.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001275
1276 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1277 end >= command_string.size())
1278 done = true;
1279 else
1280 start = command_string.find_first_not_of(k_white_space, end);
1281 } else
1282 // Unable to find any more words.
1283 done = true;
1284 }
1285
Zachary Turnera01bccd2016-10-05 21:14:56 +00001286 command_string = command_string.substr(end);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001287 return cmd_obj;
1288}
1289
1290static const char *k_valid_command_chars =
1291 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1292static void StripLeadingSpaces(std::string &s) {
1293 if (!s.empty()) {
1294 size_t pos = s.find_first_not_of(k_white_space);
1295 if (pos == std::string::npos)
1296 s.clear();
1297 else if (pos == 0)
1298 return;
1299 s.erase(0, pos);
1300 }
1301}
1302
1303static size_t FindArgumentTerminator(const std::string &s) {
1304 const size_t s_len = s.size();
1305 size_t offset = 0;
1306 while (offset < s_len) {
1307 size_t pos = s.find("--", offset);
1308 if (pos == std::string::npos)
1309 break;
1310 if (pos > 0) {
1311 if (isspace(s[pos - 1])) {
Adrian Prantl05097242018-04-30 16:49:04 +00001312 // Check if the string ends "\s--" (where \s is a space character) or
1313 // if we have "\s--\s".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001314 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1315 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001316 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317 }
1318 }
1319 offset = pos + 2;
1320 }
1321 return std::string::npos;
1322}
1323
1324static bool ExtractCommand(std::string &command_string, std::string &command,
1325 std::string &suffix, char &quote_char) {
1326 command.clear();
1327 suffix.clear();
1328 StripLeadingSpaces(command_string);
1329
1330 bool result = false;
1331 quote_char = '\0';
1332
1333 if (!command_string.empty()) {
1334 const char first_char = command_string[0];
1335 if (first_char == '\'' || first_char == '"') {
1336 quote_char = first_char;
1337 const size_t end_quote_pos = command_string.find(quote_char, 1);
1338 if (end_quote_pos == std::string::npos) {
1339 command.swap(command_string);
1340 command_string.erase();
1341 } else {
1342 command.assign(command_string, 1, end_quote_pos - 1);
1343 if (end_quote_pos + 1 < command_string.size())
1344 command_string.erase(0, command_string.find_first_not_of(
1345 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001346 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001347 command_string.erase();
1348 }
1349 } else {
1350 const size_t first_space_pos =
1351 command_string.find_first_of(k_white_space);
1352 if (first_space_pos == std::string::npos) {
1353 command.swap(command_string);
1354 command_string.erase();
1355 } else {
1356 command.assign(command_string, 0, first_space_pos);
1357 command_string.erase(0, command_string.find_first_not_of(
1358 k_white_space, first_space_pos));
1359 }
1360 }
1361 result = true;
1362 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001363
Kate Stoneb9c1b512016-09-06 20:57:50 +00001364 if (!command.empty()) {
1365 // actual commands can't start with '-' or '_'
1366 if (command[0] != '-' && command[0] != '_') {
1367 size_t pos = command.find_first_not_of(k_valid_command_chars);
1368 if (pos > 0 && pos != std::string::npos) {
1369 suffix.assign(command.begin() + pos, command.end());
1370 command.erase(pos);
1371 }
1372 }
1373 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001374
Kate Stoneb9c1b512016-09-06 20:57:50 +00001375 return result;
1376}
1377
1378CommandObject *CommandInterpreter::BuildAliasResult(
Zachary Turnera483f572016-10-05 21:14:49 +00001379 llvm::StringRef alias_name, std::string &raw_input_string,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001380 std::string &alias_result, CommandReturnObject &result) {
1381 CommandObject *alias_cmd_obj = nullptr;
1382 Args cmd_args(raw_input_string);
1383 alias_cmd_obj = GetCommandObject(alias_name);
1384 StreamString result_str;
1385
Zachary Turner5c28c662016-10-03 23:20:36 +00001386 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1387 alias_result.clear();
1388 return alias_cmd_obj;
1389 }
1390 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1391 ((CommandAlias *)alias_cmd_obj)->Desugar();
1392 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1393 alias_cmd_obj = desugared.first.get();
1394 std::string alias_name_str = alias_name;
1395 if ((cmd_args.GetArgumentCount() == 0) ||
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001396 (alias_name_str != cmd_args.GetArgumentAtIndex(0)))
Zachary Turner5c28c662016-10-03 23:20:36 +00001397 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001398
Zachary Turnera4496982016-10-05 21:14:38 +00001399 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001400
Zachary Turner5c28c662016-10-03 23:20:36 +00001401 if (!option_arg_vector_sp.get()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001402 alias_result = result_str.GetString();
Zachary Turner5c28c662016-10-03 23:20:36 +00001403 return alias_cmd_obj;
1404 }
1405 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001406
Zachary Turner5c28c662016-10-03 23:20:36 +00001407 int value_type;
1408 std::string option;
1409 std::string value;
1410 for (const auto &entry : *option_arg_vector) {
1411 std::tie(option, value_type, value) = entry;
1412 if (option == "<argument>") {
1413 result_str.Printf(" %s", value.c_str());
1414 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001415 }
1416
Zachary Turner5c28c662016-10-03 23:20:36 +00001417 result_str.Printf(" %s", option.c_str());
1418 if (value_type == OptionParser::eNoArgument)
1419 continue;
1420
1421 if (value_type != OptionParser::eOptionalArgument)
1422 result_str.Printf(" ");
1423 int index = GetOptionArgumentPosition(value.c_str());
1424 if (index == 0)
1425 result_str.Printf("%s", value.c_str());
1426 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1427
1428 result.AppendErrorWithFormat("Not enough arguments provided; you "
1429 "need at least %d arguments to use "
1430 "this alias.\n",
1431 index);
1432 result.SetStatus(eReturnStatusFailed);
1433 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001434 } else {
1435 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1436 if (strpos != std::string::npos)
1437 raw_input_string = raw_input_string.erase(
1438 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1439 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001440 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001441 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001442
Zachary Turnerc1564272016-11-16 21:15:24 +00001443 alias_result = result_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001444 return alias_cmd_obj;
1445}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001446
Zachary Turner97206d52017-05-12 04:51:55 +00001447Status CommandInterpreter::PreprocessCommand(std::string &command) {
Adrian Prantl05097242018-04-30 16:49:04 +00001448 // The command preprocessor needs to do things to the command line before any
1449 // parsing of arguments or anything else is done. The only current stuff that
1450 // gets preprocessed is anything enclosed in backtick ('`') characters is
1451 // evaluated as an expression and the result of the expression must be a
1452 // scalar that can be substituted into the command. An example would be:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001453 // (lldb) memory read `$rsp + 20`
Zachary Turner97206d52017-05-12 04:51:55 +00001454 Status error; // Status for any expressions that might not evaluate
Kate Stoneb9c1b512016-09-06 20:57:50 +00001455 size_t start_backtick;
1456 size_t pos = 0;
1457 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001458 // Stop if an error was encountered during the previous iteration.
1459 if (error.Fail())
1460 break;
1461
Kate Stoneb9c1b512016-09-06 20:57:50 +00001462 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
Adrian Prantl05097242018-04-30 16:49:04 +00001463 // The backtick was preceded by a '\' character, remove the slash and
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001464 // don't treat the backtick as the start of an expression.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001465 command.erase(start_backtick - 1, 1);
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001466 // No need to add one to start_backtick since we just deleted a char.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001467 pos = start_backtick;
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001468 continue;
1469 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001470
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001471 const size_t expr_content_start = start_backtick + 1;
1472 const size_t end_backtick = command.find('`', expr_content_start);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001473
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001474 if (end_backtick == std::string::npos) {
1475 // Stop if there's no end backtick.
1476 break;
1477 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001478
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001479 if (end_backtick == expr_content_start) {
1480 // Skip over empty expression. (two backticks in a row)
1481 command.erase(start_backtick, 2);
1482 continue;
1483 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001485 std::string expr_str(command, expr_content_start,
1486 end_backtick - expr_content_start);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001487
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001488 ExecutionContext exe_ctx(GetExecutionContext());
1489 Target *target = exe_ctx.GetTargetPtr();
1490
1491 // Get a dummy target to allow for calculator mode while processing
1492 // backticks. This also helps break the infinite loop caused when target is
1493 // null.
1494 if (!target)
1495 target = m_debugger.GetDummyTarget();
1496
1497 if (!target)
1498 continue;
1499
1500 ValueObjectSP expr_result_valobj_sp;
1501
1502 EvaluateExpressionOptions options;
1503 options.SetCoerceToId(false);
1504 options.SetUnwindOnError(true);
1505 options.SetIgnoreBreakpoints(true);
1506 options.SetKeepInMemory(false);
1507 options.SetTryAllThreads(true);
1508 options.SetTimeout(llvm::None);
1509
1510 ExpressionResults expr_result =
1511 target->EvaluateExpression(expr_str.c_str(), exe_ctx.GetFramePtr(),
1512 expr_result_valobj_sp, options);
1513
1514 if (expr_result == eExpressionCompleted) {
1515 Scalar scalar;
1516 if (expr_result_valobj_sp)
1517 expr_result_valobj_sp =
1518 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1519 expr_result_valobj_sp->GetDynamicValueType(), true);
1520 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1521 command.erase(start_backtick, end_backtick - start_backtick + 1);
1522 StreamString value_strm;
1523 const bool show_type = false;
1524 scalar.GetValue(&value_strm, show_type);
1525 size_t value_string_size = value_strm.GetSize();
1526 if (value_string_size) {
1527 command.insert(start_backtick, value_strm.GetString());
1528 pos = start_backtick + value_string_size;
1529 continue;
1530 } else {
1531 error.SetErrorStringWithFormat("expression value didn't result "
1532 "in a scalar value for the "
1533 "expression '%s'",
1534 expr_str.c_str());
1535 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001536 }
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001537 } else {
1538 error.SetErrorStringWithFormat("expression value didn't result "
1539 "in a scalar value for the "
1540 "expression '%s'",
1541 expr_str.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001542 break;
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001543 }
1544
1545 continue;
1546 }
1547
1548 if (expr_result_valobj_sp)
1549 error = expr_result_valobj_sp->GetError();
1550
1551 if (error.Success()) {
1552 switch (expr_result) {
1553 case eExpressionSetupError:
1554 error.SetErrorStringWithFormat(
1555 "expression setup error for the expression '%s'", expr_str.c_str());
1556 break;
1557 case eExpressionParseError:
1558 error.SetErrorStringWithFormat(
1559 "expression parse error for the expression '%s'", expr_str.c_str());
1560 break;
1561 case eExpressionResultUnavailable:
1562 error.SetErrorStringWithFormat(
1563 "expression error fetching result for the expression '%s'",
1564 expr_str.c_str());
1565 break;
1566 case eExpressionCompleted:
1567 break;
1568 case eExpressionDiscarded:
1569 error.SetErrorStringWithFormat(
1570 "expression discarded for the expression '%s'", expr_str.c_str());
1571 break;
1572 case eExpressionInterrupted:
1573 error.SetErrorStringWithFormat(
1574 "expression interrupted for the expression '%s'", expr_str.c_str());
1575 break;
1576 case eExpressionHitBreakpoint:
1577 error.SetErrorStringWithFormat(
1578 "expression hit breakpoint for the expression '%s'",
1579 expr_str.c_str());
1580 break;
1581 case eExpressionTimedOut:
1582 error.SetErrorStringWithFormat(
1583 "expression timed out for the expression '%s'", expr_str.c_str());
1584 break;
1585 case eExpressionStoppedForDebug:
1586 error.SetErrorStringWithFormat("expression stop at entry point "
1587 "for debugging for the "
1588 "expression '%s'",
1589 expr_str.c_str());
1590 break;
1591 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001592 }
1593 }
1594 return error;
1595}
1596
1597bool CommandInterpreter::HandleCommand(const char *command_line,
1598 LazyBool lazy_add_to_history,
1599 CommandReturnObject &result,
1600 ExecutionContext *override_context,
1601 bool repeat_on_empty_command,
1602 bool no_context_switching)
1603
1604{
1605
1606 std::string command_string(command_line);
1607 std::string original_command_string(command_line);
1608
1609 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
Jim Ingham8f7db522016-12-15 00:30:30 +00001610 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
Sean Callanan237c3ed2016-12-14 21:31:31 +00001611 command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001612
1613 if (log)
1614 log->Printf("Processing command: %s", command_line);
1615
Pavel Labathf9d16472017-05-15 13:02:37 +00001616 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1617 Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001618
1619 if (!no_context_switching)
1620 UpdateExecutionContext(override_context);
1621
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001622 if (WasInterrupted()) {
1623 result.AppendError("interrupted");
1624 result.SetStatus(eReturnStatusFailed);
1625 return false;
1626 }
1627
Kate Stoneb9c1b512016-09-06 20:57:50 +00001628 bool add_to_history;
1629 if (lazy_add_to_history == eLazyBoolCalculate)
1630 add_to_history = (m_command_source_depth == 0);
1631 else
1632 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1633
1634 bool empty_command = false;
1635 bool comment_command = false;
1636 if (command_string.empty())
1637 empty_command = true;
1638 else {
1639 const char *k_space_characters = "\t\n\v\f\r ";
1640
1641 size_t non_space = command_string.find_first_not_of(k_space_characters);
Adrian Prantl05097242018-04-30 16:49:04 +00001642 // Check for empty line or comment line (lines whose first non-space
1643 // character is the comment character for this interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001644 if (non_space == std::string::npos)
1645 empty_command = true;
1646 else if (command_string[non_space] == m_comment_char)
1647 comment_command = true;
1648 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001649 llvm::StringRef search_str(command_string);
1650 search_str = search_str.drop_front(non_space);
1651 if (auto hist_str = m_command_history.FindString(search_str)) {
1652 add_to_history = false;
1653 command_string = *hist_str;
1654 original_command_string = *hist_str;
1655 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001656 result.AppendErrorWithFormat("Could not find entry: %s in history",
1657 command_string.c_str());
1658 result.SetStatus(eReturnStatusFailed);
1659 return false;
1660 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001661 }
1662 }
1663
1664 if (empty_command) {
1665 if (repeat_on_empty_command) {
1666 if (m_command_history.IsEmpty()) {
1667 result.AppendError("empty command");
1668 result.SetStatus(eReturnStatusFailed);
1669 return false;
1670 } else {
1671 command_line = m_repeat_command.c_str();
1672 command_string = command_line;
1673 original_command_string = command_line;
1674 if (m_repeat_command.empty()) {
1675 result.AppendErrorWithFormat("No auto repeat.\n");
1676 result.SetStatus(eReturnStatusFailed);
1677 return false;
1678 }
1679 }
1680 add_to_history = false;
1681 } else {
1682 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1683 return true;
1684 }
1685 } else if (comment_command) {
1686 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1687 return true;
1688 }
1689
Zachary Turner97206d52017-05-12 04:51:55 +00001690 Status error(PreprocessCommand(command_string));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001691
1692 if (error.Fail()) {
1693 result.AppendError(error.AsCString());
1694 result.SetStatus(eReturnStatusFailed);
1695 return false;
1696 }
1697
1698 // Phase 1.
1699
1700 // Before we do ANY kind of argument processing, we need to figure out what
1701 // the real/final command object is for the specified command. This gets
1702 // complicated by the fact that the user could have specified an alias, and,
1703 // in translating the alias, there may also be command options and/or even
1704 // data (including raw text strings) that need to be found and inserted into
1705 // the command line as part of the translation. So this first step is plain
1706 // look-up and replacement, resulting in:
1707 // 1. the command object whose Execute method will actually be called
1708 // 2. a revised command string, with all substitutions and replacements
1709 // taken care of
1710 // From 1 above, we can determine whether the Execute function wants raw
1711 // input or not.
1712
1713 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1714
1715 // Although the user may have abbreviated the command, the command_string now
Adrian Prantl05097242018-04-30 16:49:04 +00001716 // has the command expanded to the full name. For example, if the input was
1717 // "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001718 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001719 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1720 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001721 log->Printf("HandleCommand, (revised) command_string: '%s'",
1722 command_string.c_str());
1723 const bool wants_raw_input =
1724 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1725 log->Printf("HandleCommand, wants_raw_input:'%s'",
1726 wants_raw_input ? "True" : "False");
1727 }
1728
1729 // Phase 2.
1730 // Take care of things like setting up the history command & calling the
Adrian Prantl05097242018-04-30 16:49:04 +00001731 // appropriate Execute method on the CommandObject, with the appropriate
1732 // arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001733
1734 if (cmd_obj != nullptr) {
1735 if (add_to_history) {
1736 Args command_args(command_string);
1737 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1738 if (repeat_command != nullptr)
1739 m_repeat_command.assign(repeat_command);
1740 else
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001741 m_repeat_command.assign(original_command_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001742
1743 m_command_history.AppendString(original_command_string);
1744 }
1745
1746 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001747 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001748 if (actual_cmd_name_len < command_string.length())
1749 remainder = command_string.substr(actual_cmd_name_len);
1750
1751 // Remove any initial spaces
1752 size_t pos = remainder.find_first_not_of(k_white_space);
1753 if (pos != 0 && pos != std::string::npos)
1754 remainder.erase(0, pos);
1755
1756 if (log)
1757 log->Printf(
1758 "HandleCommand, command line after removing command name(s): '%s'",
1759 remainder.c_str());
1760
1761 cmd_obj->Execute(remainder.c_str(), result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001762 }
1763
1764 if (log)
1765 log->Printf("HandleCommand, command %s",
1766 (result.Succeeded() ? "succeeded" : "did not succeed"));
1767
1768 return result.Succeeded();
1769}
1770
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001771int CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001772 int num_command_matches = 0;
1773 bool look_for_subcommand = false;
1774
1775 // For any of the command completions a unique match will be a complete word.
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001776 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001777
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001778 if (request.GetCursorIndex() == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001779 // We got nothing on the command line, so return the list of commands
1780 bool include_aliases = true;
Raphael Isemann7f888292018-09-13 21:26:00 +00001781 StringList new_matches, descriptions;
1782 num_command_matches = GetCommandNamesMatchingPartialString(
1783 "", include_aliases, new_matches, descriptions);
1784 request.AddCompletions(new_matches, descriptions);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001785 } else if (request.GetCursorIndex() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001786 // The cursor is in the first argument, so just do a lookup in the
1787 // dictionary.
Raphael Isemann7f888292018-09-13 21:26:00 +00001788 StringList new_matches, new_descriptions;
1789 CommandObject *cmd_obj =
1790 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0),
1791 &new_matches, &new_descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001792
1793 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001794 new_matches.GetStringAtIndex(0) != nullptr &&
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001795 strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001796 new_matches.GetStringAtIndex(0)) == 0) {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001797 if (request.GetParsedLine().GetArgumentCount() == 1) {
1798 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001799 } else {
1800 look_for_subcommand = true;
1801 num_command_matches = 0;
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001802 new_matches.DeleteStringAtIndex(0);
Raphael Isemann7f888292018-09-13 21:26:00 +00001803 new_descriptions.DeleteStringAtIndex(0);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001804 request.GetParsedLine().AppendArgument(llvm::StringRef());
1805 request.SetCursorIndex(request.GetCursorIndex() + 1);
1806 request.SetCursorCharPosition(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001807 }
1808 }
Raphael Isemann7f888292018-09-13 21:26:00 +00001809 request.AddCompletions(new_matches, new_descriptions);
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001810 num_command_matches = request.GetNumberOfMatches();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001811 }
1812
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001813 if (request.GetCursorIndex() > 0 || look_for_subcommand) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001814 // We are completing further on into a commands arguments, so find the
Adrian Prantl05097242018-04-30 16:49:04 +00001815 // command and tell it to complete the command. First see if there is a
1816 // matching initial command:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001817 CommandObject *command_object =
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001818 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001819 if (command_object == nullptr) {
1820 return 0;
1821 } else {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001822 request.GetParsedLine().Shift();
1823 request.SetCursorIndex(request.GetCursorIndex() - 1);
1824 num_command_matches = command_object->HandleCompletion(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001825 }
1826 }
1827
1828 return num_command_matches;
1829}
1830
1831int CommandInterpreter::HandleCompletion(
1832 const char *current_line, const char *cursor, const char *last_char,
Raphael Isemann7f888292018-09-13 21:26:00 +00001833 int match_start_point, int max_return_elements, StringList &matches,
1834 StringList &descriptions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001835
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001836 llvm::StringRef command_line(current_line, last_char - current_line);
Raphael Isemann7f888292018-09-13 21:26:00 +00001837 CompletionResult result;
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001838 CompletionRequest request(command_line, cursor - current_line,
Raphael Isemann7f888292018-09-13 21:26:00 +00001839 match_start_point, max_return_elements, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001840 // Don't complete comments, and if the line we are completing is just the
Adrian Prantl05097242018-04-30 16:49:04 +00001841 // history repeat character, substitute the appropriate history line.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001842 const char *first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001843 if (first_arg) {
1844 if (first_arg[0] == m_comment_char)
1845 return 0;
1846 else if (first_arg[0] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001847 if (auto hist_str = m_command_history.FindString(first_arg)) {
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001848 matches.InsertStringAtIndex(0, *hist_str);
Raphael Isemann7f888292018-09-13 21:26:00 +00001849 descriptions.InsertStringAtIndex(0, "Previous command history event");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001850 return -2;
1851 } else
1852 return 0;
1853 }
1854 }
1855
Kate Stoneb9c1b512016-09-06 20:57:50 +00001856 // Only max_return_elements == -1 is supported at present:
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001857 lldbassert(max_return_elements == -1);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001858
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001859 int num_command_matches = HandleCompletionMatches(request);
Raphael Isemann7f888292018-09-13 21:26:00 +00001860 result.GetMatches(matches);
1861 result.GetDescriptions(descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001862
1863 if (num_command_matches <= 0)
1864 return num_command_matches;
1865
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001866 if (request.GetParsedLine().GetArgumentCount() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001867 // If we got an empty string, insert nothing.
1868 matches.InsertStringAtIndex(0, "");
Raphael Isemann7f888292018-09-13 21:26:00 +00001869 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001870 } else {
1871 // Now figure out if there is a common substring, and if so put that in
Adrian Prantl05097242018-04-30 16:49:04 +00001872 // element 0, otherwise put an empty string in element 0.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001873 std::string command_partial_str = request.GetCursorArgumentPrefix().str();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001874
1875 std::string common_prefix;
1876 matches.LongestCommonPrefix(common_prefix);
1877 const size_t partial_name_len = command_partial_str.size();
1878 common_prefix.erase(0, partial_name_len);
1879
Adrian Prantl05097242018-04-30 16:49:04 +00001880 // If we matched a unique single command, add a space... Only do this if
1881 // the completer told us this was a complete word, however...
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001882 if (num_command_matches == 1 && request.GetWordComplete()) {
1883 char quote_char = request.GetParsedLine()[request.GetCursorIndex()].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001884 common_prefix =
1885 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1886 if (quote_char != '\0')
1887 common_prefix.push_back(quote_char);
1888 common_prefix.push_back(' ');
1889 }
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001890 matches.InsertStringAtIndex(0, common_prefix.c_str());
Raphael Isemann7f888292018-09-13 21:26:00 +00001891 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001892 }
1893 return num_command_matches;
1894}
1895
1896CommandInterpreter::~CommandInterpreter() {}
1897
Zachary Turner514d8cd2016-09-23 18:06:53 +00001898void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001899 EventSP prompt_change_event_sp(
1900 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1901 ;
1902 BroadcastEvent(prompt_change_event_sp);
1903 if (m_command_io_handler_sp)
1904 m_command_io_handler_sp->SetPrompt(new_prompt);
1905}
1906
Zachary Turner7a120c82016-11-13 03:05:58 +00001907bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001908 // Check AutoConfirm first:
1909 if (m_debugger.GetAutoConfirm())
1910 return default_answer;
1911
1912 IOHandlerConfirm *confirm =
1913 new IOHandlerConfirm(m_debugger, message, default_answer);
1914 IOHandlerSP io_handler_sp(confirm);
1915 m_debugger.RunIOHandler(io_handler_sp);
1916 return confirm->GetResponse();
1917}
1918
Zachary Turnera483f572016-10-05 21:14:49 +00001919const CommandAlias *
1920CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001921 OptionArgVectorSP ret_val;
1922
Zachary Turnera483f572016-10-05 21:14:49 +00001923 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001924 if (pos != m_alias_dict.end())
1925 return (CommandAlias *)pos->second.get();
1926
1927 return nullptr;
1928}
1929
Zachary Turnera4496982016-10-05 21:14:38 +00001930bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001931
Zachary Turnera4496982016-10-05 21:14:38 +00001932bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001933
Zachary Turnera4496982016-10-05 21:14:38 +00001934bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001935
Zachary Turnera4496982016-10-05 21:14:38 +00001936bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001937
1938void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1939 const char *alias_name,
1940 Args &cmd_args,
1941 std::string &raw_input_string,
1942 CommandReturnObject &result) {
1943 OptionArgVectorSP option_arg_vector_sp =
1944 GetAlias(alias_name)->GetOptionArguments();
1945
1946 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1947
1948 // Make sure that the alias name is the 0th element in cmd_args
1949 std::string alias_name_str = alias_name;
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001950 if (alias_name_str != cmd_args.GetArgumentAtIndex(0))
Zachary Turner5c725f32016-09-19 21:56:59 +00001951 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001952
1953 Args new_args(alias_cmd_obj->GetCommandName());
1954 if (new_args.GetArgumentCount() == 2)
1955 new_args.Shift();
1956
1957 if (option_arg_vector_sp.get()) {
1958 if (wants_raw_input) {
1959 // We have a command that both has command options and takes raw input.
Adrian Prantl05097242018-04-30 16:49:04 +00001960 // Make *sure* it has a " -- " in the right place in the
1961 // raw_input_string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001962 size_t pos = raw_input_string.find(" -- ");
1963 if (pos == std::string::npos) {
1964 // None found; assume it goes at the beginning of the raw input string
1965 raw_input_string.insert(0, " -- ");
1966 }
1967 }
1968
1969 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1970 const size_t old_size = cmd_args.GetArgumentCount();
1971 std::vector<bool> used(old_size + 1, false);
1972
1973 used[0] = true;
1974
Zachary Turner5c28c662016-10-03 23:20:36 +00001975 int value_type;
1976 std::string option;
1977 std::string value;
1978 for (const auto &option_entry : *option_arg_vector) {
1979 std::tie(option, value_type, value) = option_entry;
1980 if (option == "<argument>") {
1981 if (!wants_raw_input || (value != "--")) {
1982 // Since we inserted this above, make sure we don't insert it twice
1983 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001984 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001985 continue;
1986 }
1987
1988 if (value_type != OptionParser::eOptionalArgument)
1989 new_args.AppendArgument(option);
1990
1991 if (value == "<no-argument>")
1992 continue;
1993
1994 int index = GetOptionArgumentPosition(value.c_str());
1995 if (index == 0) {
1996 // value was NOT a positional argument; must be a real value
1997 if (value_type != OptionParser::eOptionalArgument)
1998 new_args.AppendArgument(value);
1999 else {
2000 char buffer[255];
2001 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2002 value.c_str());
2003 new_args.AppendArgument(llvm::StringRef(buffer));
2004 }
2005
2006 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
2007 result.AppendErrorWithFormat("Not enough arguments provided; you "
2008 "need at least %d arguments to use "
2009 "this alias.\n",
2010 index);
2011 result.SetStatus(eReturnStatusFailed);
2012 return;
2013 } else {
2014 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2015 size_t strpos =
2016 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
2017 if (strpos != std::string::npos) {
2018 raw_input_string = raw_input_string.erase(
2019 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2020 }
2021
2022 if (value_type != OptionParser::eOptionalArgument)
2023 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2024 else {
2025 char buffer[255];
2026 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2027 cmd_args.GetArgumentAtIndex(index));
2028 new_args.AppendArgument(buffer);
2029 }
2030 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002031 }
2032 }
2033
Zachary Turner97d2c402016-10-05 23:40:23 +00002034 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00002035 if (!used[entry.index()] && !wants_raw_input)
2036 new_args.AppendArgument(entry.value().ref);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002037 }
2038
2039 cmd_args.Clear();
2040 cmd_args.SetArguments(new_args.GetArgumentCount(),
2041 new_args.GetConstArgumentVector());
2042 } else {
2043 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2044 // This alias was not created with any options; nothing further needs to be
Adrian Prantl05097242018-04-30 16:49:04 +00002045 // done, unless it is a command that wants raw input, in which case we need
2046 // to clear the rest of the data from cmd_args, since its in the raw input
2047 // string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002048 if (wants_raw_input) {
2049 cmd_args.Clear();
2050 cmd_args.SetArguments(new_args.GetArgumentCount(),
2051 new_args.GetConstArgumentVector());
2052 }
2053 return;
2054 }
2055
2056 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2057 return;
2058}
2059
2060int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2061 int position = 0; // Any string that isn't an argument position, i.e. '%'
2062 // followed by an integer, gets a position
2063 // of zero.
2064
2065 const char *cptr = in_string;
2066
2067 // Does it start with '%'
2068 if (cptr[0] == '%') {
2069 ++cptr;
2070
2071 // Is the rest of it entirely digits?
2072 if (isdigit(cptr[0])) {
2073 const char *start = cptr;
2074 while (isdigit(cptr[0]))
2075 ++cptr;
2076
Adrian Prantl05097242018-04-30 16:49:04 +00002077 // We've gotten to the end of the digits; are we at the end of the
2078 // string?
Kate Stoneb9c1b512016-09-06 20:57:50 +00002079 if (cptr[0] == '\0')
2080 position = atoi(start);
2081 }
2082 }
2083
2084 return position;
2085}
2086
2087void CommandInterpreter::SourceInitFile(bool in_cwd,
2088 CommandReturnObject &result) {
2089 FileSpec init_file;
2090 if (in_cwd) {
2091 ExecutionContext exe_ctx(GetExecutionContext());
2092 Target *target = exe_ctx.GetTargetPtr();
2093 if (target) {
2094 // In the current working directory we don't load any program specific
2095 // .lldbinit files, we only look for a ".lldbinit" file.
2096 if (m_skip_lldbinit_files)
2097 return;
2098
2099 LoadCWDlldbinitFile should_load =
2100 target->TargetProperties::GetLoadCWDlldbinitFile();
2101 if (should_load == eLoadCWDlldbinitWarn) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002102 FileSpec dot_lldb(".lldbinit");
2103 FileSystem::Instance().Resolve(dot_lldb);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002104 llvm::SmallString<64> home_dir_path;
2105 llvm::sys::path::home_directory(home_dir_path);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002106 FileSpec homedir_dot_lldb(home_dir_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002107 homedir_dot_lldb.AppendPathComponent(".lldbinit");
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002108 FileSystem::Instance().Resolve(homedir_dot_lldb);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002109 if (FileSystem::Instance().Exists(dot_lldb) &&
Kate Stoneb9c1b512016-09-06 20:57:50 +00002110 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2111 result.AppendErrorWithFormat(
2112 "There is a .lldbinit file in the current directory which is not "
2113 "being read.\n"
2114 "To silence this warning without sourcing in the local "
2115 ".lldbinit,\n"
2116 "add the following to the lldbinit file in your home directory:\n"
2117 " settings set target.load-cwd-lldbinit false\n"
2118 "To allow lldb to source .lldbinit files in the current working "
2119 "directory,\n"
2120 "set the value of this variable to true. Only do so if you "
2121 "understand and\n"
2122 "accept the security risk.");
2123 result.SetStatus(eReturnStatusFailed);
2124 return;
2125 }
2126 } else if (should_load == eLoadCWDlldbinitTrue) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002127 init_file.SetFile("./.lldbinit", FileSpec::Style::native);
2128 FileSystem::Instance().Resolve(init_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002129 }
2130 }
2131 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002132 // If we aren't looking in the current working directory we are looking in
2133 // the home directory. We will first see if there is an application
2134 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a "-"
2135 // and the name of the program. If this file doesn't exist, we fall back to
2136 // just the "~/.lldbinit" file. We also obey any requests to not load the
2137 // init files.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002138 llvm::SmallString<64> home_dir_path;
2139 llvm::sys::path::home_directory(home_dir_path);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002140 FileSpec profilePath(home_dir_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002141 profilePath.AppendPathComponent(".lldbinit");
2142 std::string init_file_path = profilePath.GetPath();
2143
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002144 if (!m_skip_app_init_files) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002145 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2146 const char *program_name = program_file_spec.GetFilename().AsCString();
2147
2148 if (program_name) {
2149 char program_init_file_name[PATH_MAX];
2150 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2151 "%s-%s", init_file_path.c_str(), program_name);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002152 init_file.SetFile(program_init_file_name, FileSpec::Style::native);
2153 FileSystem::Instance().Resolve(init_file);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002154 if (!FileSystem::Instance().Exists(init_file))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002155 init_file.Clear();
2156 }
2157 }
2158
2159 if (!init_file && !m_skip_lldbinit_files)
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002160 init_file.SetFile(init_file_path, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002161 }
2162
2163 // If the file exists, tell HandleCommand to 'source' it; this will do the
Adrian Prantl05097242018-04-30 16:49:04 +00002164 // actual broadcasting of the commands back to any appropriate listener (see
Kate Stoneb9c1b512016-09-06 20:57:50 +00002165 // CommandObjectSource::Execute for more details).
2166
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002167 if (FileSystem::Instance().Exists(init_file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002168 const bool saved_batch = SetBatchCommandMode(true);
2169 CommandInterpreterRunOptions options;
2170 options.SetSilent(true);
2171 options.SetStopOnError(false);
2172 options.SetStopOnContinue(true);
2173
2174 HandleCommandsFromFile(init_file,
2175 nullptr, // Execution context
2176 options, result);
2177 SetBatchCommandMode(saved_batch);
2178 } else {
2179 // nothing to be done if the file doesn't exist
2180 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2181 }
2182}
2183
2184const char *CommandInterpreter::GetCommandPrefix() {
2185 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2186 return prefix == NULL ? "" : prefix;
2187}
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),
2362 eHandleCommandFlagStopOnCrash = (1u << 5)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002363};
2364
2365void CommandInterpreter::HandleCommandsFromFile(
2366 FileSpec &cmd_file, ExecutionContext *context,
2367 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002368 if (!FileSystem::Instance().Exists(cmd_file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002369 result.AppendErrorWithFormat(
2370 "Error reading commands from file %s - file not found.\n",
2371 cmd_file.GetFilename().AsCString("<Unknown>"));
2372 result.SetStatus(eReturnStatusFailed);
2373 return;
2374 }
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002375
2376 StreamFileSP input_file_sp(new StreamFile());
2377 std::string cmd_file_path = cmd_file.GetPath();
2378 Status error = FileSystem::Instance().Open(input_file_sp->GetFile(), cmd_file,
2379 File::eOpenOptionRead);
2380
2381 if (error.Fail()) {
2382 result.AppendErrorWithFormat(
2383 "error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(),
2384 error.AsCString());
2385 result.SetStatus(eReturnStatusFailed);
2386 return;
2387 }
2388
2389 Debugger &debugger = GetDebugger();
2390
2391 uint32_t flags = 0;
2392
2393 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2394 if (m_command_source_flags.empty()) {
2395 // Stop on continue by default
2396 flags |= eHandleCommandFlagStopOnContinue;
2397 } else if (m_command_source_flags.back() &
2398 eHandleCommandFlagStopOnContinue) {
2399 flags |= eHandleCommandFlagStopOnContinue;
2400 }
2401 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2402 flags |= eHandleCommandFlagStopOnContinue;
2403 }
2404
2405 if (options.m_stop_on_error == eLazyBoolCalculate) {
2406 if (m_command_source_flags.empty()) {
2407 if (GetStopCmdSourceOnError())
2408 flags |= eHandleCommandFlagStopOnError;
2409 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) {
2410 flags |= eHandleCommandFlagStopOnError;
2411 }
2412 } else if (options.m_stop_on_error == eLazyBoolYes) {
2413 flags |= eHandleCommandFlagStopOnError;
2414 }
2415
2416 // stop-on-crash can only be set, if it is present in all levels of
2417 // pushed flag sets.
2418 if (options.GetStopOnCrash()) {
2419 if (m_command_source_flags.empty()) {
2420 flags |= eHandleCommandFlagStopOnCrash;
2421 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) {
2422 flags |= eHandleCommandFlagStopOnCrash;
2423 }
2424 }
2425
2426 if (options.m_echo_commands == eLazyBoolCalculate) {
2427 if (m_command_source_flags.empty()) {
2428 // Echo command by default
2429 flags |= eHandleCommandFlagEchoCommand;
2430 } else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) {
2431 flags |= eHandleCommandFlagEchoCommand;
2432 }
2433 } else if (options.m_echo_commands == eLazyBoolYes) {
2434 flags |= eHandleCommandFlagEchoCommand;
2435 }
2436
2437 // We will only ever ask for this flag, if we echo commands in general.
2438 if (options.m_echo_comment_commands == eLazyBoolCalculate) {
2439 if (m_command_source_flags.empty()) {
2440 // Echo comments by default
2441 flags |= eHandleCommandFlagEchoCommentCommand;
2442 } else if (m_command_source_flags.back() &
2443 eHandleCommandFlagEchoCommentCommand) {
2444 flags |= eHandleCommandFlagEchoCommentCommand;
2445 }
2446 } else if (options.m_echo_comment_commands == eLazyBoolYes) {
2447 flags |= eHandleCommandFlagEchoCommentCommand;
2448 }
2449
2450 if (options.m_print_results == eLazyBoolCalculate) {
2451 if (m_command_source_flags.empty()) {
2452 // Print output by default
2453 flags |= eHandleCommandFlagPrintResult;
2454 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) {
2455 flags |= eHandleCommandFlagPrintResult;
2456 }
2457 } else if (options.m_print_results == eLazyBoolYes) {
2458 flags |= eHandleCommandFlagPrintResult;
2459 }
2460
2461 if (flags & eHandleCommandFlagPrintResult) {
2462 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2463 cmd_file_path.c_str());
2464 }
2465
2466 // Used for inheriting the right settings when "command source" might
2467 // have nested "command source" commands
2468 lldb::StreamFileSP empty_stream_sp;
2469 m_command_source_flags.push_back(flags);
2470 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2471 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2472 empty_stream_sp, // Pass in an empty stream so we inherit the top
2473 // input reader output stream
2474 empty_stream_sp, // Pass in an empty stream so we inherit the top
2475 // input reader error stream
2476 flags,
2477 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2478 // or written
2479 debugger.GetPrompt(), llvm::StringRef(),
2480 false, // Not multi-line
2481 debugger.GetUseColor(), 0, *this));
2482 const bool old_async_execution = debugger.GetAsyncExecution();
2483
2484 // Set synchronous execution if we are not stopping on continue
2485 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2486 debugger.SetAsyncExecution(false);
2487
2488 m_command_source_depth++;
2489
2490 debugger.RunIOHandler(io_handler_sp);
2491 if (!m_command_source_flags.empty())
2492 m_command_source_flags.pop_back();
2493 m_command_source_depth--;
2494 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2495 debugger.SetAsyncExecution(old_async_execution);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002496}
2497
2498ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
Jim Ingham30bac792017-07-13 19:45:54 +00002499 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
Greg Clayton79040462016-12-09 01:21:14 +00002500 if (!m_script_interpreter_sp) {
2501 if (!can_create)
2502 return nullptr;
2503 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2504 m_script_interpreter_sp =
2505 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2506 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002507 return m_script_interpreter_sp.get();
2508}
2509
2510bool 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) {
2587 size_t pos = S.find_first_of(' ');
2588 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
2800 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2801 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2802 GetProcessOutput();
2803
2804 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002805 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002806 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002807 }
2808
2809 // Now emit the command error text from the command we just executed
2810 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002811 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002812 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002813 }
2814 }
2815
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002816 FinishHandlingCommand();
2817
Kate Stoneb9c1b512016-09-06 20:57:50 +00002818 switch (result.GetStatus()) {
2819 case eReturnStatusInvalid:
2820 case eReturnStatusSuccessFinishNoResult:
2821 case eReturnStatusSuccessFinishResult:
2822 case eReturnStatusStarted:
2823 break;
2824
2825 case eReturnStatusSuccessContinuingNoResult:
2826 case eReturnStatusSuccessContinuingResult:
2827 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2828 io_handler.SetIsDone(true);
2829 break;
2830
2831 case eReturnStatusFailed:
2832 m_num_errors++;
2833 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2834 io_handler.SetIsDone(true);
2835 break;
2836
2837 case eReturnStatusQuit:
2838 m_quit_requested = true;
2839 io_handler.SetIsDone(true);
2840 break;
2841 }
2842
2843 // Finally, if we're going to stop on crash, check that here:
2844 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2845 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2846 bool should_stop = false;
2847 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2848 if (target_sp) {
2849 ProcessSP process_sp(target_sp->GetProcessSP());
2850 if (process_sp) {
2851 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2852 StopReason reason = thread_sp->GetStopReason();
2853 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2854 reason == eStopReasonInstrumentation) &&
2855 !result.GetAbnormalStopWasExpected()) {
2856 should_stop = true;
2857 break;
2858 }
2859 }
2860 }
2861 }
2862 if (should_stop) {
2863 io_handler.SetIsDone(true);
2864 m_stopped_for_crash = true;
2865 }
2866 }
2867}
2868
2869bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2870 ExecutionContext exe_ctx(GetExecutionContext());
2871 Process *process = exe_ctx.GetProcessPtr();
2872
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002873 if (InterruptCommand())
2874 return true;
2875
Kate Stoneb9c1b512016-09-06 20:57:50 +00002876 if (process) {
2877 StateType state = process->GetState();
2878 if (StateIsRunningState(state)) {
2879 process->Halt();
2880 return true; // Don't do any updating when we are running
2881 }
2882 }
2883
2884 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2885 if (script_interpreter) {
2886 if (script_interpreter->Interrupt())
2887 return true;
2888 }
2889 return false;
2890}
2891
2892void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2893 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2894 void *baton) {
2895 Debugger &debugger = GetDebugger();
2896 IOHandlerSP io_handler_sp(
2897 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2898 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002899 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2900 llvm::StringRef(), // Continuation prompt
2901 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002902 debugger.GetUseColor(),
2903 0, // Don't show line numbers
2904 delegate)); // IOHandlerDelegate
2905
2906 if (io_handler_sp) {
2907 io_handler_sp->SetUserData(baton);
2908 if (asynchronously)
2909 debugger.PushIOHandler(io_handler_sp);
2910 else
2911 debugger.RunIOHandler(io_handler_sp);
2912 }
2913}
2914
2915void CommandInterpreter::GetPythonCommandsFromIOHandler(
2916 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2917 void *baton) {
2918 Debugger &debugger = GetDebugger();
2919 IOHandlerSP io_handler_sp(
2920 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2921 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002922 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2923 llvm::StringRef(), // Continuation prompt
2924 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002925 debugger.GetUseColor(),
2926 0, // Don't show line numbers
2927 delegate)); // IOHandlerDelegate
2928
2929 if (io_handler_sp) {
2930 io_handler_sp->SetUserData(baton);
2931 if (asynchronously)
2932 debugger.PushIOHandler(io_handler_sp);
2933 else
2934 debugger.RunIOHandler(io_handler_sp);
2935 }
2936}
2937
2938bool CommandInterpreter::IsActive() {
2939 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2940}
2941
2942lldb::IOHandlerSP
2943CommandInterpreter::GetIOHandler(bool force_create,
2944 CommandInterpreterRunOptions *options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002945 // Always re-create the IOHandlerEditline in case the input changed. The old
2946 // instance might have had a non-interactive input and now it does or vice
2947 // versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002948 if (force_create || !m_command_io_handler_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002949 // Always re-create the IOHandlerEditline in case the input changed. The
2950 // old instance might have had a non-interactive input and now it does or
2951 // vice versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002952 uint32_t flags = 0;
2953
2954 if (options) {
2955 if (options->m_stop_on_continue == eLazyBoolYes)
2956 flags |= eHandleCommandFlagStopOnContinue;
2957 if (options->m_stop_on_error == eLazyBoolYes)
2958 flags |= eHandleCommandFlagStopOnError;
2959 if (options->m_stop_on_crash == eLazyBoolYes)
2960 flags |= eHandleCommandFlagStopOnCrash;
2961 if (options->m_echo_commands != eLazyBoolNo)
2962 flags |= eHandleCommandFlagEchoCommand;
Stefan Granitzc678ed72018-10-05 16:49:47 +00002963 if (options->m_echo_comment_commands != eLazyBoolNo)
2964 flags |= eHandleCommandFlagEchoCommentCommand;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002965 if (options->m_print_results != eLazyBoolNo)
2966 flags |= eHandleCommandFlagPrintResult;
2967 } else {
2968 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2969 }
2970
Jonas Devlieghere796ac802019-02-11 23:13:08 +00002971 m_command_io_handler_sp = std::make_shared<IOHandlerEditline>(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002972 m_debugger, IOHandler::Type::CommandInterpreter,
2973 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2974 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002975 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002976 false, // Don't enable multiple line input, just single line commands
2977 m_debugger.GetUseColor(),
2978 0, // Don't show line numbers
Jonas Devlieghere796ac802019-02-11 23:13:08 +00002979 *this);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002980 }
2981 return m_command_io_handler_sp;
2982}
2983
2984void CommandInterpreter::RunCommandInterpreter(
2985 bool auto_handle_events, bool spawn_thread,
2986 CommandInterpreterRunOptions &options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002987 // Always re-create the command interpreter when we run it in case any file
2988 // handles have changed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002989 bool force_create = true;
2990 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2991 m_stopped_for_crash = false;
2992
2993 if (auto_handle_events)
2994 m_debugger.StartEventHandlerThread();
2995
2996 if (spawn_thread) {
2997 m_debugger.StartIOHandlerThread();
2998 } else {
2999 m_debugger.ExecuteIOHandlers();
3000
3001 if (auto_handle_events)
3002 m_debugger.StopEventHandlerThread();
3003 }
3004}
3005
3006CommandObject *
3007CommandInterpreter::ResolveCommandImpl(std::string &command_line,
3008 CommandReturnObject &result) {
3009 std::string scratch_command(command_line); // working copy so we don't modify
3010 // command_line unless we succeed
3011 CommandObject *cmd_obj = nullptr;
3012 StreamString revised_command_line;
3013 bool wants_raw_input = false;
3014 size_t actual_cmd_name_len = 0;
3015 std::string next_word;
3016 StringList matches;
3017 bool done = false;
3018 while (!done) {
3019 char quote_char = '\0';
3020 std::string suffix;
3021 ExtractCommand(scratch_command, next_word, suffix, quote_char);
3022 if (cmd_obj == nullptr) {
3023 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003024 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00003025 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003026 bool is_real_command =
Jonas Devliegherea6682a42018-12-15 00:15:33 +00003027 (!is_alias) || (cmd_obj != nullptr && !cmd_obj->IsAlias());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003028 if (!is_real_command) {
3029 matches.Clear();
3030 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003031 cmd_obj =
3032 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003033 revised_command_line.Printf("%s", alias_result.c_str());
3034 if (cmd_obj) {
3035 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00003036 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003037 }
3038 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003039 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00003040 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
3041 actual_cmd_name_len += cmd_name.size();
3042 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003043 wants_raw_input = cmd_obj->WantsRawCommandString();
3044 } else {
3045 revised_command_line.Printf("%s", next_word.c_str());
3046 }
3047 }
3048 } else {
3049 if (cmd_obj->IsMultiwordObject()) {
3050 CommandObject *sub_cmd_obj =
3051 cmd_obj->GetSubcommandObject(next_word.c_str());
3052 if (sub_cmd_obj) {
Adrian Prantl05097242018-04-30 16:49:04 +00003053 // The subcommand's name includes the parent command's name, so
3054 // restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00003055 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3056 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003057 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00003058 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003059 cmd_obj = sub_cmd_obj;
3060 wants_raw_input = cmd_obj->WantsRawCommandString();
3061 } else {
3062 if (quote_char)
3063 revised_command_line.Printf(" %c%s%s%c", quote_char,
3064 next_word.c_str(), suffix.c_str(),
3065 quote_char);
3066 else
3067 revised_command_line.Printf(" %s%s", next_word.c_str(),
3068 suffix.c_str());
3069 done = true;
3070 }
3071 } else {
3072 if (quote_char)
3073 revised_command_line.Printf(" %c%s%s%c", quote_char,
3074 next_word.c_str(), suffix.c_str(),
3075 quote_char);
3076 else
3077 revised_command_line.Printf(" %s%s", next_word.c_str(),
3078 suffix.c_str());
3079 done = true;
3080 }
3081 }
3082
3083 if (cmd_obj == nullptr) {
3084 const size_t num_matches = matches.GetSize();
3085 if (matches.GetSize() > 1) {
3086 StreamString error_msg;
3087 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3088 next_word.c_str());
3089
3090 for (uint32_t i = 0; i < num_matches; ++i) {
3091 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3092 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003093 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003094 } else {
3095 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003096 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003097 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3098 next_word.c_str());
3099 }
3100 result.SetStatus(eReturnStatusFailed);
3101 return nullptr;
3102 }
3103
3104 if (cmd_obj->IsMultiwordObject()) {
3105 if (!suffix.empty()) {
3106 result.AppendErrorWithFormat(
3107 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3108 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003109 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003110 next_word.empty() ? "" : next_word.c_str(),
3111 next_word.empty() ? " -- " : " ", suffix.c_str());
3112 result.SetStatus(eReturnStatusFailed);
3113 return nullptr;
3114 }
3115 } else {
3116 // If we found a normal command, we are done
3117 done = true;
3118 if (!suffix.empty()) {
3119 switch (suffix[0]) {
3120 case '/':
3121 // GDB format suffixes
3122 {
3123 Options *command_options = cmd_obj->GetOptions();
3124 if (command_options &&
3125 command_options->SupportsLongOption("gdb-format")) {
3126 std::string gdb_format_option("--gdb-format=");
3127 gdb_format_option += (suffix.c_str() + 1);
3128
Zachary Turnerc1564272016-11-16 21:15:24 +00003129 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003130 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3131 if (arg_terminator_idx != std::string::npos) {
3132 // Insert the gdb format option before the "--" that terminates
3133 // options
3134 gdb_format_option.append(1, ' ');
3135 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003136 revised_command_line.Clear();
3137 revised_command_line.PutCString(cmd);
3138 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3140
3141 if (wants_raw_input &&
3142 FindArgumentTerminator(cmd) == std::string::npos)
3143 revised_command_line.PutCString(" --");
3144 } else {
3145 result.AppendErrorWithFormat(
3146 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003147 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003148 result.SetStatus(eReturnStatusFailed);
3149 return nullptr;
3150 }
3151 }
3152 break;
3153
3154 default:
3155 result.AppendErrorWithFormat(
3156 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3157 result.SetStatus(eReturnStatusFailed);
3158 return nullptr;
3159 }
3160 }
3161 }
3162 if (scratch_command.empty())
3163 done = true;
3164 }
3165
3166 if (!scratch_command.empty())
3167 revised_command_line.Printf(" %s", scratch_command.c_str());
3168
3169 if (cmd_obj != NULL)
Zachary Turnerc1564272016-11-16 21:15:24 +00003170 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003171
3172 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003173}