blob: 45fb3a05ade43ac672c182b8c0f252802bae65bd [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
Kate Stoneb9c1b512016-09-06 20:57:50 +00009#include <stdlib.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000010#include <string>
Caroline Tice4ab31c92010-10-12 21:57:09 +000011#include <vector>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012
Greg Clayton4a33d312011-06-23 17:59:56 +000013#include "CommandObjectScript.h"
Peter Collingbourne08405b62011-06-23 20:37:26 +000014#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000015
James Y Knight2ad48212018-05-22 22:53:50 +000016#include "Commands/CommandObjectApropos.h"
17#include "Commands/CommandObjectBreakpoint.h"
18#include "Commands/CommandObjectBugreport.h"
19#include "Commands/CommandObjectCommands.h"
20#include "Commands/CommandObjectDisassemble.h"
21#include "Commands/CommandObjectExpression.h"
22#include "Commands/CommandObjectFrame.h"
23#include "Commands/CommandObjectGUI.h"
24#include "Commands/CommandObjectHelp.h"
25#include "Commands/CommandObjectLanguage.h"
26#include "Commands/CommandObjectLog.h"
27#include "Commands/CommandObjectMemory.h"
28#include "Commands/CommandObjectPlatform.h"
29#include "Commands/CommandObjectPlugin.h"
30#include "Commands/CommandObjectProcess.h"
31#include "Commands/CommandObjectQuit.h"
32#include "Commands/CommandObjectRegister.h"
Jonas Devlieghere9e046f02018-11-13 19:18:16 +000033#include "Commands/CommandObjectReproducer.h"
James Y Knight2ad48212018-05-22 22:53:50 +000034#include "Commands/CommandObjectSettings.h"
35#include "Commands/CommandObjectSource.h"
36#include "Commands/CommandObjectStats.h"
37#include "Commands/CommandObjectTarget.h"
38#include "Commands/CommandObjectThread.h"
39#include "Commands/CommandObjectType.h"
40#include "Commands/CommandObjectVersion.h"
41#include "Commands/CommandObjectWatchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043#include "lldb/Core/Debugger.h"
Zachary Turner2c1f46d2015-07-30 20:28:07 +000044#include "lldb/Core/PluginManager.h"
Greg Clayton44d93782014-01-27 23:43:24 +000045#include "lldb/Core/StreamFile.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000046#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000047#include "lldb/Utility/State.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000048#include "lldb/Utility/Stream.h"
Pavel Labath38d06322017-06-29 14:32:17 +000049#include "lldb/Utility/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000050
Todd Fialacacde7d2014-09-27 16:54:22 +000051#ifndef LLDB_DISABLE_LIBEDIT
Greg Clayton44d93782014-01-27 23:43:24 +000052#include "lldb/Host/Editline.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000053#endif
Greg Clayton7fb56d02011-02-01 01:31:41 +000054#include "lldb/Host/Host.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000055#include "lldb/Host/HostInfo.h"
Enrico Granatab5887262012-10-29 21:18:03 +000056
Greg Clayton7d2ef162013-03-29 17:03:23 +000057#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000058#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000059#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000060#include "lldb/Interpreter/OptionValueProperties.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000061#include "lldb/Interpreter/Options.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000062#include "lldb/Interpreter/Property.h"
Pavel Labath145d95c2018-04-17 18:53:35 +000063#include "lldb/Utility/Args.h"
Enrico Granatab5887262012-10-29 21:18:03 +000064
Chris Lattner30fdc8d2010-06-08 16:52:24 +000065#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066#include "lldb/Target/TargetList.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000067#include "lldb/Target/Thread.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000068
Saleem Abdulrasool28606952014-06-27 05:17:41 +000069#include "llvm/ADT/STLExtras.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000070#include "llvm/ADT/SmallString.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000071#include "llvm/Support/Path.h"
Sean Callanan237c3ed2016-12-14 21:31:31 +000072#include "llvm/Support/PrettyStackTrace.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000073
Chris Lattner30fdc8d2010-06-08 16:52:24 +000074using namespace lldb;
75using namespace lldb_private;
76
Adrian McCarthy2304b6f2015-04-23 20:00:25 +000077static const char *k_white_space = " \t\v";
Greg Clayton754a9362012-08-23 00:22:02 +000078
Stefan Granitzc678ed72018-10-05 16:49:47 +000079static constexpr bool NoGlobalSetting = true;
80static constexpr uintptr_t DefaultValueTrue = true;
81static constexpr uintptr_t DefaultValueFalse = false;
82static constexpr const char *NoCStrDefault = nullptr;
83
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000084static constexpr PropertyDefinition g_properties[] = {
Stefan Granitzc678ed72018-10-05 16:49:47 +000085 {"expand-regex-aliases", OptionValue::eTypeBoolean, NoGlobalSetting,
86 DefaultValueFalse, NoCStrDefault, {},
87 "If true, regular expression alias commands will show the "
88 "expanded command that will be executed. This can be used to "
89 "debug new regular expression alias commands."},
90 {"prompt-on-quit", OptionValue::eTypeBoolean, NoGlobalSetting,
91 DefaultValueTrue, NoCStrDefault, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +000092 "If true, LLDB will prompt you before quitting if there are any live "
93 "processes being debugged. If false, LLDB will quit without asking in any "
94 "case."},
Stefan Granitzc678ed72018-10-05 16:49:47 +000095 {"stop-command-source-on-error", OptionValue::eTypeBoolean, NoGlobalSetting,
96 DefaultValueTrue, NoCStrDefault, {},
97 "If true, LLDB will stop running a 'command source' "
98 "script upon encountering an error."},
99 {"space-repl-prompts", OptionValue::eTypeBoolean, NoGlobalSetting,
100 DefaultValueFalse, NoCStrDefault, {},
101 "If true, blank lines will be printed between between REPL submissions."},
102 {"echo-commands", OptionValue::eTypeBoolean, NoGlobalSetting,
103 DefaultValueTrue, NoCStrDefault, {},
104 "If true, commands will be echoed before they are evaluated."},
105 {"echo-comment-commands", OptionValue::eTypeBoolean, NoGlobalSetting,
106 DefaultValueTrue, NoCStrDefault, {},
107 "If true, commands will be echoed even if they are pure comment lines."}};
Kate Stoneb9c1b512016-09-06 20:57:50 +0000108
109enum {
110 ePropertyExpandRegexAliases = 0,
111 ePropertyPromptOnQuit = 1,
112 ePropertyStopCmdSourceOnError = 2,
Stefan Granitzc678ed72018-10-05 16:49:47 +0000113 eSpaceReplPrompts = 3,
114 eEchoCommands = 4,
115 eEchoCommentCommands = 5
Greg Clayton754a9362012-08-23 00:22:02 +0000116};
117
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118ConstString &CommandInterpreter::GetStaticBroadcasterClass() {
119 static ConstString class_name("lldb.commandInterpreter");
120 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000121}
122
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123CommandInterpreter::CommandInterpreter(Debugger &debugger,
124 ScriptLanguage script_language,
125 bool synchronous_execution)
126 : Broadcaster(debugger.GetBroadcasterManager(),
127 CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
128 Properties(OptionValuePropertiesSP(
129 new OptionValueProperties(ConstString("interpreter")))),
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000130 IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 m_debugger(debugger), m_synchronous_execution(synchronous_execution),
132 m_skip_lldbinit_files(false), m_skip_app_init_files(false),
133 m_script_interpreter_sp(), m_command_io_handler_sp(), m_comment_char('#'),
134 m_batch_command_mode(false), m_truncation_warning(eNoTruncation),
135 m_command_source_depth(0), m_num_errors(0), m_quit_requested(false),
136 m_stopped_for_crash(false) {
137 debugger.SetScriptLanguage(script_language);
138 SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit");
139 SetEventName(eBroadcastBitResetPrompt, "reset-prompt");
140 SetEventName(eBroadcastBitQuitCommandReceived, "quit");
141 CheckInWithManager();
142 m_collection_sp->Initialize(g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000143}
144
Kate Stoneb9c1b512016-09-06 20:57:50 +0000145bool CommandInterpreter::GetExpandRegexAliases() const {
146 const uint32_t idx = ePropertyExpandRegexAliases;
147 return m_collection_sp->GetPropertyAtIndexAsBoolean(
148 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000149}
150
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151bool CommandInterpreter::GetPromptOnQuit() const {
152 const uint32_t idx = ePropertyPromptOnQuit;
153 return m_collection_sp->GetPropertyAtIndexAsBoolean(
154 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000155}
Greg Clayton754a9362012-08-23 00:22:02 +0000156
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157void CommandInterpreter::SetPromptOnQuit(bool b) {
158 const uint32_t idx = ePropertyPromptOnQuit;
159 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ilia Kacf28be2015-03-23 22:45:13 +0000160}
161
Stefan Granitzc678ed72018-10-05 16:49:47 +0000162bool CommandInterpreter::GetEchoCommands() const {
163 const uint32_t idx = eEchoCommands;
164 return m_collection_sp->GetPropertyAtIndexAsBoolean(
165 nullptr, idx, g_properties[idx].default_uint_value != 0);
166}
167
168void CommandInterpreter::SetEchoCommands(bool b) {
169 const uint32_t idx = eEchoCommands;
170 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
171}
172
173bool CommandInterpreter::GetEchoCommentCommands() const {
174 const uint32_t idx = eEchoCommentCommands;
175 return m_collection_sp->GetPropertyAtIndexAsBoolean(
176 nullptr, idx, g_properties[idx].default_uint_value != 0);
177}
178
179void CommandInterpreter::SetEchoCommentCommands(bool b) {
180 const uint32_t idx = eEchoCommentCommands;
181 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
182}
183
Raphael Isemannc094d232018-07-11 17:18:01 +0000184void CommandInterpreter::AllowExitCodeOnQuit(bool allow) {
185 m_allow_exit_code = allow;
186 if (!allow)
187 m_quit_exit_code.reset();
188}
189
190bool CommandInterpreter::SetQuitExitCode(int exit_code) {
191 if (!m_allow_exit_code)
192 return false;
193 m_quit_exit_code = exit_code;
194 return true;
195}
196
197int CommandInterpreter::GetQuitExitCode(bool &exited) const {
198 exited = m_quit_exit_code.hasValue();
199 if (exited)
200 return *m_quit_exit_code;
201 return 0;
202}
203
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204void CommandInterpreter::ResolveCommand(const char *command_line,
205 CommandReturnObject &result) {
206 std::string command = command_line;
207 if (ResolveCommandImpl(command, result) != nullptr) {
208 result.AppendMessageWithFormat("%s", command.c_str());
209 result.SetStatus(eReturnStatusSuccessFinishResult);
210 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000211}
212
Kate Stoneb9c1b512016-09-06 20:57:50 +0000213bool CommandInterpreter::GetStopCmdSourceOnError() const {
214 const uint32_t idx = ePropertyStopCmdSourceOnError;
215 return m_collection_sp->GetPropertyAtIndexAsBoolean(
216 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000217}
218
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219bool CommandInterpreter::GetSpaceReplPrompts() const {
220 const uint32_t idx = eSpaceReplPrompts;
221 return m_collection_sp->GetPropertyAtIndexAsBoolean(
222 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callanan66810412015-10-19 23:11:07 +0000223}
224
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225void CommandInterpreter::Initialize() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000226 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
227 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000228
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229 CommandReturnObject result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000230
Kate Stoneb9c1b512016-09-06 20:57:50 +0000231 LoadCommandDictionary();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000232
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233 // An alias arguments vector to reuse - reset it before use...
234 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
235
236 // Set up some initial aliases.
237 CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
238 if (cmd_obj_sp) {
239 AddAlias("q", cmd_obj_sp);
240 AddAlias("exit", cmd_obj_sp);
241 }
242
243 cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
244 if (cmd_obj_sp)
245 AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
246
247 cmd_obj_sp = GetCommandSPExact("process detach", false);
248 if (cmd_obj_sp) {
249 AddAlias("detach", cmd_obj_sp);
250 }
251
252 cmd_obj_sp = GetCommandSPExact("process continue", false);
253 if (cmd_obj_sp) {
254 AddAlias("c", cmd_obj_sp);
255 AddAlias("continue", cmd_obj_sp);
256 }
257
258 cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
259 if (cmd_obj_sp)
260 AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
261
262 cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
263 if (cmd_obj_sp)
264 AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
265
266 cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
267 if (cmd_obj_sp) {
268 AddAlias("stepi", cmd_obj_sp);
269 AddAlias("si", cmd_obj_sp);
270 }
271
272 cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
273 if (cmd_obj_sp) {
274 AddAlias("nexti", cmd_obj_sp);
275 AddAlias("ni", cmd_obj_sp);
276 }
277
278 cmd_obj_sp = GetCommandSPExact("thread step-in", false);
279 if (cmd_obj_sp) {
280 AddAlias("s", cmd_obj_sp);
281 AddAlias("step", cmd_obj_sp);
282 CommandAlias *sif_alias = AddAlias(
283 "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
284 if (sif_alias) {
285 sif_alias->SetHelp("Step through the current block, stopping if you step "
286 "directly into a function whose name matches the "
287 "TargetFunctionName.");
288 sif_alias->SetSyntax("sif <TargetFunctionName>");
Caroline Ticeca90c472011-05-06 21:37:15 +0000289 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000290 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000291
Kate Stoneb9c1b512016-09-06 20:57:50 +0000292 cmd_obj_sp = GetCommandSPExact("thread step-over", false);
293 if (cmd_obj_sp) {
294 AddAlias("n", cmd_obj_sp);
295 AddAlias("next", cmd_obj_sp);
296 }
297
298 cmd_obj_sp = GetCommandSPExact("thread step-out", false);
299 if (cmd_obj_sp) {
300 AddAlias("finish", cmd_obj_sp);
301 }
302
303 cmd_obj_sp = GetCommandSPExact("frame select", false);
304 if (cmd_obj_sp) {
305 AddAlias("f", cmd_obj_sp);
306 }
307
308 cmd_obj_sp = GetCommandSPExact("thread select", false);
309 if (cmd_obj_sp) {
310 AddAlias("t", cmd_obj_sp);
311 }
312
313 cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
314 if (cmd_obj_sp) {
315 AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
316 AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
317 }
318
319 cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
320 if (cmd_obj_sp) {
321 AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
322 AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
323 }
324
325 cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
326 if (cmd_obj_sp)
327 AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
328
329 cmd_obj_sp = GetCommandSPExact("memory read", false);
330 if (cmd_obj_sp)
331 AddAlias("x", cmd_obj_sp);
332
333 cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
334 if (cmd_obj_sp)
335 AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
336
337 cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
338 if (cmd_obj_sp)
339 AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
340
341 cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
342 if (cmd_obj_sp)
343 AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
344
345 cmd_obj_sp = GetCommandSPExact("disassemble", false);
346 if (cmd_obj_sp)
347 AddAlias("dis", cmd_obj_sp);
348
349 cmd_obj_sp = GetCommandSPExact("disassemble", false);
350 if (cmd_obj_sp)
351 AddAlias("di", cmd_obj_sp);
352
353 cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
354 if (cmd_obj_sp)
355 AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
356
357 cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
358 if (cmd_obj_sp)
359 AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
360
361 cmd_obj_sp = GetCommandSPExact("target create", false);
362 if (cmd_obj_sp)
363 AddAlias("file", cmd_obj_sp);
364
365 cmd_obj_sp = GetCommandSPExact("target modules", false);
366 if (cmd_obj_sp)
367 AddAlias("image", cmd_obj_sp);
368
369 alias_arguments_vector_sp.reset(new OptionArgVector);
370
371 cmd_obj_sp = GetCommandSPExact("expression", false);
372 if (cmd_obj_sp) {
373 AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
374 AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
375 AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
376 if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
377 po->SetHelp("Evaluate an expression on the current thread. Displays any "
378 "returned value with formatting "
379 "controlled by the type's author.");
380 po->SetHelpLong("");
Johnny Chen6d675242012-08-24 18:15:45 +0000381 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382 AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
383 AddAlias("poarray", cmd_obj_sp,
384 "--object-description --element-count %1 --")
385 ->SetHelpLong("");
386 }
Johnny Chen6d675242012-08-24 18:15:45 +0000387
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 cmd_obj_sp = GetCommandSPExact("process kill", false);
389 if (cmd_obj_sp) {
390 AddAlias("kill", cmd_obj_sp);
391 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000392
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 cmd_obj_sp = GetCommandSPExact("process launch", false);
394 if (cmd_obj_sp) {
Chaoren Lin6fc5c7f2016-02-26 03:36:27 +0000395 alias_arguments_vector_sp.reset(new OptionArgVector);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
397 AddAlias("r", cmd_obj_sp, "--");
398 AddAlias("run", cmd_obj_sp, "--");
Jason Molenda85da3122012-07-06 02:46:23 +0000399#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400#if defined(__APPLE__)
401 std::string shell_option;
402 shell_option.append("--shell-expand-args");
403 shell_option.append(" true");
404 shell_option.append(" --");
405 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
406 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
407#else
408 StreamString defaultshell;
409 defaultshell.Printf("--shell=%s --",
410 HostInfo::GetDefaultShell().GetPath().c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +0000411 AddAlias("r", cmd_obj_sp, defaultshell.GetString());
412 AddAlias("run", cmd_obj_sp, defaultshell.GetString());
Jason Molenda85da3122012-07-06 02:46:23 +0000413#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414#endif
415 }
416
417 cmd_obj_sp = GetCommandSPExact("target symbols add", false);
418 if (cmd_obj_sp) {
419 AddAlias("add-dsym", cmd_obj_sp);
420 }
421
422 cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
423 if (cmd_obj_sp) {
424 AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
425 }
Jim Ingham285ae0c2018-10-10 00:51:30 +0000426
427 cmd_obj_sp = GetCommandSPExact("frame variable", false);
428 if (cmd_obj_sp) {
Jim Ingham9082c1c2018-10-12 18:46:02 +0000429 AddAlias("v", cmd_obj_sp);
Jim Ingham285ae0c2018-10-10 00:51:30 +0000430 AddAlias("var", cmd_obj_sp);
431 AddAlias("vo", cmd_obj_sp, "--object-description");
432 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000433}
434
Kate Stoneb9c1b512016-09-06 20:57:50 +0000435void CommandInterpreter::Clear() {
436 m_command_io_handler_sp.reset();
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000437
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438 if (m_script_interpreter_sp)
439 m_script_interpreter_sp->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000440}
441
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
443 // This function has not yet been implemented.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000444
Kate Stoneb9c1b512016-09-06 20:57:50 +0000445 // Look for any embedded script command
446 // If found,
447 // get interpreter object from the command dictionary,
448 // call execute_one_command on it,
449 // get the results as a string,
450 // substitute that string for current stuff.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000451
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452 return arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000453}
454
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455void CommandInterpreter::LoadCommandDictionary() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000456 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
457 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000458
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000460
Kate Stoneb9c1b512016-09-06 20:57:50 +0000461 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
462 m_command_dict["breakpoint"] =
463 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
464 m_command_dict["bugreport"] =
465 CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
466 m_command_dict["command"] =
467 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
468 m_command_dict["disassemble"] =
469 CommandObjectSP(new CommandObjectDisassemble(*this));
470 m_command_dict["expression"] =
471 CommandObjectSP(new CommandObjectExpression(*this));
472 m_command_dict["frame"] =
473 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
474 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
475 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
476 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
477 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
478 m_command_dict["platform"] =
479 CommandObjectSP(new CommandObjectPlatform(*this));
480 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
481 m_command_dict["process"] =
482 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
483 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
484 m_command_dict["register"] =
485 CommandObjectSP(new CommandObjectRegister(*this));
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000486 m_command_dict["reproducer"] =
487 CommandObjectSP(new CommandObjectReproducer(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488 m_command_dict["script"] =
489 CommandObjectSP(new CommandObjectScript(*this, script_language));
490 m_command_dict["settings"] =
491 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
492 m_command_dict["source"] =
493 CommandObjectSP(new CommandObjectMultiwordSource(*this));
Davide Italiano24fff242018-04-13 18:02:39 +0000494 m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000495 m_command_dict["target"] =
496 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
497 m_command_dict["thread"] =
498 CommandObjectSP(new CommandObjectMultiwordThread(*this));
499 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
500 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
501 m_command_dict["watchpoint"] =
502 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
503 m_command_dict["language"] =
504 CommandObjectSP(new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000505
Kate Stoneb9c1b512016-09-06 20:57:50 +0000506 const char *break_regexes[][2] = {
507 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
508 "breakpoint set --file '%1' --line %2"},
509 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
510 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
511 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
512 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
513 "breakpoint set --name '%1'"},
514 {"^(-.*)$", "breakpoint set %1"},
515 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
516 "breakpoint set --name '%2' --shlib '%1'"},
517 {"^\\&(.*[^[:space:]])[[:space:]]*$",
518 "breakpoint set --name '%1' --skip-prologue=0"},
519 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
520 "breakpoint set --name '%1'"}};
Kate Stone7428a182016-07-14 22:03:10 +0000521
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000523
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap(
525 new CommandObjectRegexCommand(
526 *this, "_regexp-break",
Raphael Isemann129fe892018-07-30 21:41:13 +0000527 "Set a breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528 "\n"
529 "_regexp-break <filename>:<linenum>\n"
530 " main.c:12 // Break at line 12 of "
531 "main.c\n\n"
532 "_regexp-break <linenum>\n"
533 " 12 // Break at line 12 of current "
534 "file\n\n"
535 "_regexp-break 0x<address>\n"
536 " 0x1234000 // Break at address "
537 "0x1234000\n\n"
538 "_regexp-break <name>\n"
539 " main // Break in 'main' after the "
540 "prologue\n\n"
541 "_regexp-break &<name>\n"
542 " &main // Break at first instruction "
543 "in 'main'\n\n"
544 "_regexp-break <module>`<name>\n"
545 " libc.so`malloc // Break in 'malloc' from "
546 "'libc.so'\n\n"
547 "_regexp-break /<source-regex>/\n"
548 " /break here/ // Break on source lines in "
549 "current file\n"
550 " // containing text 'break "
551 "here'.\n",
552 2, CommandCompletions::eSymbolCompletion |
553 CommandCompletions::eSourceFileCompletion,
554 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000555
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 if (break_regex_cmd_ap.get()) {
557 bool success = true;
558 for (size_t i = 0; i < num_regexes; i++) {
559 success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0],
560 break_regexes[i][1]);
561 if (!success)
562 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000563 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564 success =
565 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Jim Inghamffba2292011-03-22 02:29:32 +0000566
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567 if (success) {
568 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
569 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
Jim Inghamca36cd12012-10-05 19:16:31 +0000570 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 }
Jim Inghamca36cd12012-10-05 19:16:31 +0000572
Kate Stoneb9c1b512016-09-06 20:57:50 +0000573 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap(
574 new CommandObjectRegexCommand(
575 *this, "_regexp-tbreak",
Raphael Isemann129fe892018-07-30 21:41:13 +0000576 "Set a one-shot breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000577 "\n"
578 "_regexp-break <filename>:<linenum>\n"
579 " main.c:12 // Break at line 12 of "
580 "main.c\n\n"
581 "_regexp-break <linenum>\n"
582 " 12 // Break at line 12 of current "
583 "file\n\n"
584 "_regexp-break 0x<address>\n"
585 " 0x1234000 // Break at address "
586 "0x1234000\n\n"
587 "_regexp-break <name>\n"
588 " main // Break in 'main' after the "
589 "prologue\n\n"
590 "_regexp-break &<name>\n"
591 " &main // Break at first instruction "
592 "in 'main'\n\n"
593 "_regexp-break <module>`<name>\n"
594 " libc.so`malloc // Break in 'malloc' from "
595 "'libc.so'\n\n"
596 "_regexp-break /<source-regex>/\n"
597 " /break here/ // Break on source lines in "
598 "current file\n"
599 " // containing text 'break "
600 "here'.\n",
601 2, CommandCompletions::eSymbolCompletion |
602 CommandCompletions::eSourceFileCompletion,
603 false));
604
605 if (tbreak_regex_cmd_ap.get()) {
606 bool success = true;
607 for (size_t i = 0; i < num_regexes; i++) {
608 // If you add a resultant command string longer than 1024 characters be
609 // sure to increase the size of this buffer.
610 char buffer[1024];
611 int num_printed =
Frederic Riss49c9d8b2018-06-18 04:34:33 +0000612 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1");
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000613 lldbassert(num_printed < 1024);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614 UNUSED_IF_ASSERT_DISABLED(num_printed);
615 success =
616 tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer);
617 if (!success)
618 break;
Johnny Chen6d675242012-08-24 18:15:45 +0000619 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000620 success =
621 tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Kate Stone7428a182016-07-14 22:03:10 +0000622
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623 if (success) {
624 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
625 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
626 tbreak_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000627 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628 }
Kate Stone7428a182016-07-14 22:03:10 +0000629
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap(
631 new CommandObjectRegexCommand(
632 *this, "_regexp-attach", "Attach to process by ID or name.",
633 "_regexp-attach <pid> | <process-name>", 2, 0, false));
634 if (attach_regex_cmd_ap.get()) {
635 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
636 "process attach --pid %1") &&
637 attach_regex_cmd_ap->AddRegexCommand(
638 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
639 // specified get passed to
640 // 'process attach'
641 attach_regex_cmd_ap->AddRegexCommand("^(.+)$",
642 "process attach --name '%1'") &&
643 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) {
644 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
645 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
646 attach_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000647 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000649
Kate Stoneb9c1b512016-09-06 20:57:50 +0000650 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap(
651 new CommandObjectRegexCommand(*this, "_regexp-down",
652 "Select a newer stack frame. Defaults to "
653 "moving one frame, a numeric argument can "
654 "specify an arbitrary number.",
655 "_regexp-down [<count>]", 2, 0, false));
656 if (down_regex_cmd_ap.get()) {
657 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
658 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
659 "frame select -r -%1")) {
660 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
661 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000662 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000664
Kate Stoneb9c1b512016-09-06 20:57:50 +0000665 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap(
666 new CommandObjectRegexCommand(
667 *this, "_regexp-up",
668 "Select an older stack frame. Defaults to moving one "
669 "frame, a numeric argument can specify an arbitrary number.",
670 "_regexp-up [<count>]", 2, 0, false));
671 if (up_regex_cmd_ap.get()) {
672 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
673 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
674 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
675 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000676 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000677 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000678
Kate Stoneb9c1b512016-09-06 20:57:50 +0000679 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap(
680 new CommandObjectRegexCommand(
681 *this, "_regexp-display",
682 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
683 "_regexp-display expression", 2, 0, false));
684 if (display_regex_cmd_ap.get()) {
685 if (display_regex_cmd_ap->AddRegexCommand(
686 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
687 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
688 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
689 display_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000690 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000692
Kate Stoneb9c1b512016-09-06 20:57:50 +0000693 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap(
694 new CommandObjectRegexCommand(
695 *this, "_regexp-undisplay", "Stop displaying expression at every "
696 "stop (specified by stop-hook index.)",
697 "_regexp-undisplay stop-hook-number", 2, 0, false));
698 if (undisplay_regex_cmd_ap.get()) {
699 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
700 "target stop-hook delete %1")) {
701 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
702 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
703 undisplay_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000704 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000706
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap(
708 new CommandObjectRegexCommand(
709 *this, "gdb-remote", "Connect to a process via remote GDB server. "
710 "If no host is specifed, localhost is assumed.",
711 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
712 if (connect_gdb_remote_cmd_ap.get()) {
713 if (connect_gdb_remote_cmd_ap->AddRegexCommand(
Chris Bieneman51978f52017-04-27 16:13:58 +0000714 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
715 "process connect --plugin gdb-remote connect://%1:%2") &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716 connect_gdb_remote_cmd_ap->AddRegexCommand(
717 "^([[:digit:]]+)$",
718 "process connect --plugin gdb-remote connect://localhost:%1")) {
719 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
720 m_command_dict[command_sp->GetCommandName()] = command_sp;
Jason Molenda4cddfed2012-10-05 05:29:32 +0000721 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722 }
Jason Molenda4cddfed2012-10-05 05:29:32 +0000723
Kate Stoneb9c1b512016-09-06 20:57:50 +0000724 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap(
725 new CommandObjectRegexCommand(
726 *this, "kdp-remote", "Connect to a process via remote KDP server. "
727 "If no UDP port is specified, port 41139 is "
728 "assumed.",
729 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
730 if (connect_kdp_remote_cmd_ap.get()) {
731 if (connect_kdp_remote_cmd_ap->AddRegexCommand(
732 "^([^:]+:[[:digit:]]+)$",
733 "process connect --plugin kdp-remote udp://%1") &&
734 connect_kdp_remote_cmd_ap->AddRegexCommand(
735 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
736 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
737 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Clayton6bade322013-02-01 23:33:03 +0000738 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739 }
Greg Clayton6bade322013-02-01 23:33:03 +0000740
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap(
742 new CommandObjectRegexCommand(
743 *this, "_regexp-bt",
744 "Show the current thread's call stack. Any numeric argument "
745 "displays at most that many "
746 "frames. The argument 'all' displays all threads.",
747 "bt [<digit> | all]", 2, 0, false));
748 if (bt_regex_cmd_ap.get()) {
749 // accept but don't document "bt -c <number>" -- before bt was a regex
Adrian Prantl05097242018-04-30 16:49:04 +0000750 // command if you wanted to backtrace three frames you would do "bt -c 3"
751 // but the intention is to have this emulate the gdb "bt" command and so
752 // now "bt 3" is the preferred form, in line with gdb.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$",
754 "thread backtrace -c %1") &&
755 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$",
756 "thread backtrace -c %1") &&
757 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
758 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) {
759 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
760 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Claytonef5651d2013-02-12 18:52:24 +0000761 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000762 }
Greg Claytonef5651d2013-02-12 18:52:24 +0000763
Kate Stoneb9c1b512016-09-06 20:57:50 +0000764 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap(
765 new CommandObjectRegexCommand(
766 *this, "_regexp-list",
767 "List relevant source code using one of several shorthand formats.",
768 "\n"
769 "_regexp-list <file>:<line> // List around specific file/line\n"
770 "_regexp-list <line> // List current file around specified "
771 "line\n"
772 "_regexp-list <function-name> // List specified function\n"
773 "_regexp-list 0x<address> // List around specified address\n"
774 "_regexp-list -[<count>] // List previous <count> lines\n"
775 "_regexp-list // List subsequent lines",
776 2, CommandCompletions::eSourceFileCompletion, false));
777 if (list_regex_cmd_ap.get()) {
778 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
779 "source list --line %1") &&
780 list_regex_cmd_ap->AddRegexCommand(
781 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
782 "]*$",
783 "source list --file '%1' --line %2") &&
784 list_regex_cmd_ap->AddRegexCommand(
785 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
786 "source list --address %1") &&
787 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$",
788 "source list --reverse") &&
789 list_regex_cmd_ap->AddRegexCommand(
790 "^-([[:digit:]]+)[[:space:]]*$",
791 "source list --reverse --count %1") &&
792 list_regex_cmd_ap->AddRegexCommand("^(.+)$",
793 "source list --name \"%1\"") &&
794 list_regex_cmd_ap->AddRegexCommand("^$", "source list")) {
795 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
796 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
Richard Mittonf86248d2013-09-12 02:20:34 +0000797 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000798 }
Richard Mittonf86248d2013-09-12 02:20:34 +0000799
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap(
801 new CommandObjectRegexCommand(
802 *this, "_regexp-env",
803 "Shorthand for viewing and setting environment variables.",
804 "\n"
805 "_regexp-env // Show enrivonment\n"
806 "_regexp-env <name>=<value> // Set an environment variable",
807 2, 0, false));
808 if (env_regex_cmd_ap.get()) {
809 if (env_regex_cmd_ap->AddRegexCommand("^$",
810 "settings show target.env-vars") &&
811 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
812 "settings set target.env-vars %1")) {
813 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
814 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
815 }
816 }
817
818 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap(
819 new CommandObjectRegexCommand(
820 *this, "_regexp-jump", "Set the program counter to a new address.",
821 "\n"
822 "_regexp-jump <line>\n"
823 "_regexp-jump +<line-offset> | -<line-offset>\n"
824 "_regexp-jump <file>:<line>\n"
825 "_regexp-jump *<addr>\n",
826 2, 0, false));
827 if (jump_regex_cmd_ap.get()) {
828 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$",
829 "thread jump --addr %1") &&
830 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
831 "thread jump --line %1") &&
832 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$",
833 "thread jump --file %1 --line %2") &&
834 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$",
835 "thread jump --by %1")) {
836 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
837 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
838 }
839 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000840}
841
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842int CommandInterpreter::GetCommandNamesMatchingPartialString(
Raphael Isemann7f888292018-09-13 21:26:00 +0000843 const char *cmd_str, bool include_aliases, StringList &matches,
844 StringList &descriptions) {
845 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches,
846 &descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000847
Kate Stoneb9c1b512016-09-06 20:57:50 +0000848 if (include_aliases) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000849 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches,
850 &descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000852
Kate Stoneb9c1b512016-09-06 20:57:50 +0000853 return matches.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000854}
855
Raphael Isemann7f888292018-09-13 21:26:00 +0000856CommandObjectSP
857CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases,
858 bool exact, StringList *matches,
859 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000861
Zachary Turnera4496982016-10-05 21:14:38 +0000862 std::string cmd = cmd_str;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000863
Kate Stoneb9c1b512016-09-06 20:57:50 +0000864 if (HasCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000865 auto pos = m_command_dict.find(cmd);
Greg Claytonb5472782015-01-09 19:08:20 +0000866 if (pos != m_command_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000867 command_sp = pos->second;
868 }
869
870 if (include_aliases && HasAliases()) {
871 auto alias_pos = m_alias_dict.find(cmd);
872 if (alias_pos != m_alias_dict.end())
873 command_sp = alias_pos->second;
874 }
875
876 if (HasUserCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000877 auto pos = m_user_dict.find(cmd);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000878 if (pos != m_user_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879 command_sp = pos->second;
880 }
881
882 if (!exact && !command_sp) {
883 // We will only get into here if we didn't find any exact matches.
884
885 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
886
887 StringList local_matches;
888 if (matches == nullptr)
889 matches = &local_matches;
890
891 unsigned int num_cmd_matches = 0;
892 unsigned int num_alias_matches = 0;
893 unsigned int num_user_matches = 0;
894
895 // Look through the command dictionaries one by one, and if we get only one
Adrian Prantl05097242018-04-30 16:49:04 +0000896 // match from any of them in toto, then return that, otherwise return an
897 // empty CommandObjectSP and the list of matches.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000898
899 if (HasCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000900 num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str,
901 *matches, descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000902 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000903
904 if (num_cmd_matches == 1) {
905 cmd.assign(matches->GetStringAtIndex(0));
Zachary Turnera4496982016-10-05 21:14:38 +0000906 auto pos = m_command_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000907 if (pos != m_command_dict.end())
908 real_match_sp = pos->second;
909 }
910
911 if (include_aliases && HasAliases()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000912 num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str,
913 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000914 }
915
916 if (num_alias_matches == 1) {
917 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
918 auto alias_pos = m_alias_dict.find(cmd);
919 if (alias_pos != m_alias_dict.end())
920 alias_match_sp = alias_pos->second;
921 }
922
923 if (HasUserCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000924 num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str,
925 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000926 }
927
928 if (num_user_matches == 1) {
929 cmd.assign(
930 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
931
Zachary Turnera4496982016-10-05 21:14:38 +0000932 auto pos = m_user_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000933 if (pos != m_user_dict.end())
934 user_match_sp = pos->second;
935 }
936
937 // If we got exactly one match, return that, otherwise return the match
938 // list.
939
940 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
941 if (num_cmd_matches)
942 return real_match_sp;
943 else if (num_alias_matches)
944 return alias_match_sp;
945 else
946 return user_match_sp;
947 }
948 } else if (matches && command_sp) {
Zachary Turnera4496982016-10-05 21:14:38 +0000949 matches->AppendString(cmd_str);
Raphael Isemann7f888292018-09-13 21:26:00 +0000950 if (descriptions)
951 descriptions->AppendString(command_sp->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 }
953
954 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000955}
956
Zachary Turnera4496982016-10-05 21:14:38 +0000957bool CommandInterpreter::AddCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000958 const lldb::CommandObjectSP &cmd_sp,
959 bool can_replace) {
960 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000961 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
962 "tried to add a CommandObject from a different interpreter");
Kate Stonea487aa42015-01-15 00:52:41 +0000963
Zachary Turnera4496982016-10-05 21:14:38 +0000964 if (name.empty())
965 return false;
966
967 std::string name_sstr(name);
968 auto name_iter = m_command_dict.find(name_sstr);
969 if (name_iter != m_command_dict.end()) {
970 if (!can_replace || !name_iter->second->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 return false;
Zachary Turnera4496982016-10-05 21:14:38 +0000972 name_iter->second = cmd_sp;
973 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 m_command_dict[name_sstr] = cmd_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000975 }
Zachary Turnera4496982016-10-05 21:14:38 +0000976 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000977}
978
Zachary Turnera483f572016-10-05 21:14:49 +0000979bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980 const lldb::CommandObjectSP &cmd_sp,
981 bool can_replace) {
982 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000983 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
984 "tried to add a CommandObject from a different interpreter");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000985
Kate Stoneb9c1b512016-09-06 20:57:50 +0000986 if (!name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000987 // do not allow replacement of internal commands
Zachary Turnera483f572016-10-05 21:14:49 +0000988 if (CommandExists(name)) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000989 if (!can_replace)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990 return false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000991 if (!m_command_dict[name]->IsRemovable())
Greg Clayton5a314712011-10-14 07:41:33 +0000992 return false;
993 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000994
Zachary Turnera483f572016-10-05 21:14:49 +0000995 if (UserCommandExists(name)) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000996 if (!can_replace)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000997 return false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000998 if (!m_user_dict[name]->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999 return false;
Caroline Tice844d2302010-12-09 22:52:49 +00001000 }
1001
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002 m_user_dict[name] = cmd_sp;
1003 return true;
1004 }
1005 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001006}
1007
Zachary Turnera4496982016-10-05 21:14:38 +00001008CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
1009 bool include_aliases) const {
1010 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011 // it's a multi-word command.
1012 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001013
Zachary Turnera4496982016-10-05 21:14:38 +00001014 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015 return ret_val;
1016
1017 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +00001018 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001019 else {
1020 // We have a multi-word command (seemingly), so we need to do more work.
1021 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +00001022 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001023 include_aliases, true, nullptr);
1024 if (cmd_obj_sp.get() != nullptr) {
Adrian Prantl05097242018-04-30 16:49:04 +00001025 // Loop through the rest of the words in the command (everything passed
1026 // in was supposed to be part of a command name), and find the
1027 // appropriate sub-command SP for each command word....
Kate Stoneb9c1b512016-09-06 20:57:50 +00001028 size_t end = cmd_words.GetArgumentCount();
1029 for (size_t j = 1; j < end; ++j) {
1030 if (cmd_obj_sp->IsMultiwordObject()) {
1031 cmd_obj_sp =
1032 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
1033 if (cmd_obj_sp.get() == nullptr)
1034 // The sub-command name was invalid. Fail and return the empty
1035 // 'ret_val'.
1036 return ret_val;
1037 } else
1038 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +00001039 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001040 return ret_val;
1041 }
1042 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +00001043 // command objects for them. Assign the last object retrieved to
1044 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001046 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001047 }
1048 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001049}
1050
Raphael Isemann7f888292018-09-13 21:26:00 +00001051CommandObject *
1052CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
1053 StringList *matches,
1054 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001055 CommandObject *command_obj =
Raphael Isemann7f888292018-09-13 21:26:00 +00001056 GetCommandSP(cmd_str, false, true, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001057
Kate Stoneb9c1b512016-09-06 20:57:50 +00001058 // If we didn't find an exact match to the command string in the commands,
Adrian Prantl05097242018-04-30 16:49:04 +00001059 // look in the aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001060
1061 if (command_obj)
1062 return command_obj;
1063
Raphael Isemann7f888292018-09-13 21:26:00 +00001064 command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001065
1066 if (command_obj)
1067 return command_obj;
1068
1069 // If there wasn't an exact match then look for an inexact one in just the
1070 // commands
Zachary Turnera4496982016-10-05 21:14:38 +00001071 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001072
1073 // Finally, if there wasn't an inexact match among the commands, look for an
Adrian Prantl05097242018-04-30 16:49:04 +00001074 // inexact match in both the commands and aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075
1076 if (command_obj) {
1077 if (matches)
1078 matches->AppendString(command_obj->GetCommandName());
Raphael Isemann7f888292018-09-13 21:26:00 +00001079 if (descriptions)
1080 descriptions->AppendString(command_obj->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001081 return command_obj;
1082 }
1083
Raphael Isemann7f888292018-09-13 21:26:00 +00001084 return GetCommandSP(cmd_str, true, false, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001085}
1086
Zachary Turnera483f572016-10-05 21:14:49 +00001087bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001088 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089}
1090
Zachary Turnera483f572016-10-05 21:14:49 +00001091bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1092 std::string &full_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1094 if (exact_match) {
1095 full_name.assign(cmd);
1096 return exact_match;
1097 } else {
1098 StringList matches;
1099 size_t num_alias_matches;
1100 num_alias_matches =
1101 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1102 if (num_alias_matches == 1) {
1103 // Make sure this isn't shadowing a command in the regular command space:
1104 StringList regular_matches;
1105 const bool include_aliases = false;
1106 const bool exact = false;
1107 CommandObjectSP cmd_obj_sp(
1108 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1109 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1110 return false;
1111 else {
1112 full_name.assign(matches.GetStringAtIndex(0));
1113 return true;
1114 }
1115 } else
1116 return false;
1117 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001118}
1119
Zachary Turnera483f572016-10-05 21:14:49 +00001120bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001121 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001122}
1123
Zachary Turnera483f572016-10-05 21:14:49 +00001124bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001126}
1127
Kate Stoneb9c1b512016-09-06 20:57:50 +00001128CommandAlias *
Zachary Turnera483f572016-10-05 21:14:49 +00001129CommandInterpreter::AddAlias(llvm::StringRef alias_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130 lldb::CommandObjectSP &command_obj_sp,
Zachary Turnera483f572016-10-05 21:14:49 +00001131 llvm::StringRef args_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001132 if (command_obj_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001133 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1134 "tried to add a CommandObject from a different interpreter");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001135
1136 std::unique_ptr<CommandAlias> command_alias_up(
1137 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1138
1139 if (command_alias_up && command_alias_up->IsValid()) {
1140 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1141 return command_alias_up.release();
1142 }
1143
1144 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001145}
1146
Zachary Turnera483f572016-10-05 21:14:49 +00001147bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001148 auto pos = m_alias_dict.find(alias_name);
1149 if (pos != m_alias_dict.end()) {
1150 m_alias_dict.erase(pos);
1151 return true;
1152 }
1153 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001154}
1155
Zachary Turnera483f572016-10-05 21:14:49 +00001156bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001157 auto pos = m_command_dict.find(cmd);
1158 if (pos != m_command_dict.end()) {
1159 if (pos->second->IsRemovable()) {
1160 // Only regular expression objects or python commands are removable
1161 m_command_dict.erase(pos);
1162 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001163 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001164 }
1165 return false;
1166}
Zachary Turnera483f572016-10-05 21:14:49 +00001167bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1169 if (pos != m_user_dict.end()) {
1170 m_user_dict.erase(pos);
1171 return true;
1172 }
1173 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001174}
1175
Kate Stoneb9c1b512016-09-06 20:57:50 +00001176void CommandInterpreter::GetHelp(CommandReturnObject &result,
1177 uint32_t cmd_types) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001178 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1179 if (!help_prologue.empty()) {
1180 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1181 help_prologue);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001182 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001183
Kate Stoneb9c1b512016-09-06 20:57:50 +00001184 CommandObject::CommandMap::const_iterator pos;
1185 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001186
Kate Stoneb9c1b512016-09-06 20:57:50 +00001187 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1188 result.AppendMessage("Debugger commands:");
1189 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001190
Kate Stoneb9c1b512016-09-06 20:57:50 +00001191 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1192 if (!(cmd_types & eCommandTypesHidden) &&
1193 (pos->first.compare(0, 1, "_") == 0))
1194 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001195
Zachary Turner0ac5f982016-11-08 04:12:42 +00001196 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1197 pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001198 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001199 result.AppendMessage("");
1200 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001201
Kate Stoneb9c1b512016-09-06 20:57:50 +00001202 if (!m_alias_dict.empty() &&
1203 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1204 result.AppendMessageWithFormat(
1205 "Current command abbreviations "
1206 "(type '%shelp command alias' for more info):\n",
1207 GetCommandPrefix());
1208 result.AppendMessage("");
1209 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001210
Kate Stoneb9c1b512016-09-06 20:57:50 +00001211 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1212 ++alias_pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001213 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001215 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001216 result.AppendMessage("");
1217 }
Greg Clayton14a35512011-09-11 00:01:44 +00001218
Kate Stoneb9c1b512016-09-06 20:57:50 +00001219 if (!m_user_dict.empty() &&
1220 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1221 result.AppendMessage("Current user-defined commands:");
1222 result.AppendMessage("");
1223 max_len = FindLongestCommandWord(m_user_dict);
1224 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001225 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1226 pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001227 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001228 result.AppendMessage("");
1229 }
Greg Clayton14a35512011-09-11 00:01:44 +00001230
Kate Stoneb9c1b512016-09-06 20:57:50 +00001231 result.AppendMessageWithFormat(
1232 "For more information on any command, type '%shelp <command-name>'.\n",
1233 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001234}
1235
Zachary Turnera01bccd2016-10-05 21:14:56 +00001236CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1237 llvm::StringRef &command_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001238 // This function finds the final, lowest-level, alias-resolved command object
Adrian Prantl05097242018-04-30 16:49:04 +00001239 // whose 'Execute' function will eventually be invoked by the given command
1240 // line.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241
1242 CommandObject *cmd_obj = nullptr;
1243 size_t start = command_string.find_first_not_of(k_white_space);
1244 size_t end = 0;
1245 bool done = false;
1246 while (!done) {
1247 if (start != std::string::npos) {
1248 // Get the next word from command_string.
1249 end = command_string.find_first_of(k_white_space, start);
1250 if (end == std::string::npos)
1251 end = command_string.size();
1252 std::string cmd_word = command_string.substr(start, end - start);
1253
1254 if (cmd_obj == nullptr)
1255 // Since cmd_obj is NULL we are on our first time through this loop.
Zachary Turnera01bccd2016-10-05 21:14:56 +00001256 // Check to see if cmd_word is a valid command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001257 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258 else if (cmd_obj->IsMultiwordObject()) {
1259 // Our current object is a multi-word object; see if the cmd_word is a
1260 // valid sub-command for our object.
1261 CommandObject *sub_cmd_obj =
1262 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1263 if (sub_cmd_obj)
1264 cmd_obj = sub_cmd_obj;
1265 else // cmd_word was not a valid sub-command word, so we are done
1266 done = true;
1267 } else
1268 // We have a cmd_obj and it is not a multi-word object, so we are done.
1269 done = true;
1270
1271 // If we didn't find a valid command object, or our command object is not
Zachary Turnera01bccd2016-10-05 21:14:56 +00001272 // a multi-word object, or we are at the end of the command_string, then
1273 // we are done. Otherwise, find the start of the next word.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274
1275 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1276 end >= command_string.size())
1277 done = true;
1278 else
1279 start = command_string.find_first_not_of(k_white_space, end);
1280 } else
1281 // Unable to find any more words.
1282 done = true;
1283 }
1284
Zachary Turnera01bccd2016-10-05 21:14:56 +00001285 command_string = command_string.substr(end);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001286 return cmd_obj;
1287}
1288
1289static const char *k_valid_command_chars =
1290 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1291static void StripLeadingSpaces(std::string &s) {
1292 if (!s.empty()) {
1293 size_t pos = s.find_first_not_of(k_white_space);
1294 if (pos == std::string::npos)
1295 s.clear();
1296 else if (pos == 0)
1297 return;
1298 s.erase(0, pos);
1299 }
1300}
1301
1302static size_t FindArgumentTerminator(const std::string &s) {
1303 const size_t s_len = s.size();
1304 size_t offset = 0;
1305 while (offset < s_len) {
1306 size_t pos = s.find("--", offset);
1307 if (pos == std::string::npos)
1308 break;
1309 if (pos > 0) {
1310 if (isspace(s[pos - 1])) {
Adrian Prantl05097242018-04-30 16:49:04 +00001311 // Check if the string ends "\s--" (where \s is a space character) or
1312 // if we have "\s--\s".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001313 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1314 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001315 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001316 }
1317 }
1318 offset = pos + 2;
1319 }
1320 return std::string::npos;
1321}
1322
1323static bool ExtractCommand(std::string &command_string, std::string &command,
1324 std::string &suffix, char &quote_char) {
1325 command.clear();
1326 suffix.clear();
1327 StripLeadingSpaces(command_string);
1328
1329 bool result = false;
1330 quote_char = '\0';
1331
1332 if (!command_string.empty()) {
1333 const char first_char = command_string[0];
1334 if (first_char == '\'' || first_char == '"') {
1335 quote_char = first_char;
1336 const size_t end_quote_pos = command_string.find(quote_char, 1);
1337 if (end_quote_pos == std::string::npos) {
1338 command.swap(command_string);
1339 command_string.erase();
1340 } else {
1341 command.assign(command_string, 1, end_quote_pos - 1);
1342 if (end_quote_pos + 1 < command_string.size())
1343 command_string.erase(0, command_string.find_first_not_of(
1344 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001345 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001346 command_string.erase();
1347 }
1348 } else {
1349 const size_t first_space_pos =
1350 command_string.find_first_of(k_white_space);
1351 if (first_space_pos == std::string::npos) {
1352 command.swap(command_string);
1353 command_string.erase();
1354 } else {
1355 command.assign(command_string, 0, first_space_pos);
1356 command_string.erase(0, command_string.find_first_not_of(
1357 k_white_space, first_space_pos));
1358 }
1359 }
1360 result = true;
1361 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001362
Kate Stoneb9c1b512016-09-06 20:57:50 +00001363 if (!command.empty()) {
1364 // actual commands can't start with '-' or '_'
1365 if (command[0] != '-' && command[0] != '_') {
1366 size_t pos = command.find_first_not_of(k_valid_command_chars);
1367 if (pos > 0 && pos != std::string::npos) {
1368 suffix.assign(command.begin() + pos, command.end());
1369 command.erase(pos);
1370 }
1371 }
1372 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001373
Kate Stoneb9c1b512016-09-06 20:57:50 +00001374 return result;
1375}
1376
1377CommandObject *CommandInterpreter::BuildAliasResult(
Zachary Turnera483f572016-10-05 21:14:49 +00001378 llvm::StringRef alias_name, std::string &raw_input_string,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001379 std::string &alias_result, CommandReturnObject &result) {
1380 CommandObject *alias_cmd_obj = nullptr;
1381 Args cmd_args(raw_input_string);
1382 alias_cmd_obj = GetCommandObject(alias_name);
1383 StreamString result_str;
1384
Zachary Turner5c28c662016-10-03 23:20:36 +00001385 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1386 alias_result.clear();
1387 return alias_cmd_obj;
1388 }
1389 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1390 ((CommandAlias *)alias_cmd_obj)->Desugar();
1391 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1392 alias_cmd_obj = desugared.first.get();
1393 std::string alias_name_str = alias_name;
1394 if ((cmd_args.GetArgumentCount() == 0) ||
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001395 (alias_name_str != cmd_args.GetArgumentAtIndex(0)))
Zachary Turner5c28c662016-10-03 23:20:36 +00001396 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397
Zachary Turnera4496982016-10-05 21:14:38 +00001398 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001399
Zachary Turner5c28c662016-10-03 23:20:36 +00001400 if (!option_arg_vector_sp.get()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001401 alias_result = result_str.GetString();
Zachary Turner5c28c662016-10-03 23:20:36 +00001402 return alias_cmd_obj;
1403 }
1404 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001405
Zachary Turner5c28c662016-10-03 23:20:36 +00001406 int value_type;
1407 std::string option;
1408 std::string value;
1409 for (const auto &entry : *option_arg_vector) {
1410 std::tie(option, value_type, value) = entry;
1411 if (option == "<argument>") {
1412 result_str.Printf(" %s", value.c_str());
1413 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001414 }
1415
Zachary Turner5c28c662016-10-03 23:20:36 +00001416 result_str.Printf(" %s", option.c_str());
1417 if (value_type == OptionParser::eNoArgument)
1418 continue;
1419
1420 if (value_type != OptionParser::eOptionalArgument)
1421 result_str.Printf(" ");
1422 int index = GetOptionArgumentPosition(value.c_str());
1423 if (index == 0)
1424 result_str.Printf("%s", value.c_str());
1425 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1426
1427 result.AppendErrorWithFormat("Not enough arguments provided; you "
1428 "need at least %d arguments to use "
1429 "this alias.\n",
1430 index);
1431 result.SetStatus(eReturnStatusFailed);
1432 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001433 } else {
1434 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1435 if (strpos != std::string::npos)
1436 raw_input_string = raw_input_string.erase(
1437 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1438 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001439 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001441
Zachary Turnerc1564272016-11-16 21:15:24 +00001442 alias_result = result_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 return alias_cmd_obj;
1444}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001445
Zachary Turner97206d52017-05-12 04:51:55 +00001446Status CommandInterpreter::PreprocessCommand(std::string &command) {
Adrian Prantl05097242018-04-30 16:49:04 +00001447 // The command preprocessor needs to do things to the command line before any
1448 // parsing of arguments or anything else is done. The only current stuff that
1449 // gets preprocessed is anything enclosed in backtick ('`') characters is
1450 // evaluated as an expression and the result of the expression must be a
1451 // scalar that can be substituted into the command. An example would be:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001452 // (lldb) memory read `$rsp + 20`
Zachary Turner97206d52017-05-12 04:51:55 +00001453 Status error; // Status for any expressions that might not evaluate
Kate Stoneb9c1b512016-09-06 20:57:50 +00001454 size_t start_backtick;
1455 size_t pos = 0;
1456 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001457 // Stop if an error was encountered during the previous iteration.
1458 if (error.Fail())
1459 break;
1460
Kate Stoneb9c1b512016-09-06 20:57:50 +00001461 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
Adrian Prantl05097242018-04-30 16:49:04 +00001462 // The backtick was preceded by a '\' character, remove the slash and
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001463 // don't treat the backtick as the start of an expression.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001464 command.erase(start_backtick - 1, 1);
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001465 // No need to add one to start_backtick since we just deleted a char.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001466 pos = start_backtick;
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001467 continue;
1468 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001469
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001470 const size_t expr_content_start = start_backtick + 1;
1471 const size_t end_backtick = command.find('`', expr_content_start);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001472
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001473 if (end_backtick == std::string::npos) {
1474 // Stop if there's no end backtick.
1475 break;
1476 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001477
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001478 if (end_backtick == expr_content_start) {
1479 // Skip over empty expression. (two backticks in a row)
1480 command.erase(start_backtick, 2);
1481 continue;
1482 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001483
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001484 std::string expr_str(command, expr_content_start,
1485 end_backtick - expr_content_start);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001486
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001487 ExecutionContext exe_ctx(GetExecutionContext());
1488 Target *target = exe_ctx.GetTargetPtr();
1489
1490 // Get a dummy target to allow for calculator mode while processing
1491 // backticks. This also helps break the infinite loop caused when target is
1492 // null.
1493 if (!target)
1494 target = m_debugger.GetDummyTarget();
1495
1496 if (!target)
1497 continue;
1498
1499 ValueObjectSP expr_result_valobj_sp;
1500
1501 EvaluateExpressionOptions options;
1502 options.SetCoerceToId(false);
1503 options.SetUnwindOnError(true);
1504 options.SetIgnoreBreakpoints(true);
1505 options.SetKeepInMemory(false);
1506 options.SetTryAllThreads(true);
1507 options.SetTimeout(llvm::None);
1508
1509 ExpressionResults expr_result =
1510 target->EvaluateExpression(expr_str.c_str(), exe_ctx.GetFramePtr(),
1511 expr_result_valobj_sp, options);
1512
1513 if (expr_result == eExpressionCompleted) {
1514 Scalar scalar;
1515 if (expr_result_valobj_sp)
1516 expr_result_valobj_sp =
1517 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1518 expr_result_valobj_sp->GetDynamicValueType(), true);
1519 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1520 command.erase(start_backtick, end_backtick - start_backtick + 1);
1521 StreamString value_strm;
1522 const bool show_type = false;
1523 scalar.GetValue(&value_strm, show_type);
1524 size_t value_string_size = value_strm.GetSize();
1525 if (value_string_size) {
1526 command.insert(start_backtick, value_strm.GetString());
1527 pos = start_backtick + value_string_size;
1528 continue;
1529 } else {
1530 error.SetErrorStringWithFormat("expression value didn't result "
1531 "in a scalar value for the "
1532 "expression '%s'",
1533 expr_str.c_str());
1534 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001535 }
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001536 } else {
1537 error.SetErrorStringWithFormat("expression value didn't result "
1538 "in a scalar value for the "
1539 "expression '%s'",
1540 expr_str.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001541 break;
Jonas Devlieghere76c6fea2018-12-30 17:56:30 +00001542 }
1543
1544 continue;
1545 }
1546
1547 if (expr_result_valobj_sp)
1548 error = expr_result_valobj_sp->GetError();
1549
1550 if (error.Success()) {
1551 switch (expr_result) {
1552 case eExpressionSetupError:
1553 error.SetErrorStringWithFormat(
1554 "expression setup error for the expression '%s'", expr_str.c_str());
1555 break;
1556 case eExpressionParseError:
1557 error.SetErrorStringWithFormat(
1558 "expression parse error for the expression '%s'", expr_str.c_str());
1559 break;
1560 case eExpressionResultUnavailable:
1561 error.SetErrorStringWithFormat(
1562 "expression error fetching result for the expression '%s'",
1563 expr_str.c_str());
1564 break;
1565 case eExpressionCompleted:
1566 break;
1567 case eExpressionDiscarded:
1568 error.SetErrorStringWithFormat(
1569 "expression discarded for the expression '%s'", expr_str.c_str());
1570 break;
1571 case eExpressionInterrupted:
1572 error.SetErrorStringWithFormat(
1573 "expression interrupted for the expression '%s'", expr_str.c_str());
1574 break;
1575 case eExpressionHitBreakpoint:
1576 error.SetErrorStringWithFormat(
1577 "expression hit breakpoint for the expression '%s'",
1578 expr_str.c_str());
1579 break;
1580 case eExpressionTimedOut:
1581 error.SetErrorStringWithFormat(
1582 "expression timed out for the expression '%s'", expr_str.c_str());
1583 break;
1584 case eExpressionStoppedForDebug:
1585 error.SetErrorStringWithFormat("expression stop at entry point "
1586 "for debugging for the "
1587 "expression '%s'",
1588 expr_str.c_str());
1589 break;
1590 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001591 }
1592 }
1593 return error;
1594}
1595
1596bool CommandInterpreter::HandleCommand(const char *command_line,
1597 LazyBool lazy_add_to_history,
1598 CommandReturnObject &result,
1599 ExecutionContext *override_context,
1600 bool repeat_on_empty_command,
1601 bool no_context_switching)
1602
1603{
1604
1605 std::string command_string(command_line);
1606 std::string original_command_string(command_line);
1607
1608 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
Jim Ingham8f7db522016-12-15 00:30:30 +00001609 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
Sean Callanan237c3ed2016-12-14 21:31:31 +00001610 command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001611
1612 if (log)
1613 log->Printf("Processing command: %s", command_line);
1614
Pavel Labathf9d16472017-05-15 13:02:37 +00001615 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1616 Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001617
1618 if (!no_context_switching)
1619 UpdateExecutionContext(override_context);
1620
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001621 if (WasInterrupted()) {
1622 result.AppendError("interrupted");
1623 result.SetStatus(eReturnStatusFailed);
1624 return false;
1625 }
1626
Kate Stoneb9c1b512016-09-06 20:57:50 +00001627 bool add_to_history;
1628 if (lazy_add_to_history == eLazyBoolCalculate)
1629 add_to_history = (m_command_source_depth == 0);
1630 else
1631 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1632
1633 bool empty_command = false;
1634 bool comment_command = false;
1635 if (command_string.empty())
1636 empty_command = true;
1637 else {
1638 const char *k_space_characters = "\t\n\v\f\r ";
1639
1640 size_t non_space = command_string.find_first_not_of(k_space_characters);
Adrian Prantl05097242018-04-30 16:49:04 +00001641 // Check for empty line or comment line (lines whose first non-space
1642 // character is the comment character for this interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001643 if (non_space == std::string::npos)
1644 empty_command = true;
1645 else if (command_string[non_space] == m_comment_char)
1646 comment_command = true;
1647 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001648 llvm::StringRef search_str(command_string);
1649 search_str = search_str.drop_front(non_space);
1650 if (auto hist_str = m_command_history.FindString(search_str)) {
1651 add_to_history = false;
1652 command_string = *hist_str;
1653 original_command_string = *hist_str;
1654 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001655 result.AppendErrorWithFormat("Could not find entry: %s in history",
1656 command_string.c_str());
1657 result.SetStatus(eReturnStatusFailed);
1658 return false;
1659 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001660 }
1661 }
1662
1663 if (empty_command) {
1664 if (repeat_on_empty_command) {
1665 if (m_command_history.IsEmpty()) {
1666 result.AppendError("empty command");
1667 result.SetStatus(eReturnStatusFailed);
1668 return false;
1669 } else {
1670 command_line = m_repeat_command.c_str();
1671 command_string = command_line;
1672 original_command_string = command_line;
1673 if (m_repeat_command.empty()) {
1674 result.AppendErrorWithFormat("No auto repeat.\n");
1675 result.SetStatus(eReturnStatusFailed);
1676 return false;
1677 }
1678 }
1679 add_to_history = false;
1680 } else {
1681 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1682 return true;
1683 }
1684 } else if (comment_command) {
1685 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1686 return true;
1687 }
1688
Zachary Turner97206d52017-05-12 04:51:55 +00001689 Status error(PreprocessCommand(command_string));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001690
1691 if (error.Fail()) {
1692 result.AppendError(error.AsCString());
1693 result.SetStatus(eReturnStatusFailed);
1694 return false;
1695 }
1696
1697 // Phase 1.
1698
1699 // Before we do ANY kind of argument processing, we need to figure out what
1700 // the real/final command object is for the specified command. This gets
1701 // complicated by the fact that the user could have specified an alias, and,
1702 // in translating the alias, there may also be command options and/or even
1703 // data (including raw text strings) that need to be found and inserted into
1704 // the command line as part of the translation. So this first step is plain
1705 // look-up and replacement, resulting in:
1706 // 1. the command object whose Execute method will actually be called
1707 // 2. a revised command string, with all substitutions and replacements
1708 // taken care of
1709 // From 1 above, we can determine whether the Execute function wants raw
1710 // input or not.
1711
1712 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1713
1714 // Although the user may have abbreviated the command, the command_string now
Adrian Prantl05097242018-04-30 16:49:04 +00001715 // has the command expanded to the full name. For example, if the input was
1716 // "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001717 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001718 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1719 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001720 log->Printf("HandleCommand, (revised) command_string: '%s'",
1721 command_string.c_str());
1722 const bool wants_raw_input =
1723 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1724 log->Printf("HandleCommand, wants_raw_input:'%s'",
1725 wants_raw_input ? "True" : "False");
1726 }
1727
1728 // Phase 2.
1729 // Take care of things like setting up the history command & calling the
Adrian Prantl05097242018-04-30 16:49:04 +00001730 // appropriate Execute method on the CommandObject, with the appropriate
1731 // arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001732
1733 if (cmd_obj != nullptr) {
1734 if (add_to_history) {
1735 Args command_args(command_string);
1736 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1737 if (repeat_command != nullptr)
1738 m_repeat_command.assign(repeat_command);
1739 else
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001740 m_repeat_command.assign(original_command_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001741
1742 m_command_history.AppendString(original_command_string);
1743 }
1744
1745 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001746 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001747 if (actual_cmd_name_len < command_string.length())
1748 remainder = command_string.substr(actual_cmd_name_len);
1749
1750 // Remove any initial spaces
1751 size_t pos = remainder.find_first_not_of(k_white_space);
1752 if (pos != 0 && pos != std::string::npos)
1753 remainder.erase(0, pos);
1754
1755 if (log)
1756 log->Printf(
1757 "HandleCommand, command line after removing command name(s): '%s'",
1758 remainder.c_str());
1759
1760 cmd_obj->Execute(remainder.c_str(), result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001761 }
1762
1763 if (log)
1764 log->Printf("HandleCommand, command %s",
1765 (result.Succeeded() ? "succeeded" : "did not succeed"));
1766
1767 return result.Succeeded();
1768}
1769
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001770int CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001771 int num_command_matches = 0;
1772 bool look_for_subcommand = false;
1773
1774 // For any of the command completions a unique match will be a complete word.
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001775 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001776
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001777 if (request.GetCursorIndex() == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001778 // We got nothing on the command line, so return the list of commands
1779 bool include_aliases = true;
Raphael Isemann7f888292018-09-13 21:26:00 +00001780 StringList new_matches, descriptions;
1781 num_command_matches = GetCommandNamesMatchingPartialString(
1782 "", include_aliases, new_matches, descriptions);
1783 request.AddCompletions(new_matches, descriptions);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001784 } else if (request.GetCursorIndex() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001785 // The cursor is in the first argument, so just do a lookup in the
1786 // dictionary.
Raphael Isemann7f888292018-09-13 21:26:00 +00001787 StringList new_matches, new_descriptions;
1788 CommandObject *cmd_obj =
1789 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0),
1790 &new_matches, &new_descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001791
1792 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001793 new_matches.GetStringAtIndex(0) != nullptr &&
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001794 strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001795 new_matches.GetStringAtIndex(0)) == 0) {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001796 if (request.GetParsedLine().GetArgumentCount() == 1) {
1797 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001798 } else {
1799 look_for_subcommand = true;
1800 num_command_matches = 0;
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001801 new_matches.DeleteStringAtIndex(0);
Raphael Isemann7f888292018-09-13 21:26:00 +00001802 new_descriptions.DeleteStringAtIndex(0);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001803 request.GetParsedLine().AppendArgument(llvm::StringRef());
1804 request.SetCursorIndex(request.GetCursorIndex() + 1);
1805 request.SetCursorCharPosition(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001806 }
1807 }
Raphael Isemann7f888292018-09-13 21:26:00 +00001808 request.AddCompletions(new_matches, new_descriptions);
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001809 num_command_matches = request.GetNumberOfMatches();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001810 }
1811
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001812 if (request.GetCursorIndex() > 0 || look_for_subcommand) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001813 // We are completing further on into a commands arguments, so find the
Adrian Prantl05097242018-04-30 16:49:04 +00001814 // command and tell it to complete the command. First see if there is a
1815 // matching initial command:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001816 CommandObject *command_object =
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001817 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001818 if (command_object == nullptr) {
1819 return 0;
1820 } else {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001821 request.GetParsedLine().Shift();
1822 request.SetCursorIndex(request.GetCursorIndex() - 1);
1823 num_command_matches = command_object->HandleCompletion(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001824 }
1825 }
1826
1827 return num_command_matches;
1828}
1829
1830int CommandInterpreter::HandleCompletion(
1831 const char *current_line, const char *cursor, const char *last_char,
Raphael Isemann7f888292018-09-13 21:26:00 +00001832 int match_start_point, int max_return_elements, StringList &matches,
1833 StringList &descriptions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001834
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001835 llvm::StringRef command_line(current_line, last_char - current_line);
Raphael Isemann7f888292018-09-13 21:26:00 +00001836 CompletionResult result;
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001837 CompletionRequest request(command_line, cursor - current_line,
Raphael Isemann7f888292018-09-13 21:26:00 +00001838 match_start_point, max_return_elements, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001839 // Don't complete comments, and if the line we are completing is just the
Adrian Prantl05097242018-04-30 16:49:04 +00001840 // history repeat character, substitute the appropriate history line.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001841 const char *first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001842 if (first_arg) {
1843 if (first_arg[0] == m_comment_char)
1844 return 0;
1845 else if (first_arg[0] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001846 if (auto hist_str = m_command_history.FindString(first_arg)) {
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001847 matches.InsertStringAtIndex(0, *hist_str);
Raphael Isemann7f888292018-09-13 21:26:00 +00001848 descriptions.InsertStringAtIndex(0, "Previous command history event");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001849 return -2;
1850 } else
1851 return 0;
1852 }
1853 }
1854
Kate Stoneb9c1b512016-09-06 20:57:50 +00001855 // Only max_return_elements == -1 is supported at present:
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001856 lldbassert(max_return_elements == -1);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001857
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001858 int num_command_matches = HandleCompletionMatches(request);
Raphael Isemann7f888292018-09-13 21:26:00 +00001859 result.GetMatches(matches);
1860 result.GetDescriptions(descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001861
1862 if (num_command_matches <= 0)
1863 return num_command_matches;
1864
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001865 if (request.GetParsedLine().GetArgumentCount() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001866 // If we got an empty string, insert nothing.
1867 matches.InsertStringAtIndex(0, "");
Raphael Isemann7f888292018-09-13 21:26:00 +00001868 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001869 } else {
1870 // Now figure out if there is a common substring, and if so put that in
Adrian Prantl05097242018-04-30 16:49:04 +00001871 // element 0, otherwise put an empty string in element 0.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001872 std::string command_partial_str = request.GetCursorArgumentPrefix().str();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001873
1874 std::string common_prefix;
1875 matches.LongestCommonPrefix(common_prefix);
1876 const size_t partial_name_len = command_partial_str.size();
1877 common_prefix.erase(0, partial_name_len);
1878
Adrian Prantl05097242018-04-30 16:49:04 +00001879 // If we matched a unique single command, add a space... Only do this if
1880 // the completer told us this was a complete word, however...
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001881 if (num_command_matches == 1 && request.GetWordComplete()) {
1882 char quote_char = request.GetParsedLine()[request.GetCursorIndex()].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001883 common_prefix =
1884 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1885 if (quote_char != '\0')
1886 common_prefix.push_back(quote_char);
1887 common_prefix.push_back(' ');
1888 }
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001889 matches.InsertStringAtIndex(0, common_prefix.c_str());
Raphael Isemann7f888292018-09-13 21:26:00 +00001890 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001891 }
1892 return num_command_matches;
1893}
1894
1895CommandInterpreter::~CommandInterpreter() {}
1896
Zachary Turner514d8cd2016-09-23 18:06:53 +00001897void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001898 EventSP prompt_change_event_sp(
1899 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1900 ;
1901 BroadcastEvent(prompt_change_event_sp);
1902 if (m_command_io_handler_sp)
1903 m_command_io_handler_sp->SetPrompt(new_prompt);
1904}
1905
Zachary Turner7a120c82016-11-13 03:05:58 +00001906bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001907 // Check AutoConfirm first:
1908 if (m_debugger.GetAutoConfirm())
1909 return default_answer;
1910
1911 IOHandlerConfirm *confirm =
1912 new IOHandlerConfirm(m_debugger, message, default_answer);
1913 IOHandlerSP io_handler_sp(confirm);
1914 m_debugger.RunIOHandler(io_handler_sp);
1915 return confirm->GetResponse();
1916}
1917
Zachary Turnera483f572016-10-05 21:14:49 +00001918const CommandAlias *
1919CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001920 OptionArgVectorSP ret_val;
1921
Zachary Turnera483f572016-10-05 21:14:49 +00001922 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001923 if (pos != m_alias_dict.end())
1924 return (CommandAlias *)pos->second.get();
1925
1926 return nullptr;
1927}
1928
Zachary Turnera4496982016-10-05 21:14:38 +00001929bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001930
Zachary Turnera4496982016-10-05 21:14:38 +00001931bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001932
Zachary Turnera4496982016-10-05 21:14:38 +00001933bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001934
Zachary Turnera4496982016-10-05 21:14:38 +00001935bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001936
1937void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1938 const char *alias_name,
1939 Args &cmd_args,
1940 std::string &raw_input_string,
1941 CommandReturnObject &result) {
1942 OptionArgVectorSP option_arg_vector_sp =
1943 GetAlias(alias_name)->GetOptionArguments();
1944
1945 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1946
1947 // Make sure that the alias name is the 0th element in cmd_args
1948 std::string alias_name_str = alias_name;
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001949 if (alias_name_str != cmd_args.GetArgumentAtIndex(0))
Zachary Turner5c725f32016-09-19 21:56:59 +00001950 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001951
1952 Args new_args(alias_cmd_obj->GetCommandName());
1953 if (new_args.GetArgumentCount() == 2)
1954 new_args.Shift();
1955
1956 if (option_arg_vector_sp.get()) {
1957 if (wants_raw_input) {
1958 // We have a command that both has command options and takes raw input.
Adrian Prantl05097242018-04-30 16:49:04 +00001959 // Make *sure* it has a " -- " in the right place in the
1960 // raw_input_string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001961 size_t pos = raw_input_string.find(" -- ");
1962 if (pos == std::string::npos) {
1963 // None found; assume it goes at the beginning of the raw input string
1964 raw_input_string.insert(0, " -- ");
1965 }
1966 }
1967
1968 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1969 const size_t old_size = cmd_args.GetArgumentCount();
1970 std::vector<bool> used(old_size + 1, false);
1971
1972 used[0] = true;
1973
Zachary Turner5c28c662016-10-03 23:20:36 +00001974 int value_type;
1975 std::string option;
1976 std::string value;
1977 for (const auto &option_entry : *option_arg_vector) {
1978 std::tie(option, value_type, value) = option_entry;
1979 if (option == "<argument>") {
1980 if (!wants_raw_input || (value != "--")) {
1981 // Since we inserted this above, make sure we don't insert it twice
1982 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001983 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001984 continue;
1985 }
1986
1987 if (value_type != OptionParser::eOptionalArgument)
1988 new_args.AppendArgument(option);
1989
1990 if (value == "<no-argument>")
1991 continue;
1992
1993 int index = GetOptionArgumentPosition(value.c_str());
1994 if (index == 0) {
1995 // value was NOT a positional argument; must be a real value
1996 if (value_type != OptionParser::eOptionalArgument)
1997 new_args.AppendArgument(value);
1998 else {
1999 char buffer[255];
2000 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2001 value.c_str());
2002 new_args.AppendArgument(llvm::StringRef(buffer));
2003 }
2004
2005 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
2006 result.AppendErrorWithFormat("Not enough arguments provided; you "
2007 "need at least %d arguments to use "
2008 "this alias.\n",
2009 index);
2010 result.SetStatus(eReturnStatusFailed);
2011 return;
2012 } else {
2013 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2014 size_t strpos =
2015 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
2016 if (strpos != std::string::npos) {
2017 raw_input_string = raw_input_string.erase(
2018 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2019 }
2020
2021 if (value_type != OptionParser::eOptionalArgument)
2022 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2023 else {
2024 char buffer[255];
2025 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2026 cmd_args.GetArgumentAtIndex(index));
2027 new_args.AppendArgument(buffer);
2028 }
2029 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002030 }
2031 }
2032
Zachary Turner97d2c402016-10-05 23:40:23 +00002033 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00002034 if (!used[entry.index()] && !wants_raw_input)
2035 new_args.AppendArgument(entry.value().ref);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002036 }
2037
2038 cmd_args.Clear();
2039 cmd_args.SetArguments(new_args.GetArgumentCount(),
2040 new_args.GetConstArgumentVector());
2041 } else {
2042 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2043 // This alias was not created with any options; nothing further needs to be
Adrian Prantl05097242018-04-30 16:49:04 +00002044 // done, unless it is a command that wants raw input, in which case we need
2045 // to clear the rest of the data from cmd_args, since its in the raw input
2046 // string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002047 if (wants_raw_input) {
2048 cmd_args.Clear();
2049 cmd_args.SetArguments(new_args.GetArgumentCount(),
2050 new_args.GetConstArgumentVector());
2051 }
2052 return;
2053 }
2054
2055 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2056 return;
2057}
2058
2059int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2060 int position = 0; // Any string that isn't an argument position, i.e. '%'
2061 // followed by an integer, gets a position
2062 // of zero.
2063
2064 const char *cptr = in_string;
2065
2066 // Does it start with '%'
2067 if (cptr[0] == '%') {
2068 ++cptr;
2069
2070 // Is the rest of it entirely digits?
2071 if (isdigit(cptr[0])) {
2072 const char *start = cptr;
2073 while (isdigit(cptr[0]))
2074 ++cptr;
2075
Adrian Prantl05097242018-04-30 16:49:04 +00002076 // We've gotten to the end of the digits; are we at the end of the
2077 // string?
Kate Stoneb9c1b512016-09-06 20:57:50 +00002078 if (cptr[0] == '\0')
2079 position = atoi(start);
2080 }
2081 }
2082
2083 return position;
2084}
2085
2086void CommandInterpreter::SourceInitFile(bool in_cwd,
2087 CommandReturnObject &result) {
2088 FileSpec init_file;
2089 if (in_cwd) {
2090 ExecutionContext exe_ctx(GetExecutionContext());
2091 Target *target = exe_ctx.GetTargetPtr();
2092 if (target) {
2093 // In the current working directory we don't load any program specific
2094 // .lldbinit files, we only look for a ".lldbinit" file.
2095 if (m_skip_lldbinit_files)
2096 return;
2097
2098 LoadCWDlldbinitFile should_load =
2099 target->TargetProperties::GetLoadCWDlldbinitFile();
2100 if (should_load == eLoadCWDlldbinitWarn) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002101 FileSpec dot_lldb(".lldbinit");
2102 FileSystem::Instance().Resolve(dot_lldb);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002103 llvm::SmallString<64> home_dir_path;
2104 llvm::sys::path::home_directory(home_dir_path);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002105 FileSpec homedir_dot_lldb(home_dir_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002106 homedir_dot_lldb.AppendPathComponent(".lldbinit");
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002107 FileSystem::Instance().Resolve(homedir_dot_lldb);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002108 if (FileSystem::Instance().Exists(dot_lldb) &&
Kate Stoneb9c1b512016-09-06 20:57:50 +00002109 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2110 result.AppendErrorWithFormat(
2111 "There is a .lldbinit file in the current directory which is not "
2112 "being read.\n"
2113 "To silence this warning without sourcing in the local "
2114 ".lldbinit,\n"
2115 "add the following to the lldbinit file in your home directory:\n"
2116 " settings set target.load-cwd-lldbinit false\n"
2117 "To allow lldb to source .lldbinit files in the current working "
2118 "directory,\n"
2119 "set the value of this variable to true. Only do so if you "
2120 "understand and\n"
2121 "accept the security risk.");
2122 result.SetStatus(eReturnStatusFailed);
2123 return;
2124 }
2125 } else if (should_load == eLoadCWDlldbinitTrue) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002126 init_file.SetFile("./.lldbinit", FileSpec::Style::native);
2127 FileSystem::Instance().Resolve(init_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002128 }
2129 }
2130 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002131 // If we aren't looking in the current working directory we are looking in
2132 // the home directory. We will first see if there is an application
2133 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a "-"
2134 // and the name of the program. If this file doesn't exist, we fall back to
2135 // just the "~/.lldbinit" file. We also obey any requests to not load the
2136 // init files.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002137 llvm::SmallString<64> home_dir_path;
2138 llvm::sys::path::home_directory(home_dir_path);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002139 FileSpec profilePath(home_dir_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002140 profilePath.AppendPathComponent(".lldbinit");
2141 std::string init_file_path = profilePath.GetPath();
2142
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002143 if (!m_skip_app_init_files) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002144 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2145 const char *program_name = program_file_spec.GetFilename().AsCString();
2146
2147 if (program_name) {
2148 char program_init_file_name[PATH_MAX];
2149 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2150 "%s-%s", init_file_path.c_str(), program_name);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002151 init_file.SetFile(program_init_file_name, FileSpec::Style::native);
2152 FileSystem::Instance().Resolve(init_file);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002153 if (!FileSystem::Instance().Exists(init_file))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002154 init_file.Clear();
2155 }
2156 }
2157
2158 if (!init_file && !m_skip_lldbinit_files)
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002159 init_file.SetFile(init_file_path, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002160 }
2161
2162 // If the file exists, tell HandleCommand to 'source' it; this will do the
Adrian Prantl05097242018-04-30 16:49:04 +00002163 // actual broadcasting of the commands back to any appropriate listener (see
Kate Stoneb9c1b512016-09-06 20:57:50 +00002164 // CommandObjectSource::Execute for more details).
2165
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002166 if (FileSystem::Instance().Exists(init_file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002167 const bool saved_batch = SetBatchCommandMode(true);
2168 CommandInterpreterRunOptions options;
2169 options.SetSilent(true);
2170 options.SetStopOnError(false);
2171 options.SetStopOnContinue(true);
2172
2173 HandleCommandsFromFile(init_file,
2174 nullptr, // Execution context
2175 options, result);
2176 SetBatchCommandMode(saved_batch);
2177 } else {
2178 // nothing to be done if the file doesn't exist
2179 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2180 }
2181}
2182
2183const char *CommandInterpreter::GetCommandPrefix() {
2184 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2185 return prefix == NULL ? "" : prefix;
2186}
2187
2188PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2189 PlatformSP platform_sp;
2190 if (prefer_target_platform) {
2191 ExecutionContext exe_ctx(GetExecutionContext());
2192 Target *target = exe_ctx.GetTargetPtr();
2193 if (target)
2194 platform_sp = target->GetPlatform();
2195 }
2196
2197 if (!platform_sp)
2198 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2199 return platform_sp;
2200}
2201
2202void CommandInterpreter::HandleCommands(const StringList &commands,
2203 ExecutionContext *override_context,
2204 CommandInterpreterRunOptions &options,
2205 CommandReturnObject &result) {
2206 size_t num_lines = commands.GetSize();
2207
2208 // If we are going to continue past a "continue" then we need to run the
Adrian Prantl05097242018-04-30 16:49:04 +00002209 // commands synchronously. Make sure you reset this value anywhere you return
2210 // from the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002211
2212 bool old_async_execution = m_debugger.GetAsyncExecution();
2213
2214 // If we've been given an execution context, set it at the start, but don't
Adrian Prantl05097242018-04-30 16:49:04 +00002215 // keep resetting it or we will cause series of commands that change the
2216 // context, then do an operation that relies on that context to fail.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002217
2218 if (override_context != nullptr)
2219 UpdateExecutionContext(override_context);
2220
2221 if (!options.GetStopOnContinue()) {
2222 m_debugger.SetAsyncExecution(false);
2223 }
2224
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002225 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002226 const char *cmd = commands.GetStringAtIndex(idx);
2227 if (cmd[0] == '\0')
2228 continue;
2229
2230 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002231 // TODO: Add Stream support.
2232 result.AppendMessageWithFormat("%s %s\n",
2233 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002234 }
2235
2236 CommandReturnObject tmp_result;
2237 // If override_context is not NULL, pass no_context_switching = true for
2238 // HandleCommand() since we updated our context already.
2239
2240 // We might call into a regex or alias command, in which case the
Adrian Prantl05097242018-04-30 16:49:04 +00002241 // add_to_history will get lost. This m_command_source_depth dingus is the
2242 // way we turn off adding to the history in that case, so set it up here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002243 if (!options.GetAddToHistory())
2244 m_command_source_depth++;
2245 bool success =
2246 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2247 nullptr, /* override_context */
2248 true, /* repeat_on_empty_command */
2249 override_context != nullptr /* no_context_switching */);
2250 if (!options.GetAddToHistory())
2251 m_command_source_depth--;
2252
2253 if (options.GetPrintResults()) {
2254 if (tmp_result.Succeeded())
Zachary Turner03c9f362016-11-14 23:23:31 +00002255 result.AppendMessage(tmp_result.GetOutputData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002256 }
2257
2258 if (!success || !tmp_result.Succeeded()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002259 llvm::StringRef error_msg = tmp_result.GetErrorData();
2260 if (error_msg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002261 error_msg = "<unknown error>.\n";
2262 if (options.GetStopOnError()) {
2263 result.AppendErrorWithFormat(
2264 "Aborting reading of commands after command #%" PRIu64
2265 ": '%s' failed with %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00002266 (uint64_t)idx, cmd, error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002267 result.SetStatus(eReturnStatusFailed);
2268 m_debugger.SetAsyncExecution(old_async_execution);
2269 return;
2270 } else if (options.GetPrintResults()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002271 result.AppendMessageWithFormat(
2272 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2273 error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002274 }
2275 }
2276
2277 if (result.GetImmediateOutputStream())
2278 result.GetImmediateOutputStream()->Flush();
2279
2280 if (result.GetImmediateErrorStream())
2281 result.GetImmediateErrorStream()->Flush();
2282
Adrian Prantl05097242018-04-30 16:49:04 +00002283 // N.B. Can't depend on DidChangeProcessState, because the state coming
2284 // into the command execution could be running (for instance in Breakpoint
2285 // Commands. So we check the return value to see if it is has running in
2286 // it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002287 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2288 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2289 if (options.GetStopOnContinue()) {
2290 // If we caused the target to proceed, and we're going to stop in that
Adrian Prantl05097242018-04-30 16:49:04 +00002291 // case, set the status in our real result before returning. This is
2292 // an error if the continue was not the last command in the set of
2293 // commands to be run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002294 if (idx != num_lines - 1)
2295 result.AppendErrorWithFormat(
2296 "Aborting reading of commands after command #%" PRIu64
2297 ": '%s' continued the target.\n",
2298 (uint64_t)idx + 1, cmd);
2299 else
2300 result.AppendMessageWithFormat("Command #%" PRIu64
2301 " '%s' continued the target.\n",
2302 (uint64_t)idx + 1, cmd);
2303
2304 result.SetStatus(tmp_result.GetStatus());
2305 m_debugger.SetAsyncExecution(old_async_execution);
2306
2307 return;
2308 }
2309 }
2310
2311 // Also check for "stop on crash here:
2312 bool should_stop = false;
2313 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2314 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2315 if (target_sp) {
2316 ProcessSP process_sp(target_sp->GetProcessSP());
2317 if (process_sp) {
2318 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2319 StopReason reason = thread_sp->GetStopReason();
2320 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2321 reason == eStopReasonInstrumentation) {
2322 should_stop = true;
2323 break;
2324 }
2325 }
2326 }
2327 }
2328 if (should_stop) {
2329 if (idx != num_lines - 1)
2330 result.AppendErrorWithFormat(
2331 "Aborting reading of commands after command #%" PRIu64
2332 ": '%s' stopped with a signal or exception.\n",
2333 (uint64_t)idx + 1, cmd);
2334 else
2335 result.AppendMessageWithFormat(
2336 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2337 (uint64_t)idx + 1, cmd);
2338
2339 result.SetStatus(tmp_result.GetStatus());
2340 m_debugger.SetAsyncExecution(old_async_execution);
2341
2342 return;
2343 }
2344 }
2345 }
2346
2347 result.SetStatus(eReturnStatusSuccessFinishResult);
2348 m_debugger.SetAsyncExecution(old_async_execution);
2349
2350 return;
2351}
2352
2353// Make flags that we can pass into the IOHandler so our delegates can do the
2354// right thing
2355enum {
2356 eHandleCommandFlagStopOnContinue = (1u << 0),
2357 eHandleCommandFlagStopOnError = (1u << 1),
2358 eHandleCommandFlagEchoCommand = (1u << 2),
Stefan Granitzc678ed72018-10-05 16:49:47 +00002359 eHandleCommandFlagEchoCommentCommand = (1u << 3),
2360 eHandleCommandFlagPrintResult = (1u << 4),
2361 eHandleCommandFlagStopOnCrash = (1u << 5)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002362};
2363
2364void CommandInterpreter::HandleCommandsFromFile(
2365 FileSpec &cmd_file, ExecutionContext *context,
2366 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002367 if (!FileSystem::Instance().Exists(cmd_file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002368 result.AppendErrorWithFormat(
2369 "Error reading commands from file %s - file not found.\n",
2370 cmd_file.GetFilename().AsCString("<Unknown>"));
2371 result.SetStatus(eReturnStatusFailed);
2372 return;
2373 }
Jonas Devlieghere166c2622019-02-07 21:51:20 +00002374
2375 StreamFileSP input_file_sp(new StreamFile());
2376 std::string cmd_file_path = cmd_file.GetPath();
2377 Status error = FileSystem::Instance().Open(input_file_sp->GetFile(), cmd_file,
2378 File::eOpenOptionRead);
2379
2380 if (error.Fail()) {
2381 result.AppendErrorWithFormat(
2382 "error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(),
2383 error.AsCString());
2384 result.SetStatus(eReturnStatusFailed);
2385 return;
2386 }
2387
2388 Debugger &debugger = GetDebugger();
2389
2390 uint32_t flags = 0;
2391
2392 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2393 if (m_command_source_flags.empty()) {
2394 // Stop on continue by default
2395 flags |= eHandleCommandFlagStopOnContinue;
2396 } else if (m_command_source_flags.back() &
2397 eHandleCommandFlagStopOnContinue) {
2398 flags |= eHandleCommandFlagStopOnContinue;
2399 }
2400 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2401 flags |= eHandleCommandFlagStopOnContinue;
2402 }
2403
2404 if (options.m_stop_on_error == eLazyBoolCalculate) {
2405 if (m_command_source_flags.empty()) {
2406 if (GetStopCmdSourceOnError())
2407 flags |= eHandleCommandFlagStopOnError;
2408 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) {
2409 flags |= eHandleCommandFlagStopOnError;
2410 }
2411 } else if (options.m_stop_on_error == eLazyBoolYes) {
2412 flags |= eHandleCommandFlagStopOnError;
2413 }
2414
2415 // stop-on-crash can only be set, if it is present in all levels of
2416 // pushed flag sets.
2417 if (options.GetStopOnCrash()) {
2418 if (m_command_source_flags.empty()) {
2419 flags |= eHandleCommandFlagStopOnCrash;
2420 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) {
2421 flags |= eHandleCommandFlagStopOnCrash;
2422 }
2423 }
2424
2425 if (options.m_echo_commands == eLazyBoolCalculate) {
2426 if (m_command_source_flags.empty()) {
2427 // Echo command by default
2428 flags |= eHandleCommandFlagEchoCommand;
2429 } else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) {
2430 flags |= eHandleCommandFlagEchoCommand;
2431 }
2432 } else if (options.m_echo_commands == eLazyBoolYes) {
2433 flags |= eHandleCommandFlagEchoCommand;
2434 }
2435
2436 // We will only ever ask for this flag, if we echo commands in general.
2437 if (options.m_echo_comment_commands == eLazyBoolCalculate) {
2438 if (m_command_source_flags.empty()) {
2439 // Echo comments by default
2440 flags |= eHandleCommandFlagEchoCommentCommand;
2441 } else if (m_command_source_flags.back() &
2442 eHandleCommandFlagEchoCommentCommand) {
2443 flags |= eHandleCommandFlagEchoCommentCommand;
2444 }
2445 } else if (options.m_echo_comment_commands == eLazyBoolYes) {
2446 flags |= eHandleCommandFlagEchoCommentCommand;
2447 }
2448
2449 if (options.m_print_results == eLazyBoolCalculate) {
2450 if (m_command_source_flags.empty()) {
2451 // Print output by default
2452 flags |= eHandleCommandFlagPrintResult;
2453 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) {
2454 flags |= eHandleCommandFlagPrintResult;
2455 }
2456 } else if (options.m_print_results == eLazyBoolYes) {
2457 flags |= eHandleCommandFlagPrintResult;
2458 }
2459
2460 if (flags & eHandleCommandFlagPrintResult) {
2461 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2462 cmd_file_path.c_str());
2463 }
2464
2465 // Used for inheriting the right settings when "command source" might
2466 // have nested "command source" commands
2467 lldb::StreamFileSP empty_stream_sp;
2468 m_command_source_flags.push_back(flags);
2469 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2470 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2471 empty_stream_sp, // Pass in an empty stream so we inherit the top
2472 // input reader output stream
2473 empty_stream_sp, // Pass in an empty stream so we inherit the top
2474 // input reader error stream
2475 flags,
2476 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2477 // or written
2478 debugger.GetPrompt(), llvm::StringRef(),
2479 false, // Not multi-line
2480 debugger.GetUseColor(), 0, *this));
2481 const bool old_async_execution = debugger.GetAsyncExecution();
2482
2483 // Set synchronous execution if we are not stopping on continue
2484 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2485 debugger.SetAsyncExecution(false);
2486
2487 m_command_source_depth++;
2488
2489 debugger.RunIOHandler(io_handler_sp);
2490 if (!m_command_source_flags.empty())
2491 m_command_source_flags.pop_back();
2492 m_command_source_depth--;
2493 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2494 debugger.SetAsyncExecution(old_async_execution);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002495}
2496
2497ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
Jim Ingham30bac792017-07-13 19:45:54 +00002498 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
Greg Clayton79040462016-12-09 01:21:14 +00002499 if (!m_script_interpreter_sp) {
2500 if (!can_create)
2501 return nullptr;
2502 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2503 m_script_interpreter_sp =
2504 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2505 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002506 return m_script_interpreter_sp.get();
2507}
2508
2509bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2510
2511void CommandInterpreter::SetSynchronous(bool value) {
2512 m_synchronous_execution = value;
2513}
2514
2515void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002516 llvm::StringRef prefix,
2517 llvm::StringRef help_text) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002518 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002519
Zachary Turner0ac5f982016-11-08 04:12:42 +00002520 size_t line_width_max = max_columns - prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002521 if (line_width_max < 16)
Zachary Turner0ac5f982016-11-08 04:12:42 +00002522 line_width_max = help_text.size() + prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002523
Zachary Turner0ac5f982016-11-08 04:12:42 +00002524 strm.IndentMore(prefix.size());
2525 bool prefixed_yet = false;
2526 while (!help_text.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002527 // Prefix the first line, indent subsequent lines to line up
Zachary Turner0ac5f982016-11-08 04:12:42 +00002528 if (!prefixed_yet) {
2529 strm << prefix;
2530 prefixed_yet = true;
2531 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002532 strm.Indent();
Zachary Turner0ac5f982016-11-08 04:12:42 +00002533
2534 // Never print more than the maximum on one line.
2535 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2536
2537 // Always break on an explicit newline.
2538 std::size_t first_newline = this_line.find_first_of("\n");
2539
2540 // Don't break on space/tab unless the text is too long to fit on one line.
2541 std::size_t last_space = llvm::StringRef::npos;
2542 if (this_line.size() != help_text.size())
2543 last_space = this_line.find_last_of(" \t");
2544
2545 // Break at whichever condition triggered first.
2546 this_line = this_line.substr(0, std::min(first_newline, last_space));
2547 strm.PutCString(this_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002548 strm.EOL();
2549
Zachary Turner0ac5f982016-11-08 04:12:42 +00002550 // Remove whitespace / newlines after breaking.
2551 help_text = help_text.drop_front(this_line.size()).ltrim();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002552 }
Zachary Turner0ac5f982016-11-08 04:12:42 +00002553 strm.IndentLess(prefix.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002554}
2555
2556void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002557 llvm::StringRef word_text,
2558 llvm::StringRef separator,
2559 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002560 size_t max_word_len) {
2561 StreamString prefix_stream;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002562 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2563 (int)separator.size(), separator.data());
Zachary Turnerc1564272016-11-16 21:15:24 +00002564 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2565}
2566
Zachary Turner0ac5f982016-11-08 04:12:42 +00002567void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2568 llvm::StringRef separator,
2569 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002570 uint32_t max_word_len) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00002571 int indent_size = max_word_len + separator.size() + 2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002572
2573 strm.IndentMore(indent_size);
2574
2575 StreamString text_strm;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002576 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2577 text_strm << separator << " " << help_text;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002578
2579 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2580
Zachary Turnerc1564272016-11-16 21:15:24 +00002581 llvm::StringRef text = text_strm.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002582
2583 uint32_t chars_left = max_columns;
2584
Davide Italianocf8a8292017-04-14 22:36:08 +00002585 auto nextWordLength = [](llvm::StringRef S) {
2586 size_t pos = S.find_first_of(' ');
2587 return pos == llvm::StringRef::npos ? S.size() : pos;
2588 };
2589
Zachary Turnerc1564272016-11-16 21:15:24 +00002590 while (!text.empty()) {
2591 if (text.front() == '\n' ||
Jim Inghama81bd7f2017-07-27 00:18:18 +00002592 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002593 strm.EOL();
2594 strm.Indent();
Zachary Turnerc1564272016-11-16 21:15:24 +00002595 chars_left = max_columns - indent_size;
2596 if (text.front() == '\n')
2597 text = text.drop_front();
2598 else
2599 text = text.ltrim(' ');
Kate Stoneb9c1b512016-09-06 20:57:50 +00002600 } else {
Zachary Turnerc1564272016-11-16 21:15:24 +00002601 strm.PutChar(text.front());
2602 --chars_left;
2603 text = text.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002604 }
2605 }
2606
2607 strm.EOL();
2608 strm.IndentLess(indent_size);
2609}
2610
2611void CommandInterpreter::FindCommandsForApropos(
Zachary Turner067d1db2016-11-16 21:45:04 +00002612 llvm::StringRef search_word, StringList &commands_found,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002613 StringList &commands_help, CommandObject::CommandMap &command_map) {
2614 CommandObject::CommandMap::const_iterator pos;
2615
2616 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
Zachary Turner067d1db2016-11-16 21:45:04 +00002617 llvm::StringRef command_name = pos->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002618 CommandObject *cmd_obj = pos->second.get();
2619
2620 const bool search_short_help = true;
2621 const bool search_long_help = false;
2622 const bool search_syntax = false;
2623 const bool search_options = false;
Zachary Turner067d1db2016-11-16 21:45:04 +00002624 if (command_name.contains_lower(search_word) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002625 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2626 search_long_help, search_syntax,
2627 search_options)) {
2628 commands_found.AppendString(cmd_obj->GetCommandName());
2629 commands_help.AppendString(cmd_obj->GetHelp());
2630 }
2631
2632 if (cmd_obj->IsMultiwordObject()) {
2633 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2634 FindCommandsForApropos(search_word, commands_found, commands_help,
2635 cmd_multiword->GetSubcommandDictionary());
2636 }
2637 }
2638}
2639
Zachary Turner067d1db2016-11-16 21:45:04 +00002640void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002641 StringList &commands_found,
2642 StringList &commands_help,
2643 bool search_builtin_commands,
2644 bool search_user_commands,
2645 bool search_alias_commands) {
2646 CommandObject::CommandMap::const_iterator pos;
2647
2648 if (search_builtin_commands)
2649 FindCommandsForApropos(search_word, commands_found, commands_help,
2650 m_command_dict);
2651
2652 if (search_user_commands)
2653 FindCommandsForApropos(search_word, commands_found, commands_help,
2654 m_user_dict);
2655
2656 if (search_alias_commands)
2657 FindCommandsForApropos(search_word, commands_found, commands_help,
2658 m_alias_dict);
2659}
2660
2661void CommandInterpreter::UpdateExecutionContext(
2662 ExecutionContext *override_context) {
2663 if (override_context != nullptr) {
2664 m_exe_ctx_ref = *override_context;
2665 } else {
2666 const bool adopt_selected = true;
2667 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2668 adopt_selected);
2669 }
2670}
2671
2672size_t CommandInterpreter::GetProcessOutput() {
2673 // The process has stuff waiting for stderr; get it and write it out to the
2674 // appropriate place.
2675 char stdio_buffer[1024];
2676 size_t len;
2677 size_t total_bytes = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002678 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002679 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2680 if (target_sp) {
2681 ProcessSP process_sp(target_sp->GetProcessSP());
2682 if (process_sp) {
2683 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2684 error)) > 0) {
2685 size_t bytes_written = len;
2686 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2687 total_bytes += len;
2688 }
2689 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2690 error)) > 0) {
2691 size_t bytes_written = len;
2692 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2693 total_bytes += len;
2694 }
2695 }
2696 }
2697 return total_bytes;
2698}
2699
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002700void CommandInterpreter::StartHandlingCommand() {
2701 auto idle_state = CommandHandlingState::eIdle;
2702 if (m_command_state.compare_exchange_strong(
2703 idle_state, CommandHandlingState::eInProgress))
2704 lldbassert(m_iohandler_nesting_level == 0);
2705 else
2706 lldbassert(m_iohandler_nesting_level > 0);
2707 ++m_iohandler_nesting_level;
2708}
2709
2710void CommandInterpreter::FinishHandlingCommand() {
2711 lldbassert(m_iohandler_nesting_level > 0);
2712 if (--m_iohandler_nesting_level == 0) {
2713 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2714 lldbassert(prev_state != CommandHandlingState::eIdle);
2715 }
2716}
2717
2718bool CommandInterpreter::InterruptCommand() {
2719 auto in_progress = CommandHandlingState::eInProgress;
2720 return m_command_state.compare_exchange_strong(
2721 in_progress, CommandHandlingState::eInterrupted);
2722}
2723
2724bool CommandInterpreter::WasInterrupted() const {
2725 bool was_interrupted =
2726 (m_command_state == CommandHandlingState::eInterrupted);
2727 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2728 return was_interrupted;
2729}
2730
2731void CommandInterpreter::PrintCommandOutput(Stream &stream,
2732 llvm::StringRef str) {
2733 // Split the output into lines and poll for interrupt requests
2734 const char *data = str.data();
2735 size_t size = str.size();
2736 while (size > 0 && !WasInterrupted()) {
2737 size_t chunk_size = 0;
2738 for (; chunk_size < size; ++chunk_size) {
2739 lldbassert(data[chunk_size] != '\0');
2740 if (data[chunk_size] == '\n') {
2741 ++chunk_size;
2742 break;
2743 }
2744 }
2745 chunk_size = stream.Write(data, chunk_size);
2746 lldbassert(size >= chunk_size);
2747 data += chunk_size;
2748 size -= chunk_size;
2749 }
2750 if (size > 0) {
2751 stream.Printf("\n... Interrupted.\n");
2752 }
2753}
2754
Stefan Granitzc678ed72018-10-05 16:49:47 +00002755bool CommandInterpreter::EchoCommandNonInteractive(
2756 llvm::StringRef line, const Flags &io_handler_flags) const {
2757 if (!io_handler_flags.Test(eHandleCommandFlagEchoCommand))
2758 return false;
2759
2760 llvm::StringRef command = line.trim();
2761 if (command.empty())
2762 return true;
2763
2764 if (command.front() == m_comment_char)
2765 return io_handler_flags.Test(eHandleCommandFlagEchoCommentCommand);
2766
2767 return true;
2768}
2769
Kate Stoneb9c1b512016-09-06 20:57:50 +00002770void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2771 std::string &line) {
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002772 // If we were interrupted, bail out...
2773 if (WasInterrupted())
2774 return;
2775
Kate Stoneb9c1b512016-09-06 20:57:50 +00002776 const bool is_interactive = io_handler.GetIsInteractive();
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002777 if (!is_interactive) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002778 // When we are not interactive, don't execute blank lines. This will happen
2779 // sourcing a commands file. We don't want blank lines to repeat the
Adrian Prantl05097242018-04-30 16:49:04 +00002780 // previous command and cause any errors to occur (like redefining an
2781 // alias, get an error and stop parsing the commands file).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002782 if (line.empty())
2783 return;
2784
2785 // When using a non-interactive file handle (like when sourcing commands
Adrian Prantl05097242018-04-30 16:49:04 +00002786 // from a file) we need to echo the command out so we don't just see the
2787 // command output and no command...
Stefan Granitzc678ed72018-10-05 16:49:47 +00002788 if (EchoCommandNonInteractive(line, io_handler.GetFlags()))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002789 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2790 line.c_str());
2791 }
2792
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002793 StartHandlingCommand();
2794
Kate Stoneb9c1b512016-09-06 20:57:50 +00002795 lldb_private::CommandReturnObject result;
2796 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2797
2798 // Now emit the command output text from the command we just executed
2799 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2800 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2801 GetProcessOutput();
2802
2803 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002804 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002805 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002806 }
2807
2808 // Now emit the command error text from the command we just executed
2809 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002810 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002811 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002812 }
2813 }
2814
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002815 FinishHandlingCommand();
2816
Kate Stoneb9c1b512016-09-06 20:57:50 +00002817 switch (result.GetStatus()) {
2818 case eReturnStatusInvalid:
2819 case eReturnStatusSuccessFinishNoResult:
2820 case eReturnStatusSuccessFinishResult:
2821 case eReturnStatusStarted:
2822 break;
2823
2824 case eReturnStatusSuccessContinuingNoResult:
2825 case eReturnStatusSuccessContinuingResult:
2826 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2827 io_handler.SetIsDone(true);
2828 break;
2829
2830 case eReturnStatusFailed:
2831 m_num_errors++;
2832 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2833 io_handler.SetIsDone(true);
2834 break;
2835
2836 case eReturnStatusQuit:
2837 m_quit_requested = true;
2838 io_handler.SetIsDone(true);
2839 break;
2840 }
2841
2842 // Finally, if we're going to stop on crash, check that here:
2843 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2844 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2845 bool should_stop = false;
2846 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2847 if (target_sp) {
2848 ProcessSP process_sp(target_sp->GetProcessSP());
2849 if (process_sp) {
2850 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2851 StopReason reason = thread_sp->GetStopReason();
2852 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2853 reason == eStopReasonInstrumentation) &&
2854 !result.GetAbnormalStopWasExpected()) {
2855 should_stop = true;
2856 break;
2857 }
2858 }
2859 }
2860 }
2861 if (should_stop) {
2862 io_handler.SetIsDone(true);
2863 m_stopped_for_crash = true;
2864 }
2865 }
2866}
2867
2868bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2869 ExecutionContext exe_ctx(GetExecutionContext());
2870 Process *process = exe_ctx.GetProcessPtr();
2871
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002872 if (InterruptCommand())
2873 return true;
2874
Kate Stoneb9c1b512016-09-06 20:57:50 +00002875 if (process) {
2876 StateType state = process->GetState();
2877 if (StateIsRunningState(state)) {
2878 process->Halt();
2879 return true; // Don't do any updating when we are running
2880 }
2881 }
2882
2883 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2884 if (script_interpreter) {
2885 if (script_interpreter->Interrupt())
2886 return true;
2887 }
2888 return false;
2889}
2890
2891void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2892 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2893 void *baton) {
2894 Debugger &debugger = GetDebugger();
2895 IOHandlerSP io_handler_sp(
2896 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2897 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002898 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2899 llvm::StringRef(), // Continuation prompt
2900 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002901 debugger.GetUseColor(),
2902 0, // Don't show line numbers
2903 delegate)); // IOHandlerDelegate
2904
2905 if (io_handler_sp) {
2906 io_handler_sp->SetUserData(baton);
2907 if (asynchronously)
2908 debugger.PushIOHandler(io_handler_sp);
2909 else
2910 debugger.RunIOHandler(io_handler_sp);
2911 }
2912}
2913
2914void CommandInterpreter::GetPythonCommandsFromIOHandler(
2915 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2916 void *baton) {
2917 Debugger &debugger = GetDebugger();
2918 IOHandlerSP io_handler_sp(
2919 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2920 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002921 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2922 llvm::StringRef(), // Continuation prompt
2923 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002924 debugger.GetUseColor(),
2925 0, // Don't show line numbers
2926 delegate)); // IOHandlerDelegate
2927
2928 if (io_handler_sp) {
2929 io_handler_sp->SetUserData(baton);
2930 if (asynchronously)
2931 debugger.PushIOHandler(io_handler_sp);
2932 else
2933 debugger.RunIOHandler(io_handler_sp);
2934 }
2935}
2936
2937bool CommandInterpreter::IsActive() {
2938 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2939}
2940
2941lldb::IOHandlerSP
2942CommandInterpreter::GetIOHandler(bool force_create,
2943 CommandInterpreterRunOptions *options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002944 // Always re-create the IOHandlerEditline in case the input changed. The old
2945 // instance might have had a non-interactive input and now it does or vice
2946 // versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002947 if (force_create || !m_command_io_handler_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002948 // Always re-create the IOHandlerEditline in case the input changed. The
2949 // old instance might have had a non-interactive input and now it does or
2950 // vice versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002951 uint32_t flags = 0;
2952
2953 if (options) {
2954 if (options->m_stop_on_continue == eLazyBoolYes)
2955 flags |= eHandleCommandFlagStopOnContinue;
2956 if (options->m_stop_on_error == eLazyBoolYes)
2957 flags |= eHandleCommandFlagStopOnError;
2958 if (options->m_stop_on_crash == eLazyBoolYes)
2959 flags |= eHandleCommandFlagStopOnCrash;
2960 if (options->m_echo_commands != eLazyBoolNo)
2961 flags |= eHandleCommandFlagEchoCommand;
Stefan Granitzc678ed72018-10-05 16:49:47 +00002962 if (options->m_echo_comment_commands != eLazyBoolNo)
2963 flags |= eHandleCommandFlagEchoCommentCommand;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002964 if (options->m_print_results != eLazyBoolNo)
2965 flags |= eHandleCommandFlagPrintResult;
2966 } else {
2967 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2968 }
2969
2970 m_command_io_handler_sp.reset(new IOHandlerEditline(
2971 m_debugger, IOHandler::Type::CommandInterpreter,
2972 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2973 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002974 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002975 false, // Don't enable multiple line input, just single line commands
2976 m_debugger.GetUseColor(),
2977 0, // Don't show line numbers
2978 *this));
2979 }
2980 return m_command_io_handler_sp;
2981}
2982
2983void CommandInterpreter::RunCommandInterpreter(
2984 bool auto_handle_events, bool spawn_thread,
2985 CommandInterpreterRunOptions &options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002986 // Always re-create the command interpreter when we run it in case any file
2987 // handles have changed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002988 bool force_create = true;
2989 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2990 m_stopped_for_crash = false;
2991
2992 if (auto_handle_events)
2993 m_debugger.StartEventHandlerThread();
2994
2995 if (spawn_thread) {
2996 m_debugger.StartIOHandlerThread();
2997 } else {
2998 m_debugger.ExecuteIOHandlers();
2999
3000 if (auto_handle_events)
3001 m_debugger.StopEventHandlerThread();
3002 }
3003}
3004
3005CommandObject *
3006CommandInterpreter::ResolveCommandImpl(std::string &command_line,
3007 CommandReturnObject &result) {
3008 std::string scratch_command(command_line); // working copy so we don't modify
3009 // command_line unless we succeed
3010 CommandObject *cmd_obj = nullptr;
3011 StreamString revised_command_line;
3012 bool wants_raw_input = false;
3013 size_t actual_cmd_name_len = 0;
3014 std::string next_word;
3015 StringList matches;
3016 bool done = false;
3017 while (!done) {
3018 char quote_char = '\0';
3019 std::string suffix;
3020 ExtractCommand(scratch_command, next_word, suffix, quote_char);
3021 if (cmd_obj == nullptr) {
3022 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003023 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00003024 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003025 bool is_real_command =
Jonas Devliegherea6682a42018-12-15 00:15:33 +00003026 (!is_alias) || (cmd_obj != nullptr && !cmd_obj->IsAlias());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003027 if (!is_real_command) {
3028 matches.Clear();
3029 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003030 cmd_obj =
3031 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003032 revised_command_line.Printf("%s", alias_result.c_str());
3033 if (cmd_obj) {
3034 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00003035 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003036 }
3037 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003038 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00003039 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
3040 actual_cmd_name_len += cmd_name.size();
3041 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003042 wants_raw_input = cmd_obj->WantsRawCommandString();
3043 } else {
3044 revised_command_line.Printf("%s", next_word.c_str());
3045 }
3046 }
3047 } else {
3048 if (cmd_obj->IsMultiwordObject()) {
3049 CommandObject *sub_cmd_obj =
3050 cmd_obj->GetSubcommandObject(next_word.c_str());
3051 if (sub_cmd_obj) {
Adrian Prantl05097242018-04-30 16:49:04 +00003052 // The subcommand's name includes the parent command's name, so
3053 // restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00003054 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3055 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003056 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00003057 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003058 cmd_obj = sub_cmd_obj;
3059 wants_raw_input = cmd_obj->WantsRawCommandString();
3060 } else {
3061 if (quote_char)
3062 revised_command_line.Printf(" %c%s%s%c", quote_char,
3063 next_word.c_str(), suffix.c_str(),
3064 quote_char);
3065 else
3066 revised_command_line.Printf(" %s%s", next_word.c_str(),
3067 suffix.c_str());
3068 done = true;
3069 }
3070 } else {
3071 if (quote_char)
3072 revised_command_line.Printf(" %c%s%s%c", quote_char,
3073 next_word.c_str(), suffix.c_str(),
3074 quote_char);
3075 else
3076 revised_command_line.Printf(" %s%s", next_word.c_str(),
3077 suffix.c_str());
3078 done = true;
3079 }
3080 }
3081
3082 if (cmd_obj == nullptr) {
3083 const size_t num_matches = matches.GetSize();
3084 if (matches.GetSize() > 1) {
3085 StreamString error_msg;
3086 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3087 next_word.c_str());
3088
3089 for (uint32_t i = 0; i < num_matches; ++i) {
3090 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3091 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003092 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003093 } else {
3094 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003095 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003096 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3097 next_word.c_str());
3098 }
3099 result.SetStatus(eReturnStatusFailed);
3100 return nullptr;
3101 }
3102
3103 if (cmd_obj->IsMultiwordObject()) {
3104 if (!suffix.empty()) {
3105 result.AppendErrorWithFormat(
3106 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3107 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003108 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003109 next_word.empty() ? "" : next_word.c_str(),
3110 next_word.empty() ? " -- " : " ", suffix.c_str());
3111 result.SetStatus(eReturnStatusFailed);
3112 return nullptr;
3113 }
3114 } else {
3115 // If we found a normal command, we are done
3116 done = true;
3117 if (!suffix.empty()) {
3118 switch (suffix[0]) {
3119 case '/':
3120 // GDB format suffixes
3121 {
3122 Options *command_options = cmd_obj->GetOptions();
3123 if (command_options &&
3124 command_options->SupportsLongOption("gdb-format")) {
3125 std::string gdb_format_option("--gdb-format=");
3126 gdb_format_option += (suffix.c_str() + 1);
3127
Zachary Turnerc1564272016-11-16 21:15:24 +00003128 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003129 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3130 if (arg_terminator_idx != std::string::npos) {
3131 // Insert the gdb format option before the "--" that terminates
3132 // options
3133 gdb_format_option.append(1, ' ');
3134 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003135 revised_command_line.Clear();
3136 revised_command_line.PutCString(cmd);
3137 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003138 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3139
3140 if (wants_raw_input &&
3141 FindArgumentTerminator(cmd) == std::string::npos)
3142 revised_command_line.PutCString(" --");
3143 } else {
3144 result.AppendErrorWithFormat(
3145 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003146 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003147 result.SetStatus(eReturnStatusFailed);
3148 return nullptr;
3149 }
3150 }
3151 break;
3152
3153 default:
3154 result.AppendErrorWithFormat(
3155 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3156 result.SetStatus(eReturnStatusFailed);
3157 return nullptr;
3158 }
3159 }
3160 }
3161 if (scratch_command.empty())
3162 done = true;
3163 }
3164
3165 if (!scratch_command.empty())
3166 revised_command_line.Printf(" %s", scratch_command.c_str());
3167
3168 if (cmd_obj != NULL)
Zachary Turnerc1564272016-11-16 21:15:24 +00003169 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003170
3171 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003172}