blob: 47f5125804fd6e2918c99ccd2eb9d2da106ba31c [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Kate Stoneb9c1b512016-09-06 20:57:50 +000010#include <stdlib.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000011#include <string>
Caroline Tice4ab31c92010-10-12 21:57:09 +000012#include <vector>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013
Greg Clayton4a33d312011-06-23 17:59:56 +000014#include "CommandObjectScript.h"
Peter Collingbourne08405b62011-06-23 20:37:26 +000015#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000016
James Y Knight2ad48212018-05-22 22:53:50 +000017#include "Commands/CommandObjectApropos.h"
18#include "Commands/CommandObjectBreakpoint.h"
19#include "Commands/CommandObjectBugreport.h"
20#include "Commands/CommandObjectCommands.h"
21#include "Commands/CommandObjectDisassemble.h"
22#include "Commands/CommandObjectExpression.h"
23#include "Commands/CommandObjectFrame.h"
24#include "Commands/CommandObjectGUI.h"
25#include "Commands/CommandObjectHelp.h"
26#include "Commands/CommandObjectLanguage.h"
27#include "Commands/CommandObjectLog.h"
28#include "Commands/CommandObjectMemory.h"
29#include "Commands/CommandObjectPlatform.h"
30#include "Commands/CommandObjectPlugin.h"
31#include "Commands/CommandObjectProcess.h"
32#include "Commands/CommandObjectQuit.h"
33#include "Commands/CommandObjectRegister.h"
34#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));
486 m_command_dict["script"] =
487 CommandObjectSP(new CommandObjectScript(*this, script_language));
488 m_command_dict["settings"] =
489 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
490 m_command_dict["source"] =
491 CommandObjectSP(new CommandObjectMultiwordSource(*this));
Davide Italiano24fff242018-04-13 18:02:39 +0000492 m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493 m_command_dict["target"] =
494 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
495 m_command_dict["thread"] =
496 CommandObjectSP(new CommandObjectMultiwordThread(*this));
497 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
498 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
499 m_command_dict["watchpoint"] =
500 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
501 m_command_dict["language"] =
502 CommandObjectSP(new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000503
Kate Stoneb9c1b512016-09-06 20:57:50 +0000504 const char *break_regexes[][2] = {
505 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
506 "breakpoint set --file '%1' --line %2"},
507 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
508 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
509 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
510 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
511 "breakpoint set --name '%1'"},
512 {"^(-.*)$", "breakpoint set %1"},
513 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
514 "breakpoint set --name '%2' --shlib '%1'"},
515 {"^\\&(.*[^[:space:]])[[:space:]]*$",
516 "breakpoint set --name '%1' --skip-prologue=0"},
517 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
518 "breakpoint set --name '%1'"}};
Kate Stone7428a182016-07-14 22:03:10 +0000519
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000521
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap(
523 new CommandObjectRegexCommand(
524 *this, "_regexp-break",
Raphael Isemann129fe892018-07-30 21:41:13 +0000525 "Set a breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000526 "\n"
527 "_regexp-break <filename>:<linenum>\n"
528 " main.c:12 // Break at line 12 of "
529 "main.c\n\n"
530 "_regexp-break <linenum>\n"
531 " 12 // Break at line 12 of current "
532 "file\n\n"
533 "_regexp-break 0x<address>\n"
534 " 0x1234000 // Break at address "
535 "0x1234000\n\n"
536 "_regexp-break <name>\n"
537 " main // Break in 'main' after the "
538 "prologue\n\n"
539 "_regexp-break &<name>\n"
540 " &main // Break at first instruction "
541 "in 'main'\n\n"
542 "_regexp-break <module>`<name>\n"
543 " libc.so`malloc // Break in 'malloc' from "
544 "'libc.so'\n\n"
545 "_regexp-break /<source-regex>/\n"
546 " /break here/ // Break on source lines in "
547 "current file\n"
548 " // containing text 'break "
549 "here'.\n",
550 2, CommandCompletions::eSymbolCompletion |
551 CommandCompletions::eSourceFileCompletion,
552 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000553
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 if (break_regex_cmd_ap.get()) {
555 bool success = true;
556 for (size_t i = 0; i < num_regexes; i++) {
557 success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0],
558 break_regexes[i][1]);
559 if (!success)
560 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000561 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 success =
563 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Jim Inghamffba2292011-03-22 02:29:32 +0000564
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565 if (success) {
566 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
567 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
Jim Inghamca36cd12012-10-05 19:16:31 +0000568 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569 }
Jim Inghamca36cd12012-10-05 19:16:31 +0000570
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap(
572 new CommandObjectRegexCommand(
573 *this, "_regexp-tbreak",
Raphael Isemann129fe892018-07-30 21:41:13 +0000574 "Set a one-shot breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000575 "\n"
576 "_regexp-break <filename>:<linenum>\n"
577 " main.c:12 // Break at line 12 of "
578 "main.c\n\n"
579 "_regexp-break <linenum>\n"
580 " 12 // Break at line 12 of current "
581 "file\n\n"
582 "_regexp-break 0x<address>\n"
583 " 0x1234000 // Break at address "
584 "0x1234000\n\n"
585 "_regexp-break <name>\n"
586 " main // Break in 'main' after the "
587 "prologue\n\n"
588 "_regexp-break &<name>\n"
589 " &main // Break at first instruction "
590 "in 'main'\n\n"
591 "_regexp-break <module>`<name>\n"
592 " libc.so`malloc // Break in 'malloc' from "
593 "'libc.so'\n\n"
594 "_regexp-break /<source-regex>/\n"
595 " /break here/ // Break on source lines in "
596 "current file\n"
597 " // containing text 'break "
598 "here'.\n",
599 2, CommandCompletions::eSymbolCompletion |
600 CommandCompletions::eSourceFileCompletion,
601 false));
602
603 if (tbreak_regex_cmd_ap.get()) {
604 bool success = true;
605 for (size_t i = 0; i < num_regexes; i++) {
606 // If you add a resultant command string longer than 1024 characters be
607 // sure to increase the size of this buffer.
608 char buffer[1024];
609 int num_printed =
Frederic Riss49c9d8b2018-06-18 04:34:33 +0000610 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1");
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000611 lldbassert(num_printed < 1024);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000612 UNUSED_IF_ASSERT_DISABLED(num_printed);
613 success =
614 tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer);
615 if (!success)
616 break;
Johnny Chen6d675242012-08-24 18:15:45 +0000617 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000618 success =
619 tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Kate Stone7428a182016-07-14 22:03:10 +0000620
Kate Stoneb9c1b512016-09-06 20:57:50 +0000621 if (success) {
622 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
623 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
624 tbreak_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000625 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000626 }
Kate Stone7428a182016-07-14 22:03:10 +0000627
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap(
629 new CommandObjectRegexCommand(
630 *this, "_regexp-attach", "Attach to process by ID or name.",
631 "_regexp-attach <pid> | <process-name>", 2, 0, false));
632 if (attach_regex_cmd_ap.get()) {
633 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
634 "process attach --pid %1") &&
635 attach_regex_cmd_ap->AddRegexCommand(
636 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
637 // specified get passed to
638 // 'process attach'
639 attach_regex_cmd_ap->AddRegexCommand("^(.+)$",
640 "process attach --name '%1'") &&
641 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) {
642 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
643 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
644 attach_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000645 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000647
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap(
649 new CommandObjectRegexCommand(*this, "_regexp-down",
650 "Select a newer stack frame. Defaults to "
651 "moving one frame, a numeric argument can "
652 "specify an arbitrary number.",
653 "_regexp-down [<count>]", 2, 0, false));
654 if (down_regex_cmd_ap.get()) {
655 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
656 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
657 "frame select -r -%1")) {
658 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
659 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000660 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000662
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap(
664 new CommandObjectRegexCommand(
665 *this, "_regexp-up",
666 "Select an older stack frame. Defaults to moving one "
667 "frame, a numeric argument can specify an arbitrary number.",
668 "_regexp-up [<count>]", 2, 0, false));
669 if (up_regex_cmd_ap.get()) {
670 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
671 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
672 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
673 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000674 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000675 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000676
Kate Stoneb9c1b512016-09-06 20:57:50 +0000677 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap(
678 new CommandObjectRegexCommand(
679 *this, "_regexp-display",
680 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
681 "_regexp-display expression", 2, 0, false));
682 if (display_regex_cmd_ap.get()) {
683 if (display_regex_cmd_ap->AddRegexCommand(
684 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
685 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
686 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
687 display_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000688 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000689 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000690
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap(
692 new CommandObjectRegexCommand(
693 *this, "_regexp-undisplay", "Stop displaying expression at every "
694 "stop (specified by stop-hook index.)",
695 "_regexp-undisplay stop-hook-number", 2, 0, false));
696 if (undisplay_regex_cmd_ap.get()) {
697 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
698 "target stop-hook delete %1")) {
699 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
700 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
701 undisplay_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000702 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000703 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000704
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap(
706 new CommandObjectRegexCommand(
707 *this, "gdb-remote", "Connect to a process via remote GDB server. "
708 "If no host is specifed, localhost is assumed.",
709 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
710 if (connect_gdb_remote_cmd_ap.get()) {
711 if (connect_gdb_remote_cmd_ap->AddRegexCommand(
Chris Bieneman51978f52017-04-27 16:13:58 +0000712 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
713 "process connect --plugin gdb-remote connect://%1:%2") &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000714 connect_gdb_remote_cmd_ap->AddRegexCommand(
715 "^([[:digit:]]+)$",
716 "process connect --plugin gdb-remote connect://localhost:%1")) {
717 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
718 m_command_dict[command_sp->GetCommandName()] = command_sp;
Jason Molenda4cddfed2012-10-05 05:29:32 +0000719 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000720 }
Jason Molenda4cddfed2012-10-05 05:29:32 +0000721
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap(
723 new CommandObjectRegexCommand(
724 *this, "kdp-remote", "Connect to a process via remote KDP server. "
725 "If no UDP port is specified, port 41139 is "
726 "assumed.",
727 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
728 if (connect_kdp_remote_cmd_ap.get()) {
729 if (connect_kdp_remote_cmd_ap->AddRegexCommand(
730 "^([^:]+:[[:digit:]]+)$",
731 "process connect --plugin kdp-remote udp://%1") &&
732 connect_kdp_remote_cmd_ap->AddRegexCommand(
733 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
734 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
735 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Clayton6bade322013-02-01 23:33:03 +0000736 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000737 }
Greg Clayton6bade322013-02-01 23:33:03 +0000738
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap(
740 new CommandObjectRegexCommand(
741 *this, "_regexp-bt",
742 "Show the current thread's call stack. Any numeric argument "
743 "displays at most that many "
744 "frames. The argument 'all' displays all threads.",
745 "bt [<digit> | all]", 2, 0, false));
746 if (bt_regex_cmd_ap.get()) {
747 // accept but don't document "bt -c <number>" -- before bt was a regex
Adrian Prantl05097242018-04-30 16:49:04 +0000748 // command if you wanted to backtrace three frames you would do "bt -c 3"
749 // but the intention is to have this emulate the gdb "bt" command and so
750 // now "bt 3" is the preferred form, in line with gdb.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000751 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$",
752 "thread backtrace -c %1") &&
753 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$",
754 "thread backtrace -c %1") &&
755 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
756 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) {
757 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
758 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Claytonef5651d2013-02-12 18:52:24 +0000759 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760 }
Greg Claytonef5651d2013-02-12 18:52:24 +0000761
Kate Stoneb9c1b512016-09-06 20:57:50 +0000762 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap(
763 new CommandObjectRegexCommand(
764 *this, "_regexp-list",
765 "List relevant source code using one of several shorthand formats.",
766 "\n"
767 "_regexp-list <file>:<line> // List around specific file/line\n"
768 "_regexp-list <line> // List current file around specified "
769 "line\n"
770 "_regexp-list <function-name> // List specified function\n"
771 "_regexp-list 0x<address> // List around specified address\n"
772 "_regexp-list -[<count>] // List previous <count> lines\n"
773 "_regexp-list // List subsequent lines",
774 2, CommandCompletions::eSourceFileCompletion, false));
775 if (list_regex_cmd_ap.get()) {
776 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
777 "source list --line %1") &&
778 list_regex_cmd_ap->AddRegexCommand(
779 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
780 "]*$",
781 "source list --file '%1' --line %2") &&
782 list_regex_cmd_ap->AddRegexCommand(
783 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
784 "source list --address %1") &&
785 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$",
786 "source list --reverse") &&
787 list_regex_cmd_ap->AddRegexCommand(
788 "^-([[:digit:]]+)[[:space:]]*$",
789 "source list --reverse --count %1") &&
790 list_regex_cmd_ap->AddRegexCommand("^(.+)$",
791 "source list --name \"%1\"") &&
792 list_regex_cmd_ap->AddRegexCommand("^$", "source list")) {
793 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
794 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
Richard Mittonf86248d2013-09-12 02:20:34 +0000795 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000796 }
Richard Mittonf86248d2013-09-12 02:20:34 +0000797
Kate Stoneb9c1b512016-09-06 20:57:50 +0000798 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap(
799 new CommandObjectRegexCommand(
800 *this, "_regexp-env",
801 "Shorthand for viewing and setting environment variables.",
802 "\n"
803 "_regexp-env // Show enrivonment\n"
804 "_regexp-env <name>=<value> // Set an environment variable",
805 2, 0, false));
806 if (env_regex_cmd_ap.get()) {
807 if (env_regex_cmd_ap->AddRegexCommand("^$",
808 "settings show target.env-vars") &&
809 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
810 "settings set target.env-vars %1")) {
811 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
812 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
813 }
814 }
815
816 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap(
817 new CommandObjectRegexCommand(
818 *this, "_regexp-jump", "Set the program counter to a new address.",
819 "\n"
820 "_regexp-jump <line>\n"
821 "_regexp-jump +<line-offset> | -<line-offset>\n"
822 "_regexp-jump <file>:<line>\n"
823 "_regexp-jump *<addr>\n",
824 2, 0, false));
825 if (jump_regex_cmd_ap.get()) {
826 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$",
827 "thread jump --addr %1") &&
828 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
829 "thread jump --line %1") &&
830 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$",
831 "thread jump --file %1 --line %2") &&
832 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$",
833 "thread jump --by %1")) {
834 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
835 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
836 }
837 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000838}
839
Kate Stoneb9c1b512016-09-06 20:57:50 +0000840int CommandInterpreter::GetCommandNamesMatchingPartialString(
Raphael Isemann7f888292018-09-13 21:26:00 +0000841 const char *cmd_str, bool include_aliases, StringList &matches,
842 StringList &descriptions) {
843 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches,
844 &descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000845
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 if (include_aliases) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000847 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches,
848 &descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000849 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000850
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 return matches.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000852}
853
Raphael Isemann7f888292018-09-13 21:26:00 +0000854CommandObjectSP
855CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases,
856 bool exact, StringList *matches,
857 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000858 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000859
Zachary Turnera4496982016-10-05 21:14:38 +0000860 std::string cmd = cmd_str;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000861
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862 if (HasCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000863 auto pos = m_command_dict.find(cmd);
Greg Claytonb5472782015-01-09 19:08:20 +0000864 if (pos != m_command_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865 command_sp = pos->second;
866 }
867
868 if (include_aliases && HasAliases()) {
869 auto alias_pos = m_alias_dict.find(cmd);
870 if (alias_pos != m_alias_dict.end())
871 command_sp = alias_pos->second;
872 }
873
874 if (HasUserCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000875 auto pos = m_user_dict.find(cmd);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000876 if (pos != m_user_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877 command_sp = pos->second;
878 }
879
880 if (!exact && !command_sp) {
881 // We will only get into here if we didn't find any exact matches.
882
883 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
884
885 StringList local_matches;
886 if (matches == nullptr)
887 matches = &local_matches;
888
889 unsigned int num_cmd_matches = 0;
890 unsigned int num_alias_matches = 0;
891 unsigned int num_user_matches = 0;
892
893 // Look through the command dictionaries one by one, and if we get only one
Adrian Prantl05097242018-04-30 16:49:04 +0000894 // match from any of them in toto, then return that, otherwise return an
895 // empty CommandObjectSP and the list of matches.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896
897 if (HasCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000898 num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str,
899 *matches, descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000900 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901
902 if (num_cmd_matches == 1) {
903 cmd.assign(matches->GetStringAtIndex(0));
Zachary Turnera4496982016-10-05 21:14:38 +0000904 auto pos = m_command_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000905 if (pos != m_command_dict.end())
906 real_match_sp = pos->second;
907 }
908
909 if (include_aliases && HasAliases()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000910 num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str,
911 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912 }
913
914 if (num_alias_matches == 1) {
915 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
916 auto alias_pos = m_alias_dict.find(cmd);
917 if (alias_pos != m_alias_dict.end())
918 alias_match_sp = alias_pos->second;
919 }
920
921 if (HasUserCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000922 num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str,
923 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 }
925
926 if (num_user_matches == 1) {
927 cmd.assign(
928 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
929
Zachary Turnera4496982016-10-05 21:14:38 +0000930 auto pos = m_user_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000931 if (pos != m_user_dict.end())
932 user_match_sp = pos->second;
933 }
934
935 // If we got exactly one match, return that, otherwise return the match
936 // list.
937
938 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
939 if (num_cmd_matches)
940 return real_match_sp;
941 else if (num_alias_matches)
942 return alias_match_sp;
943 else
944 return user_match_sp;
945 }
946 } else if (matches && command_sp) {
Zachary Turnera4496982016-10-05 21:14:38 +0000947 matches->AppendString(cmd_str);
Raphael Isemann7f888292018-09-13 21:26:00 +0000948 if (descriptions)
949 descriptions->AppendString(command_sp->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000950 }
951
952 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000953}
954
Zachary Turnera4496982016-10-05 21:14:38 +0000955bool CommandInterpreter::AddCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000956 const lldb::CommandObjectSP &cmd_sp,
957 bool can_replace) {
958 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000959 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
960 "tried to add a CommandObject from a different interpreter");
Kate Stonea487aa42015-01-15 00:52:41 +0000961
Zachary Turnera4496982016-10-05 21:14:38 +0000962 if (name.empty())
963 return false;
964
965 std::string name_sstr(name);
966 auto name_iter = m_command_dict.find(name_sstr);
967 if (name_iter != m_command_dict.end()) {
968 if (!can_replace || !name_iter->second->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 return false;
Zachary Turnera4496982016-10-05 21:14:38 +0000970 name_iter->second = cmd_sp;
971 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000972 m_command_dict[name_sstr] = cmd_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000973 }
Zachary Turnera4496982016-10-05 21:14:38 +0000974 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000975}
976
Zachary Turnera483f572016-10-05 21:14:49 +0000977bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978 const lldb::CommandObjectSP &cmd_sp,
979 bool can_replace) {
980 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000981 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
982 "tried to add a CommandObject from a different interpreter");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000983
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 if (!name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000985 // do not allow replacement of internal commands
Zachary Turnera483f572016-10-05 21:14:49 +0000986 if (CommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000987 if (can_replace == false)
988 return false;
989 if (m_command_dict[name]->IsRemovable() == false)
Greg Clayton5a314712011-10-14 07:41:33 +0000990 return false;
991 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000992
Zachary Turnera483f572016-10-05 21:14:49 +0000993 if (UserCommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000994 if (can_replace == false)
995 return false;
996 if (m_user_dict[name]->IsRemovable() == false)
997 return false;
Caroline Tice844d2302010-12-09 22:52:49 +0000998 }
999
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 m_user_dict[name] = cmd_sp;
1001 return true;
1002 }
1003 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001004}
1005
Zachary Turnera4496982016-10-05 21:14:38 +00001006CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
1007 bool include_aliases) const {
1008 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009 // it's a multi-word command.
1010 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001011
Zachary Turnera4496982016-10-05 21:14:38 +00001012 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001013 return ret_val;
1014
1015 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +00001016 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001017 else {
1018 // We have a multi-word command (seemingly), so we need to do more work.
1019 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +00001020 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001021 include_aliases, true, nullptr);
1022 if (cmd_obj_sp.get() != nullptr) {
Adrian Prantl05097242018-04-30 16:49:04 +00001023 // Loop through the rest of the words in the command (everything passed
1024 // in was supposed to be part of a command name), and find the
1025 // appropriate sub-command SP for each command word....
Kate Stoneb9c1b512016-09-06 20:57:50 +00001026 size_t end = cmd_words.GetArgumentCount();
1027 for (size_t j = 1; j < end; ++j) {
1028 if (cmd_obj_sp->IsMultiwordObject()) {
1029 cmd_obj_sp =
1030 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
1031 if (cmd_obj_sp.get() == nullptr)
1032 // The sub-command name was invalid. Fail and return the empty
1033 // 'ret_val'.
1034 return ret_val;
1035 } else
1036 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +00001037 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001038 return ret_val;
1039 }
1040 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +00001041 // command objects for them. Assign the last object retrieved to
1042 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001043 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001044 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 }
1046 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047}
1048
Raphael Isemann7f888292018-09-13 21:26:00 +00001049CommandObject *
1050CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
1051 StringList *matches,
1052 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001053 CommandObject *command_obj =
Raphael Isemann7f888292018-09-13 21:26:00 +00001054 GetCommandSP(cmd_str, false, true, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001055
Kate Stoneb9c1b512016-09-06 20:57:50 +00001056 // If we didn't find an exact match to the command string in the commands,
Adrian Prantl05097242018-04-30 16:49:04 +00001057 // look in the aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001058
1059 if (command_obj)
1060 return command_obj;
1061
Raphael Isemann7f888292018-09-13 21:26:00 +00001062 command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063
1064 if (command_obj)
1065 return command_obj;
1066
1067 // If there wasn't an exact match then look for an inexact one in just the
1068 // commands
Zachary Turnera4496982016-10-05 21:14:38 +00001069 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001070
1071 // Finally, if there wasn't an inexact match among the commands, look for an
Adrian Prantl05097242018-04-30 16:49:04 +00001072 // inexact match in both the commands and aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073
1074 if (command_obj) {
1075 if (matches)
1076 matches->AppendString(command_obj->GetCommandName());
Raphael Isemann7f888292018-09-13 21:26:00 +00001077 if (descriptions)
1078 descriptions->AppendString(command_obj->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001079 return command_obj;
1080 }
1081
Raphael Isemann7f888292018-09-13 21:26:00 +00001082 return GetCommandSP(cmd_str, true, false, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001083}
1084
Zachary Turnera483f572016-10-05 21:14:49 +00001085bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001086 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001087}
1088
Zachary Turnera483f572016-10-05 21:14:49 +00001089bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1090 std::string &full_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001091 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1092 if (exact_match) {
1093 full_name.assign(cmd);
1094 return exact_match;
1095 } else {
1096 StringList matches;
1097 size_t num_alias_matches;
1098 num_alias_matches =
1099 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1100 if (num_alias_matches == 1) {
1101 // Make sure this isn't shadowing a command in the regular command space:
1102 StringList regular_matches;
1103 const bool include_aliases = false;
1104 const bool exact = false;
1105 CommandObjectSP cmd_obj_sp(
1106 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1107 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1108 return false;
1109 else {
1110 full_name.assign(matches.GetStringAtIndex(0));
1111 return true;
1112 }
1113 } else
1114 return false;
1115 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116}
1117
Zachary Turnera483f572016-10-05 21:14:49 +00001118bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001119 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001120}
1121
Zachary Turnera483f572016-10-05 21:14:49 +00001122bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001124}
1125
Kate Stoneb9c1b512016-09-06 20:57:50 +00001126CommandAlias *
Zachary Turnera483f572016-10-05 21:14:49 +00001127CommandInterpreter::AddAlias(llvm::StringRef alias_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001128 lldb::CommandObjectSP &command_obj_sp,
Zachary Turnera483f572016-10-05 21:14:49 +00001129 llvm::StringRef args_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130 if (command_obj_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001131 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1132 "tried to add a CommandObject from a different interpreter");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133
1134 std::unique_ptr<CommandAlias> command_alias_up(
1135 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1136
1137 if (command_alias_up && command_alias_up->IsValid()) {
1138 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1139 return command_alias_up.release();
1140 }
1141
1142 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001143}
1144
Zachary Turnera483f572016-10-05 21:14:49 +00001145bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001146 auto pos = m_alias_dict.find(alias_name);
1147 if (pos != m_alias_dict.end()) {
1148 m_alias_dict.erase(pos);
1149 return true;
1150 }
1151 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001152}
1153
Zachary Turnera483f572016-10-05 21:14:49 +00001154bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001155 auto pos = m_command_dict.find(cmd);
1156 if (pos != m_command_dict.end()) {
1157 if (pos->second->IsRemovable()) {
1158 // Only regular expression objects or python commands are removable
1159 m_command_dict.erase(pos);
1160 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001161 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001162 }
1163 return false;
1164}
Zachary Turnera483f572016-10-05 21:14:49 +00001165bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001166 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1167 if (pos != m_user_dict.end()) {
1168 m_user_dict.erase(pos);
1169 return true;
1170 }
1171 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001172}
1173
Kate Stoneb9c1b512016-09-06 20:57:50 +00001174void CommandInterpreter::GetHelp(CommandReturnObject &result,
1175 uint32_t cmd_types) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001176 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1177 if (!help_prologue.empty()) {
1178 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1179 help_prologue);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001180 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001181
Kate Stoneb9c1b512016-09-06 20:57:50 +00001182 CommandObject::CommandMap::const_iterator pos;
1183 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001184
Kate Stoneb9c1b512016-09-06 20:57:50 +00001185 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1186 result.AppendMessage("Debugger commands:");
1187 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001188
Kate Stoneb9c1b512016-09-06 20:57:50 +00001189 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1190 if (!(cmd_types & eCommandTypesHidden) &&
1191 (pos->first.compare(0, 1, "_") == 0))
1192 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001193
Zachary Turner0ac5f982016-11-08 04:12:42 +00001194 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1195 pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001196 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197 result.AppendMessage("");
1198 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001199
Kate Stoneb9c1b512016-09-06 20:57:50 +00001200 if (!m_alias_dict.empty() &&
1201 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1202 result.AppendMessageWithFormat(
1203 "Current command abbreviations "
1204 "(type '%shelp command alias' for more info):\n",
1205 GetCommandPrefix());
1206 result.AppendMessage("");
1207 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001208
Kate Stoneb9c1b512016-09-06 20:57:50 +00001209 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1210 ++alias_pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001211 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
Kate Stoneb9c1b512016-09-06 20:57:50 +00001212 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001213 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214 result.AppendMessage("");
1215 }
Greg Clayton14a35512011-09-11 00:01:44 +00001216
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 if (!m_user_dict.empty() &&
1218 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1219 result.AppendMessage("Current user-defined commands:");
1220 result.AppendMessage("");
1221 max_len = FindLongestCommandWord(m_user_dict);
1222 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001223 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1224 pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001225 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001226 result.AppendMessage("");
1227 }
Greg Clayton14a35512011-09-11 00:01:44 +00001228
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229 result.AppendMessageWithFormat(
1230 "For more information on any command, type '%shelp <command-name>'.\n",
1231 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001232}
1233
Zachary Turnera01bccd2016-10-05 21:14:56 +00001234CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1235 llvm::StringRef &command_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001236 // This function finds the final, lowest-level, alias-resolved command object
Adrian Prantl05097242018-04-30 16:49:04 +00001237 // whose 'Execute' function will eventually be invoked by the given command
1238 // line.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001239
1240 CommandObject *cmd_obj = nullptr;
1241 size_t start = command_string.find_first_not_of(k_white_space);
1242 size_t end = 0;
1243 bool done = false;
1244 while (!done) {
1245 if (start != std::string::npos) {
1246 // Get the next word from command_string.
1247 end = command_string.find_first_of(k_white_space, start);
1248 if (end == std::string::npos)
1249 end = command_string.size();
1250 std::string cmd_word = command_string.substr(start, end - start);
1251
1252 if (cmd_obj == nullptr)
1253 // Since cmd_obj is NULL we are on our first time through this loop.
Zachary Turnera01bccd2016-10-05 21:14:56 +00001254 // Check to see if cmd_word is a valid command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001255 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001256 else if (cmd_obj->IsMultiwordObject()) {
1257 // Our current object is a multi-word object; see if the cmd_word is a
1258 // valid sub-command for our object.
1259 CommandObject *sub_cmd_obj =
1260 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1261 if (sub_cmd_obj)
1262 cmd_obj = sub_cmd_obj;
1263 else // cmd_word was not a valid sub-command word, so we are done
1264 done = true;
1265 } else
1266 // We have a cmd_obj and it is not a multi-word object, so we are done.
1267 done = true;
1268
1269 // If we didn't find a valid command object, or our command object is not
Zachary Turnera01bccd2016-10-05 21:14:56 +00001270 // a multi-word object, or we are at the end of the command_string, then
1271 // we are done. Otherwise, find the start of the next word.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001272
1273 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1274 end >= command_string.size())
1275 done = true;
1276 else
1277 start = command_string.find_first_not_of(k_white_space, end);
1278 } else
1279 // Unable to find any more words.
1280 done = true;
1281 }
1282
Zachary Turnera01bccd2016-10-05 21:14:56 +00001283 command_string = command_string.substr(end);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001284 return cmd_obj;
1285}
1286
1287static const char *k_valid_command_chars =
1288 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1289static void StripLeadingSpaces(std::string &s) {
1290 if (!s.empty()) {
1291 size_t pos = s.find_first_not_of(k_white_space);
1292 if (pos == std::string::npos)
1293 s.clear();
1294 else if (pos == 0)
1295 return;
1296 s.erase(0, pos);
1297 }
1298}
1299
1300static size_t FindArgumentTerminator(const std::string &s) {
1301 const size_t s_len = s.size();
1302 size_t offset = 0;
1303 while (offset < s_len) {
1304 size_t pos = s.find("--", offset);
1305 if (pos == std::string::npos)
1306 break;
1307 if (pos > 0) {
1308 if (isspace(s[pos - 1])) {
Adrian Prantl05097242018-04-30 16:49:04 +00001309 // Check if the string ends "\s--" (where \s is a space character) or
1310 // if we have "\s--\s".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001311 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1312 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001313 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001314 }
1315 }
1316 offset = pos + 2;
1317 }
1318 return std::string::npos;
1319}
1320
1321static bool ExtractCommand(std::string &command_string, std::string &command,
1322 std::string &suffix, char &quote_char) {
1323 command.clear();
1324 suffix.clear();
1325 StripLeadingSpaces(command_string);
1326
1327 bool result = false;
1328 quote_char = '\0';
1329
1330 if (!command_string.empty()) {
1331 const char first_char = command_string[0];
1332 if (first_char == '\'' || first_char == '"') {
1333 quote_char = first_char;
1334 const size_t end_quote_pos = command_string.find(quote_char, 1);
1335 if (end_quote_pos == std::string::npos) {
1336 command.swap(command_string);
1337 command_string.erase();
1338 } else {
1339 command.assign(command_string, 1, end_quote_pos - 1);
1340 if (end_quote_pos + 1 < command_string.size())
1341 command_string.erase(0, command_string.find_first_not_of(
1342 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001343 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344 command_string.erase();
1345 }
1346 } else {
1347 const size_t first_space_pos =
1348 command_string.find_first_of(k_white_space);
1349 if (first_space_pos == std::string::npos) {
1350 command.swap(command_string);
1351 command_string.erase();
1352 } else {
1353 command.assign(command_string, 0, first_space_pos);
1354 command_string.erase(0, command_string.find_first_not_of(
1355 k_white_space, first_space_pos));
1356 }
1357 }
1358 result = true;
1359 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001360
Kate Stoneb9c1b512016-09-06 20:57:50 +00001361 if (!command.empty()) {
1362 // actual commands can't start with '-' or '_'
1363 if (command[0] != '-' && command[0] != '_') {
1364 size_t pos = command.find_first_not_of(k_valid_command_chars);
1365 if (pos > 0 && pos != std::string::npos) {
1366 suffix.assign(command.begin() + pos, command.end());
1367 command.erase(pos);
1368 }
1369 }
1370 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001371
Kate Stoneb9c1b512016-09-06 20:57:50 +00001372 return result;
1373}
1374
1375CommandObject *CommandInterpreter::BuildAliasResult(
Zachary Turnera483f572016-10-05 21:14:49 +00001376 llvm::StringRef alias_name, std::string &raw_input_string,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001377 std::string &alias_result, CommandReturnObject &result) {
1378 CommandObject *alias_cmd_obj = nullptr;
1379 Args cmd_args(raw_input_string);
1380 alias_cmd_obj = GetCommandObject(alias_name);
1381 StreamString result_str;
1382
Zachary Turner5c28c662016-10-03 23:20:36 +00001383 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1384 alias_result.clear();
1385 return alias_cmd_obj;
1386 }
1387 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1388 ((CommandAlias *)alias_cmd_obj)->Desugar();
1389 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1390 alias_cmd_obj = desugared.first.get();
1391 std::string alias_name_str = alias_name;
1392 if ((cmd_args.GetArgumentCount() == 0) ||
1393 (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0))
1394 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395
Zachary Turnera4496982016-10-05 21:14:38 +00001396 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397
Zachary Turner5c28c662016-10-03 23:20:36 +00001398 if (!option_arg_vector_sp.get()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001399 alias_result = result_str.GetString();
Zachary Turner5c28c662016-10-03 23:20:36 +00001400 return alias_cmd_obj;
1401 }
1402 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001403
Zachary Turner5c28c662016-10-03 23:20:36 +00001404 int value_type;
1405 std::string option;
1406 std::string value;
1407 for (const auto &entry : *option_arg_vector) {
1408 std::tie(option, value_type, value) = entry;
1409 if (option == "<argument>") {
1410 result_str.Printf(" %s", value.c_str());
1411 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001412 }
1413
Zachary Turner5c28c662016-10-03 23:20:36 +00001414 result_str.Printf(" %s", option.c_str());
1415 if (value_type == OptionParser::eNoArgument)
1416 continue;
1417
1418 if (value_type != OptionParser::eOptionalArgument)
1419 result_str.Printf(" ");
1420 int index = GetOptionArgumentPosition(value.c_str());
1421 if (index == 0)
1422 result_str.Printf("%s", value.c_str());
1423 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1424
1425 result.AppendErrorWithFormat("Not enough arguments provided; you "
1426 "need at least %d arguments to use "
1427 "this alias.\n",
1428 index);
1429 result.SetStatus(eReturnStatusFailed);
1430 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001431 } else {
1432 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1433 if (strpos != std::string::npos)
1434 raw_input_string = raw_input_string.erase(
1435 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1436 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001437 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001438 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001439
Zachary Turnerc1564272016-11-16 21:15:24 +00001440 alias_result = result_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001441 return alias_cmd_obj;
1442}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001443
Zachary Turner97206d52017-05-12 04:51:55 +00001444Status CommandInterpreter::PreprocessCommand(std::string &command) {
Adrian Prantl05097242018-04-30 16:49:04 +00001445 // The command preprocessor needs to do things to the command line before any
1446 // parsing of arguments or anything else is done. The only current stuff that
1447 // gets preprocessed is anything enclosed in backtick ('`') characters is
1448 // evaluated as an expression and the result of the expression must be a
1449 // scalar that can be substituted into the command. An example would be:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001450 // (lldb) memory read `$rsp + 20`
Zachary Turner97206d52017-05-12 04:51:55 +00001451 Status error; // Status for any expressions that might not evaluate
Kate Stoneb9c1b512016-09-06 20:57:50 +00001452 size_t start_backtick;
1453 size_t pos = 0;
1454 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1455 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
Adrian Prantl05097242018-04-30 16:49:04 +00001456 // The backtick was preceded by a '\' character, remove the slash and
1457 // don't treat the backtick as the start of an expression
Kate Stoneb9c1b512016-09-06 20:57:50 +00001458 command.erase(start_backtick - 1, 1);
1459 // No need to add one to start_backtick since we just deleted a char
1460 pos = start_backtick;
1461 } else {
1462 const size_t expr_content_start = start_backtick + 1;
1463 const size_t end_backtick = command.find('`', expr_content_start);
1464 if (end_backtick == std::string::npos)
1465 return error;
1466 else if (end_backtick == expr_content_start) {
1467 // Empty expression (two backticks in a row)
1468 command.erase(start_backtick, 2);
1469 } else {
1470 std::string expr_str(command, expr_content_start,
1471 end_backtick - expr_content_start);
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001472
Kate Stoneb9c1b512016-09-06 20:57:50 +00001473 ExecutionContext exe_ctx(GetExecutionContext());
1474 Target *target = exe_ctx.GetTargetPtr();
1475 // Get a dummy target to allow for calculator mode while processing
Adrian Prantl05097242018-04-30 16:49:04 +00001476 // backticks. This also helps break the infinite loop caused when
1477 // target is null.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001478 if (!target)
1479 target = m_debugger.GetDummyTarget();
1480 if (target) {
1481 ValueObjectSP expr_result_valobj_sp;
1482
1483 EvaluateExpressionOptions options;
1484 options.SetCoerceToId(false);
1485 options.SetUnwindOnError(true);
1486 options.SetIgnoreBreakpoints(true);
1487 options.SetKeepInMemory(false);
1488 options.SetTryAllThreads(true);
Pavel Labath43d35412016-12-06 11:24:51 +00001489 options.SetTimeout(llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001490
1491 ExpressionResults expr_result = target->EvaluateExpression(
1492 expr_str.c_str(), exe_ctx.GetFramePtr(), expr_result_valobj_sp,
1493 options);
1494
1495 if (expr_result == eExpressionCompleted) {
1496 Scalar scalar;
1497 if (expr_result_valobj_sp)
1498 expr_result_valobj_sp =
1499 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1500 expr_result_valobj_sp->GetDynamicValueType(), true);
1501 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1502 command.erase(start_backtick, end_backtick - start_backtick + 1);
1503 StreamString value_strm;
1504 const bool show_type = false;
1505 scalar.GetValue(&value_strm, show_type);
1506 size_t value_string_size = value_strm.GetSize();
1507 if (value_string_size) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001508 command.insert(start_backtick, value_strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001509 pos = start_backtick + value_string_size;
1510 continue;
1511 } else {
1512 error.SetErrorStringWithFormat("expression value didn't result "
1513 "in a scalar value for the "
1514 "expression '%s'",
1515 expr_str.c_str());
1516 }
1517 } else {
1518 error.SetErrorStringWithFormat("expression value didn't result "
1519 "in a scalar value for the "
1520 "expression '%s'",
1521 expr_str.c_str());
1522 }
1523 } else {
1524 if (expr_result_valobj_sp)
1525 error = expr_result_valobj_sp->GetError();
1526 if (error.Success()) {
1527
1528 switch (expr_result) {
1529 case eExpressionSetupError:
1530 error.SetErrorStringWithFormat(
1531 "expression setup error for the expression '%s'",
1532 expr_str.c_str());
1533 break;
1534 case eExpressionParseError:
1535 error.SetErrorStringWithFormat(
1536 "expression parse error for the expression '%s'",
1537 expr_str.c_str());
1538 break;
1539 case eExpressionResultUnavailable:
1540 error.SetErrorStringWithFormat(
1541 "expression error fetching result for the expression '%s'",
1542 expr_str.c_str());
1543 break;
1544 case eExpressionCompleted:
1545 break;
1546 case eExpressionDiscarded:
1547 error.SetErrorStringWithFormat(
1548 "expression discarded for the expression '%s'",
1549 expr_str.c_str());
1550 break;
1551 case eExpressionInterrupted:
1552 error.SetErrorStringWithFormat(
1553 "expression interrupted for the expression '%s'",
1554 expr_str.c_str());
1555 break;
1556 case eExpressionHitBreakpoint:
1557 error.SetErrorStringWithFormat(
1558 "expression hit breakpoint for the expression '%s'",
1559 expr_str.c_str());
1560 break;
1561 case eExpressionTimedOut:
1562 error.SetErrorStringWithFormat(
1563 "expression timed out for the expression '%s'",
1564 expr_str.c_str());
1565 break;
1566 case eExpressionStoppedForDebug:
1567 error.SetErrorStringWithFormat("expression stop at entry point "
1568 "for debugging for the "
1569 "expression '%s'",
1570 expr_str.c_str());
1571 break;
1572 }
1573 }
1574 }
1575 }
1576 }
1577 if (error.Fail())
1578 break;
1579 }
1580 }
1581 return error;
1582}
1583
1584bool CommandInterpreter::HandleCommand(const char *command_line,
1585 LazyBool lazy_add_to_history,
1586 CommandReturnObject &result,
1587 ExecutionContext *override_context,
1588 bool repeat_on_empty_command,
1589 bool no_context_switching)
1590
1591{
1592
1593 std::string command_string(command_line);
1594 std::string original_command_string(command_line);
1595
1596 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
Jim Ingham8f7db522016-12-15 00:30:30 +00001597 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
Sean Callanan237c3ed2016-12-14 21:31:31 +00001598 command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001599
1600 if (log)
1601 log->Printf("Processing command: %s", command_line);
1602
Pavel Labathf9d16472017-05-15 13:02:37 +00001603 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1604 Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001605
1606 if (!no_context_switching)
1607 UpdateExecutionContext(override_context);
1608
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001609 if (WasInterrupted()) {
1610 result.AppendError("interrupted");
1611 result.SetStatus(eReturnStatusFailed);
1612 return false;
1613 }
1614
Kate Stoneb9c1b512016-09-06 20:57:50 +00001615 bool add_to_history;
1616 if (lazy_add_to_history == eLazyBoolCalculate)
1617 add_to_history = (m_command_source_depth == 0);
1618 else
1619 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1620
1621 bool empty_command = false;
1622 bool comment_command = false;
1623 if (command_string.empty())
1624 empty_command = true;
1625 else {
1626 const char *k_space_characters = "\t\n\v\f\r ";
1627
1628 size_t non_space = command_string.find_first_not_of(k_space_characters);
Adrian Prantl05097242018-04-30 16:49:04 +00001629 // Check for empty line or comment line (lines whose first non-space
1630 // character is the comment character for this interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001631 if (non_space == std::string::npos)
1632 empty_command = true;
1633 else if (command_string[non_space] == m_comment_char)
1634 comment_command = true;
1635 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001636 llvm::StringRef search_str(command_string);
1637 search_str = search_str.drop_front(non_space);
1638 if (auto hist_str = m_command_history.FindString(search_str)) {
1639 add_to_history = false;
1640 command_string = *hist_str;
1641 original_command_string = *hist_str;
1642 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001643 result.AppendErrorWithFormat("Could not find entry: %s in history",
1644 command_string.c_str());
1645 result.SetStatus(eReturnStatusFailed);
1646 return false;
1647 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001648 }
1649 }
1650
1651 if (empty_command) {
1652 if (repeat_on_empty_command) {
1653 if (m_command_history.IsEmpty()) {
1654 result.AppendError("empty command");
1655 result.SetStatus(eReturnStatusFailed);
1656 return false;
1657 } else {
1658 command_line = m_repeat_command.c_str();
1659 command_string = command_line;
1660 original_command_string = command_line;
1661 if (m_repeat_command.empty()) {
1662 result.AppendErrorWithFormat("No auto repeat.\n");
1663 result.SetStatus(eReturnStatusFailed);
1664 return false;
1665 }
1666 }
1667 add_to_history = false;
1668 } else {
1669 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1670 return true;
1671 }
1672 } else if (comment_command) {
1673 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1674 return true;
1675 }
1676
Zachary Turner97206d52017-05-12 04:51:55 +00001677 Status error(PreprocessCommand(command_string));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001678
1679 if (error.Fail()) {
1680 result.AppendError(error.AsCString());
1681 result.SetStatus(eReturnStatusFailed);
1682 return false;
1683 }
1684
1685 // Phase 1.
1686
1687 // Before we do ANY kind of argument processing, we need to figure out what
1688 // the real/final command object is for the specified command. This gets
1689 // complicated by the fact that the user could have specified an alias, and,
1690 // in translating the alias, there may also be command options and/or even
1691 // data (including raw text strings) that need to be found and inserted into
1692 // the command line as part of the translation. So this first step is plain
1693 // look-up and replacement, resulting in:
1694 // 1. the command object whose Execute method will actually be called
1695 // 2. a revised command string, with all substitutions and replacements
1696 // taken care of
1697 // From 1 above, we can determine whether the Execute function wants raw
1698 // input or not.
1699
1700 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1701
1702 // Although the user may have abbreviated the command, the command_string now
Adrian Prantl05097242018-04-30 16:49:04 +00001703 // has the command expanded to the full name. For example, if the input was
1704 // "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001705 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001706 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1707 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001708 log->Printf("HandleCommand, (revised) command_string: '%s'",
1709 command_string.c_str());
1710 const bool wants_raw_input =
1711 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1712 log->Printf("HandleCommand, wants_raw_input:'%s'",
1713 wants_raw_input ? "True" : "False");
1714 }
1715
1716 // Phase 2.
1717 // Take care of things like setting up the history command & calling the
Adrian Prantl05097242018-04-30 16:49:04 +00001718 // appropriate Execute method on the CommandObject, with the appropriate
1719 // arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001720
1721 if (cmd_obj != nullptr) {
1722 if (add_to_history) {
1723 Args command_args(command_string);
1724 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1725 if (repeat_command != nullptr)
1726 m_repeat_command.assign(repeat_command);
1727 else
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001728 m_repeat_command.assign(original_command_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001729
1730 m_command_history.AppendString(original_command_string);
1731 }
1732
1733 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001734 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001735 if (actual_cmd_name_len < command_string.length())
1736 remainder = command_string.substr(actual_cmd_name_len);
1737
1738 // Remove any initial spaces
1739 size_t pos = remainder.find_first_not_of(k_white_space);
1740 if (pos != 0 && pos != std::string::npos)
1741 remainder.erase(0, pos);
1742
1743 if (log)
1744 log->Printf(
1745 "HandleCommand, command line after removing command name(s): '%s'",
1746 remainder.c_str());
1747
1748 cmd_obj->Execute(remainder.c_str(), result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001749 }
1750
1751 if (log)
1752 log->Printf("HandleCommand, command %s",
1753 (result.Succeeded() ? "succeeded" : "did not succeed"));
1754
1755 return result.Succeeded();
1756}
1757
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001758int CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001759 int num_command_matches = 0;
1760 bool look_for_subcommand = false;
1761
1762 // For any of the command completions a unique match will be a complete word.
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001763 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001764
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001765 if (request.GetCursorIndex() == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001766 // We got nothing on the command line, so return the list of commands
1767 bool include_aliases = true;
Raphael Isemann7f888292018-09-13 21:26:00 +00001768 StringList new_matches, descriptions;
1769 num_command_matches = GetCommandNamesMatchingPartialString(
1770 "", include_aliases, new_matches, descriptions);
1771 request.AddCompletions(new_matches, descriptions);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001772 } else if (request.GetCursorIndex() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001773 // The cursor is in the first argument, so just do a lookup in the
1774 // dictionary.
Raphael Isemann7f888292018-09-13 21:26:00 +00001775 StringList new_matches, new_descriptions;
1776 CommandObject *cmd_obj =
1777 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0),
1778 &new_matches, &new_descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001779
1780 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001781 new_matches.GetStringAtIndex(0) != nullptr &&
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001782 strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001783 new_matches.GetStringAtIndex(0)) == 0) {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001784 if (request.GetParsedLine().GetArgumentCount() == 1) {
1785 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001786 } else {
1787 look_for_subcommand = true;
1788 num_command_matches = 0;
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001789 new_matches.DeleteStringAtIndex(0);
Raphael Isemann7f888292018-09-13 21:26:00 +00001790 new_descriptions.DeleteStringAtIndex(0);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001791 request.GetParsedLine().AppendArgument(llvm::StringRef());
1792 request.SetCursorIndex(request.GetCursorIndex() + 1);
1793 request.SetCursorCharPosition(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001794 }
1795 }
Raphael Isemann7f888292018-09-13 21:26:00 +00001796 request.AddCompletions(new_matches, new_descriptions);
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001797 num_command_matches = request.GetNumberOfMatches();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001798 }
1799
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001800 if (request.GetCursorIndex() > 0 || look_for_subcommand) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001801 // We are completing further on into a commands arguments, so find the
Adrian Prantl05097242018-04-30 16:49:04 +00001802 // command and tell it to complete the command. First see if there is a
1803 // matching initial command:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001804 CommandObject *command_object =
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001805 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001806 if (command_object == nullptr) {
1807 return 0;
1808 } else {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001809 request.GetParsedLine().Shift();
1810 request.SetCursorIndex(request.GetCursorIndex() - 1);
1811 num_command_matches = command_object->HandleCompletion(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001812 }
1813 }
1814
1815 return num_command_matches;
1816}
1817
1818int CommandInterpreter::HandleCompletion(
1819 const char *current_line, const char *cursor, const char *last_char,
Raphael Isemann7f888292018-09-13 21:26:00 +00001820 int match_start_point, int max_return_elements, StringList &matches,
1821 StringList &descriptions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001822
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001823 llvm::StringRef command_line(current_line, last_char - current_line);
Raphael Isemann7f888292018-09-13 21:26:00 +00001824 CompletionResult result;
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001825 CompletionRequest request(command_line, cursor - current_line,
Raphael Isemann7f888292018-09-13 21:26:00 +00001826 match_start_point, max_return_elements, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001827 // Don't complete comments, and if the line we are completing is just the
Adrian Prantl05097242018-04-30 16:49:04 +00001828 // history repeat character, substitute the appropriate history line.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001829 const char *first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001830 if (first_arg) {
1831 if (first_arg[0] == m_comment_char)
1832 return 0;
1833 else if (first_arg[0] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001834 if (auto hist_str = m_command_history.FindString(first_arg)) {
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001835 matches.InsertStringAtIndex(0, *hist_str);
Raphael Isemann7f888292018-09-13 21:26:00 +00001836 descriptions.InsertStringAtIndex(0, "Previous command history event");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001837 return -2;
1838 } else
1839 return 0;
1840 }
1841 }
1842
Kate Stoneb9c1b512016-09-06 20:57:50 +00001843 // Only max_return_elements == -1 is supported at present:
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001844 lldbassert(max_return_elements == -1);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001845
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001846 int num_command_matches = HandleCompletionMatches(request);
Raphael Isemann7f888292018-09-13 21:26:00 +00001847 result.GetMatches(matches);
1848 result.GetDescriptions(descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001849
1850 if (num_command_matches <= 0)
1851 return num_command_matches;
1852
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001853 if (request.GetParsedLine().GetArgumentCount() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001854 // If we got an empty string, insert nothing.
1855 matches.InsertStringAtIndex(0, "");
Raphael Isemann7f888292018-09-13 21:26:00 +00001856 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001857 } else {
1858 // Now figure out if there is a common substring, and if so put that in
Adrian Prantl05097242018-04-30 16:49:04 +00001859 // element 0, otherwise put an empty string in element 0.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001860 std::string command_partial_str = request.GetCursorArgumentPrefix().str();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001861
1862 std::string common_prefix;
1863 matches.LongestCommonPrefix(common_prefix);
1864 const size_t partial_name_len = command_partial_str.size();
1865 common_prefix.erase(0, partial_name_len);
1866
Adrian Prantl05097242018-04-30 16:49:04 +00001867 // If we matched a unique single command, add a space... Only do this if
1868 // the completer told us this was a complete word, however...
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001869 if (num_command_matches == 1 && request.GetWordComplete()) {
1870 char quote_char = request.GetParsedLine()[request.GetCursorIndex()].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001871 common_prefix =
1872 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1873 if (quote_char != '\0')
1874 common_prefix.push_back(quote_char);
1875 common_prefix.push_back(' ');
1876 }
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001877 matches.InsertStringAtIndex(0, common_prefix.c_str());
Raphael Isemann7f888292018-09-13 21:26:00 +00001878 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001879 }
1880 return num_command_matches;
1881}
1882
1883CommandInterpreter::~CommandInterpreter() {}
1884
Zachary Turner514d8cd2016-09-23 18:06:53 +00001885void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001886 EventSP prompt_change_event_sp(
1887 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1888 ;
1889 BroadcastEvent(prompt_change_event_sp);
1890 if (m_command_io_handler_sp)
1891 m_command_io_handler_sp->SetPrompt(new_prompt);
1892}
1893
Zachary Turner7a120c82016-11-13 03:05:58 +00001894bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001895 // Check AutoConfirm first:
1896 if (m_debugger.GetAutoConfirm())
1897 return default_answer;
1898
1899 IOHandlerConfirm *confirm =
1900 new IOHandlerConfirm(m_debugger, message, default_answer);
1901 IOHandlerSP io_handler_sp(confirm);
1902 m_debugger.RunIOHandler(io_handler_sp);
1903 return confirm->GetResponse();
1904}
1905
Zachary Turnera483f572016-10-05 21:14:49 +00001906const CommandAlias *
1907CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001908 OptionArgVectorSP ret_val;
1909
Zachary Turnera483f572016-10-05 21:14:49 +00001910 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001911 if (pos != m_alias_dict.end())
1912 return (CommandAlias *)pos->second.get();
1913
1914 return nullptr;
1915}
1916
Zachary Turnera4496982016-10-05 21:14:38 +00001917bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001918
Zachary Turnera4496982016-10-05 21:14:38 +00001919bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001920
Zachary Turnera4496982016-10-05 21:14:38 +00001921bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001922
Zachary Turnera4496982016-10-05 21:14:38 +00001923bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001924
1925void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1926 const char *alias_name,
1927 Args &cmd_args,
1928 std::string &raw_input_string,
1929 CommandReturnObject &result) {
1930 OptionArgVectorSP option_arg_vector_sp =
1931 GetAlias(alias_name)->GetOptionArguments();
1932
1933 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1934
1935 // Make sure that the alias name is the 0th element in cmd_args
1936 std::string alias_name_str = alias_name;
1937 if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)
Zachary Turner5c725f32016-09-19 21:56:59 +00001938 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001939
1940 Args new_args(alias_cmd_obj->GetCommandName());
1941 if (new_args.GetArgumentCount() == 2)
1942 new_args.Shift();
1943
1944 if (option_arg_vector_sp.get()) {
1945 if (wants_raw_input) {
1946 // We have a command that both has command options and takes raw input.
Adrian Prantl05097242018-04-30 16:49:04 +00001947 // Make *sure* it has a " -- " in the right place in the
1948 // raw_input_string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001949 size_t pos = raw_input_string.find(" -- ");
1950 if (pos == std::string::npos) {
1951 // None found; assume it goes at the beginning of the raw input string
1952 raw_input_string.insert(0, " -- ");
1953 }
1954 }
1955
1956 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1957 const size_t old_size = cmd_args.GetArgumentCount();
1958 std::vector<bool> used(old_size + 1, false);
1959
1960 used[0] = true;
1961
Zachary Turner5c28c662016-10-03 23:20:36 +00001962 int value_type;
1963 std::string option;
1964 std::string value;
1965 for (const auto &option_entry : *option_arg_vector) {
1966 std::tie(option, value_type, value) = option_entry;
1967 if (option == "<argument>") {
1968 if (!wants_raw_input || (value != "--")) {
1969 // Since we inserted this above, make sure we don't insert it twice
1970 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001971 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001972 continue;
1973 }
1974
1975 if (value_type != OptionParser::eOptionalArgument)
1976 new_args.AppendArgument(option);
1977
1978 if (value == "<no-argument>")
1979 continue;
1980
1981 int index = GetOptionArgumentPosition(value.c_str());
1982 if (index == 0) {
1983 // value was NOT a positional argument; must be a real value
1984 if (value_type != OptionParser::eOptionalArgument)
1985 new_args.AppendArgument(value);
1986 else {
1987 char buffer[255];
1988 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1989 value.c_str());
1990 new_args.AppendArgument(llvm::StringRef(buffer));
1991 }
1992
1993 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1994 result.AppendErrorWithFormat("Not enough arguments provided; you "
1995 "need at least %d arguments to use "
1996 "this alias.\n",
1997 index);
1998 result.SetStatus(eReturnStatusFailed);
1999 return;
2000 } else {
2001 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2002 size_t strpos =
2003 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
2004 if (strpos != std::string::npos) {
2005 raw_input_string = raw_input_string.erase(
2006 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2007 }
2008
2009 if (value_type != OptionParser::eOptionalArgument)
2010 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2011 else {
2012 char buffer[255];
2013 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2014 cmd_args.GetArgumentAtIndex(index));
2015 new_args.AppendArgument(buffer);
2016 }
2017 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002018 }
2019 }
2020
Zachary Turner97d2c402016-10-05 23:40:23 +00002021 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00002022 if (!used[entry.index()] && !wants_raw_input)
2023 new_args.AppendArgument(entry.value().ref);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002024 }
2025
2026 cmd_args.Clear();
2027 cmd_args.SetArguments(new_args.GetArgumentCount(),
2028 new_args.GetConstArgumentVector());
2029 } else {
2030 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2031 // This alias was not created with any options; nothing further needs to be
Adrian Prantl05097242018-04-30 16:49:04 +00002032 // done, unless it is a command that wants raw input, in which case we need
2033 // to clear the rest of the data from cmd_args, since its in the raw input
2034 // string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002035 if (wants_raw_input) {
2036 cmd_args.Clear();
2037 cmd_args.SetArguments(new_args.GetArgumentCount(),
2038 new_args.GetConstArgumentVector());
2039 }
2040 return;
2041 }
2042
2043 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2044 return;
2045}
2046
2047int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2048 int position = 0; // Any string that isn't an argument position, i.e. '%'
2049 // followed by an integer, gets a position
2050 // of zero.
2051
2052 const char *cptr = in_string;
2053
2054 // Does it start with '%'
2055 if (cptr[0] == '%') {
2056 ++cptr;
2057
2058 // Is the rest of it entirely digits?
2059 if (isdigit(cptr[0])) {
2060 const char *start = cptr;
2061 while (isdigit(cptr[0]))
2062 ++cptr;
2063
Adrian Prantl05097242018-04-30 16:49:04 +00002064 // We've gotten to the end of the digits; are we at the end of the
2065 // string?
Kate Stoneb9c1b512016-09-06 20:57:50 +00002066 if (cptr[0] == '\0')
2067 position = atoi(start);
2068 }
2069 }
2070
2071 return position;
2072}
2073
2074void CommandInterpreter::SourceInitFile(bool in_cwd,
2075 CommandReturnObject &result) {
2076 FileSpec init_file;
2077 if (in_cwd) {
2078 ExecutionContext exe_ctx(GetExecutionContext());
2079 Target *target = exe_ctx.GetTargetPtr();
2080 if (target) {
2081 // In the current working directory we don't load any program specific
2082 // .lldbinit files, we only look for a ".lldbinit" file.
2083 if (m_skip_lldbinit_files)
2084 return;
2085
2086 LoadCWDlldbinitFile should_load =
2087 target->TargetProperties::GetLoadCWDlldbinitFile();
2088 if (should_load == eLoadCWDlldbinitWarn) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002089 FileSpec dot_lldb(".lldbinit");
2090 FileSystem::Instance().Resolve(dot_lldb);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002091 llvm::SmallString<64> home_dir_path;
2092 llvm::sys::path::home_directory(home_dir_path);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002093 FileSpec homedir_dot_lldb(home_dir_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002094 homedir_dot_lldb.AppendPathComponent(".lldbinit");
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002095 FileSystem::Instance().Resolve(homedir_dot_lldb);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002096 if (FileSystem::Instance().Exists(dot_lldb) &&
Kate Stoneb9c1b512016-09-06 20:57:50 +00002097 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2098 result.AppendErrorWithFormat(
2099 "There is a .lldbinit file in the current directory which is not "
2100 "being read.\n"
2101 "To silence this warning without sourcing in the local "
2102 ".lldbinit,\n"
2103 "add the following to the lldbinit file in your home directory:\n"
2104 " settings set target.load-cwd-lldbinit false\n"
2105 "To allow lldb to source .lldbinit files in the current working "
2106 "directory,\n"
2107 "set the value of this variable to true. Only do so if you "
2108 "understand and\n"
2109 "accept the security risk.");
2110 result.SetStatus(eReturnStatusFailed);
2111 return;
2112 }
2113 } else if (should_load == eLoadCWDlldbinitTrue) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002114 init_file.SetFile("./.lldbinit", FileSpec::Style::native);
2115 FileSystem::Instance().Resolve(init_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002116 }
2117 }
2118 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002119 // If we aren't looking in the current working directory we are looking in
2120 // the home directory. We will first see if there is an application
2121 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a "-"
2122 // and the name of the program. If this file doesn't exist, we fall back to
2123 // just the "~/.lldbinit" file. We also obey any requests to not load the
2124 // init files.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002125 llvm::SmallString<64> home_dir_path;
2126 llvm::sys::path::home_directory(home_dir_path);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002127 FileSpec profilePath(home_dir_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002128 profilePath.AppendPathComponent(".lldbinit");
2129 std::string init_file_path = profilePath.GetPath();
2130
2131 if (m_skip_app_init_files == false) {
2132 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2133 const char *program_name = program_file_spec.GetFilename().AsCString();
2134
2135 if (program_name) {
2136 char program_init_file_name[PATH_MAX];
2137 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2138 "%s-%s", init_file_path.c_str(), program_name);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002139 init_file.SetFile(program_init_file_name, FileSpec::Style::native);
2140 FileSystem::Instance().Resolve(init_file);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002141 if (!FileSystem::Instance().Exists(init_file))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002142 init_file.Clear();
2143 }
2144 }
2145
2146 if (!init_file && !m_skip_lldbinit_files)
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002147 init_file.SetFile(init_file_path, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002148 }
2149
2150 // If the file exists, tell HandleCommand to 'source' it; this will do the
Adrian Prantl05097242018-04-30 16:49:04 +00002151 // actual broadcasting of the commands back to any appropriate listener (see
Kate Stoneb9c1b512016-09-06 20:57:50 +00002152 // CommandObjectSource::Execute for more details).
2153
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002154 if (FileSystem::Instance().Exists(init_file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002155 const bool saved_batch = SetBatchCommandMode(true);
2156 CommandInterpreterRunOptions options;
2157 options.SetSilent(true);
2158 options.SetStopOnError(false);
2159 options.SetStopOnContinue(true);
2160
2161 HandleCommandsFromFile(init_file,
2162 nullptr, // Execution context
2163 options, result);
2164 SetBatchCommandMode(saved_batch);
2165 } else {
2166 // nothing to be done if the file doesn't exist
2167 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2168 }
2169}
2170
2171const char *CommandInterpreter::GetCommandPrefix() {
2172 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2173 return prefix == NULL ? "" : prefix;
2174}
2175
2176PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2177 PlatformSP platform_sp;
2178 if (prefer_target_platform) {
2179 ExecutionContext exe_ctx(GetExecutionContext());
2180 Target *target = exe_ctx.GetTargetPtr();
2181 if (target)
2182 platform_sp = target->GetPlatform();
2183 }
2184
2185 if (!platform_sp)
2186 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2187 return platform_sp;
2188}
2189
2190void CommandInterpreter::HandleCommands(const StringList &commands,
2191 ExecutionContext *override_context,
2192 CommandInterpreterRunOptions &options,
2193 CommandReturnObject &result) {
2194 size_t num_lines = commands.GetSize();
2195
2196 // If we are going to continue past a "continue" then we need to run the
Adrian Prantl05097242018-04-30 16:49:04 +00002197 // commands synchronously. Make sure you reset this value anywhere you return
2198 // from the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002199
2200 bool old_async_execution = m_debugger.GetAsyncExecution();
2201
2202 // If we've been given an execution context, set it at the start, but don't
Adrian Prantl05097242018-04-30 16:49:04 +00002203 // keep resetting it or we will cause series of commands that change the
2204 // context, then do an operation that relies on that context to fail.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002205
2206 if (override_context != nullptr)
2207 UpdateExecutionContext(override_context);
2208
2209 if (!options.GetStopOnContinue()) {
2210 m_debugger.SetAsyncExecution(false);
2211 }
2212
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002213 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002214 const char *cmd = commands.GetStringAtIndex(idx);
2215 if (cmd[0] == '\0')
2216 continue;
2217
2218 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002219 // TODO: Add Stream support.
2220 result.AppendMessageWithFormat("%s %s\n",
2221 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002222 }
2223
2224 CommandReturnObject tmp_result;
2225 // If override_context is not NULL, pass no_context_switching = true for
2226 // HandleCommand() since we updated our context already.
2227
2228 // We might call into a regex or alias command, in which case the
Adrian Prantl05097242018-04-30 16:49:04 +00002229 // add_to_history will get lost. This m_command_source_depth dingus is the
2230 // way we turn off adding to the history in that case, so set it up here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002231 if (!options.GetAddToHistory())
2232 m_command_source_depth++;
2233 bool success =
2234 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2235 nullptr, /* override_context */
2236 true, /* repeat_on_empty_command */
2237 override_context != nullptr /* no_context_switching */);
2238 if (!options.GetAddToHistory())
2239 m_command_source_depth--;
2240
2241 if (options.GetPrintResults()) {
2242 if (tmp_result.Succeeded())
Zachary Turner03c9f362016-11-14 23:23:31 +00002243 result.AppendMessage(tmp_result.GetOutputData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002244 }
2245
2246 if (!success || !tmp_result.Succeeded()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002247 llvm::StringRef error_msg = tmp_result.GetErrorData();
2248 if (error_msg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002249 error_msg = "<unknown error>.\n";
2250 if (options.GetStopOnError()) {
2251 result.AppendErrorWithFormat(
2252 "Aborting reading of commands after command #%" PRIu64
2253 ": '%s' failed with %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00002254 (uint64_t)idx, cmd, error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002255 result.SetStatus(eReturnStatusFailed);
2256 m_debugger.SetAsyncExecution(old_async_execution);
2257 return;
2258 } else if (options.GetPrintResults()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002259 result.AppendMessageWithFormat(
2260 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2261 error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002262 }
2263 }
2264
2265 if (result.GetImmediateOutputStream())
2266 result.GetImmediateOutputStream()->Flush();
2267
2268 if (result.GetImmediateErrorStream())
2269 result.GetImmediateErrorStream()->Flush();
2270
Adrian Prantl05097242018-04-30 16:49:04 +00002271 // N.B. Can't depend on DidChangeProcessState, because the state coming
2272 // into the command execution could be running (for instance in Breakpoint
2273 // Commands. So we check the return value to see if it is has running in
2274 // it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002275 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2276 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2277 if (options.GetStopOnContinue()) {
2278 // If we caused the target to proceed, and we're going to stop in that
Adrian Prantl05097242018-04-30 16:49:04 +00002279 // case, set the status in our real result before returning. This is
2280 // an error if the continue was not the last command in the set of
2281 // commands to be run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002282 if (idx != num_lines - 1)
2283 result.AppendErrorWithFormat(
2284 "Aborting reading of commands after command #%" PRIu64
2285 ": '%s' continued the target.\n",
2286 (uint64_t)idx + 1, cmd);
2287 else
2288 result.AppendMessageWithFormat("Command #%" PRIu64
2289 " '%s' continued the target.\n",
2290 (uint64_t)idx + 1, cmd);
2291
2292 result.SetStatus(tmp_result.GetStatus());
2293 m_debugger.SetAsyncExecution(old_async_execution);
2294
2295 return;
2296 }
2297 }
2298
2299 // Also check for "stop on crash here:
2300 bool should_stop = false;
2301 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2302 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2303 if (target_sp) {
2304 ProcessSP process_sp(target_sp->GetProcessSP());
2305 if (process_sp) {
2306 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2307 StopReason reason = thread_sp->GetStopReason();
2308 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2309 reason == eStopReasonInstrumentation) {
2310 should_stop = true;
2311 break;
2312 }
2313 }
2314 }
2315 }
2316 if (should_stop) {
2317 if (idx != num_lines - 1)
2318 result.AppendErrorWithFormat(
2319 "Aborting reading of commands after command #%" PRIu64
2320 ": '%s' stopped with a signal or exception.\n",
2321 (uint64_t)idx + 1, cmd);
2322 else
2323 result.AppendMessageWithFormat(
2324 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2325 (uint64_t)idx + 1, cmd);
2326
2327 result.SetStatus(tmp_result.GetStatus());
2328 m_debugger.SetAsyncExecution(old_async_execution);
2329
2330 return;
2331 }
2332 }
2333 }
2334
2335 result.SetStatus(eReturnStatusSuccessFinishResult);
2336 m_debugger.SetAsyncExecution(old_async_execution);
2337
2338 return;
2339}
2340
2341// Make flags that we can pass into the IOHandler so our delegates can do the
2342// right thing
2343enum {
2344 eHandleCommandFlagStopOnContinue = (1u << 0),
2345 eHandleCommandFlagStopOnError = (1u << 1),
2346 eHandleCommandFlagEchoCommand = (1u << 2),
Stefan Granitzc678ed72018-10-05 16:49:47 +00002347 eHandleCommandFlagEchoCommentCommand = (1u << 3),
2348 eHandleCommandFlagPrintResult = (1u << 4),
2349 eHandleCommandFlagStopOnCrash = (1u << 5)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002350};
2351
2352void CommandInterpreter::HandleCommandsFromFile(
2353 FileSpec &cmd_file, ExecutionContext *context,
2354 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002355 if (FileSystem::Instance().Exists(cmd_file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002356 StreamFileSP input_file_sp(new StreamFile());
2357
2358 std::string cmd_file_path = cmd_file.GetPath();
Jonas Devlieghere50bc1ed2018-11-02 22:34:51 +00002359 Status error = FileSystem::Instance().Open(input_file_sp->GetFile(),
2360 cmd_file, File::eOpenOptionRead);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002361 if (error.Success()) {
2362 Debugger &debugger = GetDebugger();
2363
2364 uint32_t flags = 0;
2365
2366 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2367 if (m_command_source_flags.empty()) {
2368 // Stop on continue by default
2369 flags |= eHandleCommandFlagStopOnContinue;
2370 } else if (m_command_source_flags.back() &
2371 eHandleCommandFlagStopOnContinue) {
2372 flags |= eHandleCommandFlagStopOnContinue;
2373 }
2374 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2375 flags |= eHandleCommandFlagStopOnContinue;
2376 }
2377
2378 if (options.m_stop_on_error == eLazyBoolCalculate) {
2379 if (m_command_source_flags.empty()) {
2380 if (GetStopCmdSourceOnError())
2381 flags |= eHandleCommandFlagStopOnError;
2382 } else if (m_command_source_flags.back() &
2383 eHandleCommandFlagStopOnError) {
2384 flags |= eHandleCommandFlagStopOnError;
2385 }
2386 } else if (options.m_stop_on_error == eLazyBoolYes) {
2387 flags |= eHandleCommandFlagStopOnError;
2388 }
2389
Stefan Granitzc678ed72018-10-05 16:49:47 +00002390 // stop-on-crash can only be set, if it is present in all levels of
2391 // pushed flag sets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002392 if (options.GetStopOnCrash()) {
2393 if (m_command_source_flags.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002394 flags |= eHandleCommandFlagStopOnCrash;
2395 } else if (m_command_source_flags.back() &
2396 eHandleCommandFlagStopOnCrash) {
2397 flags |= eHandleCommandFlagStopOnCrash;
2398 }
2399 }
2400
2401 if (options.m_echo_commands == eLazyBoolCalculate) {
2402 if (m_command_source_flags.empty()) {
2403 // Echo command by default
2404 flags |= eHandleCommandFlagEchoCommand;
2405 } else if (m_command_source_flags.back() &
2406 eHandleCommandFlagEchoCommand) {
2407 flags |= eHandleCommandFlagEchoCommand;
2408 }
2409 } else if (options.m_echo_commands == eLazyBoolYes) {
2410 flags |= eHandleCommandFlagEchoCommand;
2411 }
2412
Stefan Granitzc678ed72018-10-05 16:49:47 +00002413 // We will only ever ask for this flag, if we echo commands in general.
2414 if (options.m_echo_comment_commands == eLazyBoolCalculate) {
2415 if (m_command_source_flags.empty()) {
2416 // Echo comments by default
2417 flags |= eHandleCommandFlagEchoCommentCommand;
2418 } else if (m_command_source_flags.back() &
2419 eHandleCommandFlagEchoCommentCommand) {
2420 flags |= eHandleCommandFlagEchoCommentCommand;
2421 }
2422 } else if (options.m_echo_comment_commands == eLazyBoolYes) {
2423 flags |= eHandleCommandFlagEchoCommentCommand;
2424 }
2425
Kate Stoneb9c1b512016-09-06 20:57:50 +00002426 if (options.m_print_results == eLazyBoolCalculate) {
2427 if (m_command_source_flags.empty()) {
2428 // Print output by default
2429 flags |= eHandleCommandFlagPrintResult;
2430 } else if (m_command_source_flags.back() &
2431 eHandleCommandFlagPrintResult) {
2432 flags |= eHandleCommandFlagPrintResult;
2433 }
2434 } else if (options.m_print_results == eLazyBoolYes) {
2435 flags |= eHandleCommandFlagPrintResult;
2436 }
2437
2438 if (flags & eHandleCommandFlagPrintResult) {
2439 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2440 cmd_file_path.c_str());
2441 }
2442
Adrian Prantl05097242018-04-30 16:49:04 +00002443 // Used for inheriting the right settings when "command source" might
2444 // have nested "command source" commands
Kate Stoneb9c1b512016-09-06 20:57:50 +00002445 lldb::StreamFileSP empty_stream_sp;
2446 m_command_source_flags.push_back(flags);
2447 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2448 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2449 empty_stream_sp, // Pass in an empty stream so we inherit the top
2450 // input reader output stream
2451 empty_stream_sp, // Pass in an empty stream so we inherit the top
2452 // input reader error stream
2453 flags,
2454 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2455 // or written
Zachary Turner514d8cd2016-09-23 18:06:53 +00002456 debugger.GetPrompt(), llvm::StringRef(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00002457 false, // Not multi-line
2458 debugger.GetUseColor(), 0, *this));
2459 const bool old_async_execution = debugger.GetAsyncExecution();
2460
2461 // Set synchronous execution if we are not stopping on continue
2462 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2463 debugger.SetAsyncExecution(false);
2464
2465 m_command_source_depth++;
2466
2467 debugger.RunIOHandler(io_handler_sp);
2468 if (!m_command_source_flags.empty())
2469 m_command_source_flags.pop_back();
2470 m_command_source_depth--;
2471 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2472 debugger.SetAsyncExecution(old_async_execution);
2473 } else {
2474 result.AppendErrorWithFormat(
2475 "error: an error occurred read file '%s': %s\n",
2476 cmd_file_path.c_str(), error.AsCString());
2477 result.SetStatus(eReturnStatusFailed);
2478 }
2479
2480 } else {
2481 result.AppendErrorWithFormat(
2482 "Error reading commands from file %s - file not found.\n",
2483 cmd_file.GetFilename().AsCString("<Unknown>"));
2484 result.SetStatus(eReturnStatusFailed);
2485 return;
2486 }
2487}
2488
2489ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
Jim Ingham30bac792017-07-13 19:45:54 +00002490 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
Greg Clayton79040462016-12-09 01:21:14 +00002491 if (!m_script_interpreter_sp) {
2492 if (!can_create)
2493 return nullptr;
2494 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2495 m_script_interpreter_sp =
2496 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2497 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002498 return m_script_interpreter_sp.get();
2499}
2500
2501bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2502
2503void CommandInterpreter::SetSynchronous(bool value) {
2504 m_synchronous_execution = value;
2505}
2506
2507void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002508 llvm::StringRef prefix,
2509 llvm::StringRef help_text) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002510 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002511
Zachary Turner0ac5f982016-11-08 04:12:42 +00002512 size_t line_width_max = max_columns - prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002513 if (line_width_max < 16)
Zachary Turner0ac5f982016-11-08 04:12:42 +00002514 line_width_max = help_text.size() + prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002515
Zachary Turner0ac5f982016-11-08 04:12:42 +00002516 strm.IndentMore(prefix.size());
2517 bool prefixed_yet = false;
2518 while (!help_text.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002519 // Prefix the first line, indent subsequent lines to line up
Zachary Turner0ac5f982016-11-08 04:12:42 +00002520 if (!prefixed_yet) {
2521 strm << prefix;
2522 prefixed_yet = true;
2523 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002524 strm.Indent();
Zachary Turner0ac5f982016-11-08 04:12:42 +00002525
2526 // Never print more than the maximum on one line.
2527 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2528
2529 // Always break on an explicit newline.
2530 std::size_t first_newline = this_line.find_first_of("\n");
2531
2532 // Don't break on space/tab unless the text is too long to fit on one line.
2533 std::size_t last_space = llvm::StringRef::npos;
2534 if (this_line.size() != help_text.size())
2535 last_space = this_line.find_last_of(" \t");
2536
2537 // Break at whichever condition triggered first.
2538 this_line = this_line.substr(0, std::min(first_newline, last_space));
2539 strm.PutCString(this_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002540 strm.EOL();
2541
Zachary Turner0ac5f982016-11-08 04:12:42 +00002542 // Remove whitespace / newlines after breaking.
2543 help_text = help_text.drop_front(this_line.size()).ltrim();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002544 }
Zachary Turner0ac5f982016-11-08 04:12:42 +00002545 strm.IndentLess(prefix.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002546}
2547
2548void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002549 llvm::StringRef word_text,
2550 llvm::StringRef separator,
2551 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002552 size_t max_word_len) {
2553 StreamString prefix_stream;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002554 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2555 (int)separator.size(), separator.data());
Zachary Turnerc1564272016-11-16 21:15:24 +00002556 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2557}
2558
Zachary Turner0ac5f982016-11-08 04:12:42 +00002559void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2560 llvm::StringRef separator,
2561 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002562 uint32_t max_word_len) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00002563 int indent_size = max_word_len + separator.size() + 2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002564
2565 strm.IndentMore(indent_size);
2566
2567 StreamString text_strm;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002568 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2569 text_strm << separator << " " << help_text;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002570
2571 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2572
Zachary Turnerc1564272016-11-16 21:15:24 +00002573 llvm::StringRef text = text_strm.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002574
2575 uint32_t chars_left = max_columns;
2576
Davide Italianocf8a8292017-04-14 22:36:08 +00002577 auto nextWordLength = [](llvm::StringRef S) {
2578 size_t pos = S.find_first_of(' ');
2579 return pos == llvm::StringRef::npos ? S.size() : pos;
2580 };
2581
Zachary Turnerc1564272016-11-16 21:15:24 +00002582 while (!text.empty()) {
2583 if (text.front() == '\n' ||
Jim Inghama81bd7f2017-07-27 00:18:18 +00002584 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002585 strm.EOL();
2586 strm.Indent();
Zachary Turnerc1564272016-11-16 21:15:24 +00002587 chars_left = max_columns - indent_size;
2588 if (text.front() == '\n')
2589 text = text.drop_front();
2590 else
2591 text = text.ltrim(' ');
Kate Stoneb9c1b512016-09-06 20:57:50 +00002592 } else {
Zachary Turnerc1564272016-11-16 21:15:24 +00002593 strm.PutChar(text.front());
2594 --chars_left;
2595 text = text.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002596 }
2597 }
2598
2599 strm.EOL();
2600 strm.IndentLess(indent_size);
2601}
2602
2603void CommandInterpreter::FindCommandsForApropos(
Zachary Turner067d1db2016-11-16 21:45:04 +00002604 llvm::StringRef search_word, StringList &commands_found,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002605 StringList &commands_help, CommandObject::CommandMap &command_map) {
2606 CommandObject::CommandMap::const_iterator pos;
2607
2608 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
Zachary Turner067d1db2016-11-16 21:45:04 +00002609 llvm::StringRef command_name = pos->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002610 CommandObject *cmd_obj = pos->second.get();
2611
2612 const bool search_short_help = true;
2613 const bool search_long_help = false;
2614 const bool search_syntax = false;
2615 const bool search_options = false;
Zachary Turner067d1db2016-11-16 21:45:04 +00002616 if (command_name.contains_lower(search_word) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002617 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2618 search_long_help, search_syntax,
2619 search_options)) {
2620 commands_found.AppendString(cmd_obj->GetCommandName());
2621 commands_help.AppendString(cmd_obj->GetHelp());
2622 }
2623
2624 if (cmd_obj->IsMultiwordObject()) {
2625 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2626 FindCommandsForApropos(search_word, commands_found, commands_help,
2627 cmd_multiword->GetSubcommandDictionary());
2628 }
2629 }
2630}
2631
Zachary Turner067d1db2016-11-16 21:45:04 +00002632void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002633 StringList &commands_found,
2634 StringList &commands_help,
2635 bool search_builtin_commands,
2636 bool search_user_commands,
2637 bool search_alias_commands) {
2638 CommandObject::CommandMap::const_iterator pos;
2639
2640 if (search_builtin_commands)
2641 FindCommandsForApropos(search_word, commands_found, commands_help,
2642 m_command_dict);
2643
2644 if (search_user_commands)
2645 FindCommandsForApropos(search_word, commands_found, commands_help,
2646 m_user_dict);
2647
2648 if (search_alias_commands)
2649 FindCommandsForApropos(search_word, commands_found, commands_help,
2650 m_alias_dict);
2651}
2652
2653void CommandInterpreter::UpdateExecutionContext(
2654 ExecutionContext *override_context) {
2655 if (override_context != nullptr) {
2656 m_exe_ctx_ref = *override_context;
2657 } else {
2658 const bool adopt_selected = true;
2659 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2660 adopt_selected);
2661 }
2662}
2663
2664size_t CommandInterpreter::GetProcessOutput() {
2665 // The process has stuff waiting for stderr; get it and write it out to the
2666 // appropriate place.
2667 char stdio_buffer[1024];
2668 size_t len;
2669 size_t total_bytes = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002670 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002671 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2672 if (target_sp) {
2673 ProcessSP process_sp(target_sp->GetProcessSP());
2674 if (process_sp) {
2675 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2676 error)) > 0) {
2677 size_t bytes_written = len;
2678 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2679 total_bytes += len;
2680 }
2681 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2682 error)) > 0) {
2683 size_t bytes_written = len;
2684 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2685 total_bytes += len;
2686 }
2687 }
2688 }
2689 return total_bytes;
2690}
2691
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002692void CommandInterpreter::StartHandlingCommand() {
2693 auto idle_state = CommandHandlingState::eIdle;
2694 if (m_command_state.compare_exchange_strong(
2695 idle_state, CommandHandlingState::eInProgress))
2696 lldbassert(m_iohandler_nesting_level == 0);
2697 else
2698 lldbassert(m_iohandler_nesting_level > 0);
2699 ++m_iohandler_nesting_level;
2700}
2701
2702void CommandInterpreter::FinishHandlingCommand() {
2703 lldbassert(m_iohandler_nesting_level > 0);
2704 if (--m_iohandler_nesting_level == 0) {
2705 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2706 lldbassert(prev_state != CommandHandlingState::eIdle);
2707 }
2708}
2709
2710bool CommandInterpreter::InterruptCommand() {
2711 auto in_progress = CommandHandlingState::eInProgress;
2712 return m_command_state.compare_exchange_strong(
2713 in_progress, CommandHandlingState::eInterrupted);
2714}
2715
2716bool CommandInterpreter::WasInterrupted() const {
2717 bool was_interrupted =
2718 (m_command_state == CommandHandlingState::eInterrupted);
2719 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2720 return was_interrupted;
2721}
2722
2723void CommandInterpreter::PrintCommandOutput(Stream &stream,
2724 llvm::StringRef str) {
2725 // Split the output into lines and poll for interrupt requests
2726 const char *data = str.data();
2727 size_t size = str.size();
2728 while (size > 0 && !WasInterrupted()) {
2729 size_t chunk_size = 0;
2730 for (; chunk_size < size; ++chunk_size) {
2731 lldbassert(data[chunk_size] != '\0');
2732 if (data[chunk_size] == '\n') {
2733 ++chunk_size;
2734 break;
2735 }
2736 }
2737 chunk_size = stream.Write(data, chunk_size);
2738 lldbassert(size >= chunk_size);
2739 data += chunk_size;
2740 size -= chunk_size;
2741 }
2742 if (size > 0) {
2743 stream.Printf("\n... Interrupted.\n");
2744 }
2745}
2746
Stefan Granitzc678ed72018-10-05 16:49:47 +00002747bool CommandInterpreter::EchoCommandNonInteractive(
2748 llvm::StringRef line, const Flags &io_handler_flags) const {
2749 if (!io_handler_flags.Test(eHandleCommandFlagEchoCommand))
2750 return false;
2751
2752 llvm::StringRef command = line.trim();
2753 if (command.empty())
2754 return true;
2755
2756 if (command.front() == m_comment_char)
2757 return io_handler_flags.Test(eHandleCommandFlagEchoCommentCommand);
2758
2759 return true;
2760}
2761
Kate Stoneb9c1b512016-09-06 20:57:50 +00002762void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2763 std::string &line) {
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002764 // If we were interrupted, bail out...
2765 if (WasInterrupted())
2766 return;
2767
Kate Stoneb9c1b512016-09-06 20:57:50 +00002768 const bool is_interactive = io_handler.GetIsInteractive();
2769 if (is_interactive == false) {
2770 // When we are not interactive, don't execute blank lines. This will happen
2771 // sourcing a commands file. We don't want blank lines to repeat the
Adrian Prantl05097242018-04-30 16:49:04 +00002772 // previous command and cause any errors to occur (like redefining an
2773 // alias, get an error and stop parsing the commands file).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002774 if (line.empty())
2775 return;
2776
2777 // When using a non-interactive file handle (like when sourcing commands
Adrian Prantl05097242018-04-30 16:49:04 +00002778 // from a file) we need to echo the command out so we don't just see the
2779 // command output and no command...
Stefan Granitzc678ed72018-10-05 16:49:47 +00002780 if (EchoCommandNonInteractive(line, io_handler.GetFlags()))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002781 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2782 line.c_str());
2783 }
2784
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002785 StartHandlingCommand();
2786
Kate Stoneb9c1b512016-09-06 20:57:50 +00002787 lldb_private::CommandReturnObject result;
2788 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2789
2790 // Now emit the command output text from the command we just executed
2791 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2792 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2793 GetProcessOutput();
2794
2795 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002796 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002797 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002798 }
2799
2800 // Now emit the command error text from the command we just executed
2801 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002802 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002803 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002804 }
2805 }
2806
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002807 FinishHandlingCommand();
2808
Kate Stoneb9c1b512016-09-06 20:57:50 +00002809 switch (result.GetStatus()) {
2810 case eReturnStatusInvalid:
2811 case eReturnStatusSuccessFinishNoResult:
2812 case eReturnStatusSuccessFinishResult:
2813 case eReturnStatusStarted:
2814 break;
2815
2816 case eReturnStatusSuccessContinuingNoResult:
2817 case eReturnStatusSuccessContinuingResult:
2818 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2819 io_handler.SetIsDone(true);
2820 break;
2821
2822 case eReturnStatusFailed:
2823 m_num_errors++;
2824 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2825 io_handler.SetIsDone(true);
2826 break;
2827
2828 case eReturnStatusQuit:
2829 m_quit_requested = true;
2830 io_handler.SetIsDone(true);
2831 break;
2832 }
2833
2834 // Finally, if we're going to stop on crash, check that here:
2835 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2836 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2837 bool should_stop = false;
2838 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2839 if (target_sp) {
2840 ProcessSP process_sp(target_sp->GetProcessSP());
2841 if (process_sp) {
2842 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2843 StopReason reason = thread_sp->GetStopReason();
2844 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2845 reason == eStopReasonInstrumentation) &&
2846 !result.GetAbnormalStopWasExpected()) {
2847 should_stop = true;
2848 break;
2849 }
2850 }
2851 }
2852 }
2853 if (should_stop) {
2854 io_handler.SetIsDone(true);
2855 m_stopped_for_crash = true;
2856 }
2857 }
2858}
2859
2860bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2861 ExecutionContext exe_ctx(GetExecutionContext());
2862 Process *process = exe_ctx.GetProcessPtr();
2863
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002864 if (InterruptCommand())
2865 return true;
2866
Kate Stoneb9c1b512016-09-06 20:57:50 +00002867 if (process) {
2868 StateType state = process->GetState();
2869 if (StateIsRunningState(state)) {
2870 process->Halt();
2871 return true; // Don't do any updating when we are running
2872 }
2873 }
2874
2875 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2876 if (script_interpreter) {
2877 if (script_interpreter->Interrupt())
2878 return true;
2879 }
2880 return false;
2881}
2882
2883void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2884 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2885 void *baton) {
2886 Debugger &debugger = GetDebugger();
2887 IOHandlerSP io_handler_sp(
2888 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2889 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002890 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2891 llvm::StringRef(), // Continuation prompt
2892 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002893 debugger.GetUseColor(),
2894 0, // Don't show line numbers
2895 delegate)); // IOHandlerDelegate
2896
2897 if (io_handler_sp) {
2898 io_handler_sp->SetUserData(baton);
2899 if (asynchronously)
2900 debugger.PushIOHandler(io_handler_sp);
2901 else
2902 debugger.RunIOHandler(io_handler_sp);
2903 }
2904}
2905
2906void CommandInterpreter::GetPythonCommandsFromIOHandler(
2907 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2908 void *baton) {
2909 Debugger &debugger = GetDebugger();
2910 IOHandlerSP io_handler_sp(
2911 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2912 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002913 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2914 llvm::StringRef(), // Continuation prompt
2915 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002916 debugger.GetUseColor(),
2917 0, // Don't show line numbers
2918 delegate)); // IOHandlerDelegate
2919
2920 if (io_handler_sp) {
2921 io_handler_sp->SetUserData(baton);
2922 if (asynchronously)
2923 debugger.PushIOHandler(io_handler_sp);
2924 else
2925 debugger.RunIOHandler(io_handler_sp);
2926 }
2927}
2928
2929bool CommandInterpreter::IsActive() {
2930 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2931}
2932
2933lldb::IOHandlerSP
2934CommandInterpreter::GetIOHandler(bool force_create,
2935 CommandInterpreterRunOptions *options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002936 // Always re-create the IOHandlerEditline in case the input changed. The old
2937 // instance might have had a non-interactive input and now it does or vice
2938 // versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002939 if (force_create || !m_command_io_handler_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002940 // Always re-create the IOHandlerEditline in case the input changed. The
2941 // old instance might have had a non-interactive input and now it does or
2942 // vice versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002943 uint32_t flags = 0;
2944
2945 if (options) {
2946 if (options->m_stop_on_continue == eLazyBoolYes)
2947 flags |= eHandleCommandFlagStopOnContinue;
2948 if (options->m_stop_on_error == eLazyBoolYes)
2949 flags |= eHandleCommandFlagStopOnError;
2950 if (options->m_stop_on_crash == eLazyBoolYes)
2951 flags |= eHandleCommandFlagStopOnCrash;
2952 if (options->m_echo_commands != eLazyBoolNo)
2953 flags |= eHandleCommandFlagEchoCommand;
Stefan Granitzc678ed72018-10-05 16:49:47 +00002954 if (options->m_echo_comment_commands != eLazyBoolNo)
2955 flags |= eHandleCommandFlagEchoCommentCommand;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002956 if (options->m_print_results != eLazyBoolNo)
2957 flags |= eHandleCommandFlagPrintResult;
2958 } else {
2959 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2960 }
2961
2962 m_command_io_handler_sp.reset(new IOHandlerEditline(
2963 m_debugger, IOHandler::Type::CommandInterpreter,
2964 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2965 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002966 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002967 false, // Don't enable multiple line input, just single line commands
2968 m_debugger.GetUseColor(),
2969 0, // Don't show line numbers
2970 *this));
2971 }
2972 return m_command_io_handler_sp;
2973}
2974
2975void CommandInterpreter::RunCommandInterpreter(
2976 bool auto_handle_events, bool spawn_thread,
2977 CommandInterpreterRunOptions &options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002978 // Always re-create the command interpreter when we run it in case any file
2979 // handles have changed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002980 bool force_create = true;
2981 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2982 m_stopped_for_crash = false;
2983
2984 if (auto_handle_events)
2985 m_debugger.StartEventHandlerThread();
2986
2987 if (spawn_thread) {
2988 m_debugger.StartIOHandlerThread();
2989 } else {
2990 m_debugger.ExecuteIOHandlers();
2991
2992 if (auto_handle_events)
2993 m_debugger.StopEventHandlerThread();
2994 }
2995}
2996
2997CommandObject *
2998CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2999 CommandReturnObject &result) {
3000 std::string scratch_command(command_line); // working copy so we don't modify
3001 // command_line unless we succeed
3002 CommandObject *cmd_obj = nullptr;
3003 StreamString revised_command_line;
3004 bool wants_raw_input = false;
3005 size_t actual_cmd_name_len = 0;
3006 std::string next_word;
3007 StringList matches;
3008 bool done = false;
3009 while (!done) {
3010 char quote_char = '\0';
3011 std::string suffix;
3012 ExtractCommand(scratch_command, next_word, suffix, quote_char);
3013 if (cmd_obj == nullptr) {
3014 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003015 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00003016 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003017 bool is_real_command =
3018 (is_alias == false) ||
3019 (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
3020 if (!is_real_command) {
3021 matches.Clear();
3022 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003023 cmd_obj =
3024 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003025 revised_command_line.Printf("%s", alias_result.c_str());
3026 if (cmd_obj) {
3027 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00003028 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003029 }
3030 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003031 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00003032 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
3033 actual_cmd_name_len += cmd_name.size();
3034 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003035 wants_raw_input = cmd_obj->WantsRawCommandString();
3036 } else {
3037 revised_command_line.Printf("%s", next_word.c_str());
3038 }
3039 }
3040 } else {
3041 if (cmd_obj->IsMultiwordObject()) {
3042 CommandObject *sub_cmd_obj =
3043 cmd_obj->GetSubcommandObject(next_word.c_str());
3044 if (sub_cmd_obj) {
Adrian Prantl05097242018-04-30 16:49:04 +00003045 // The subcommand's name includes the parent command's name, so
3046 // restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00003047 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3048 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003049 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00003050 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003051 cmd_obj = sub_cmd_obj;
3052 wants_raw_input = cmd_obj->WantsRawCommandString();
3053 } else {
3054 if (quote_char)
3055 revised_command_line.Printf(" %c%s%s%c", quote_char,
3056 next_word.c_str(), suffix.c_str(),
3057 quote_char);
3058 else
3059 revised_command_line.Printf(" %s%s", next_word.c_str(),
3060 suffix.c_str());
3061 done = true;
3062 }
3063 } else {
3064 if (quote_char)
3065 revised_command_line.Printf(" %c%s%s%c", quote_char,
3066 next_word.c_str(), suffix.c_str(),
3067 quote_char);
3068 else
3069 revised_command_line.Printf(" %s%s", next_word.c_str(),
3070 suffix.c_str());
3071 done = true;
3072 }
3073 }
3074
3075 if (cmd_obj == nullptr) {
3076 const size_t num_matches = matches.GetSize();
3077 if (matches.GetSize() > 1) {
3078 StreamString error_msg;
3079 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3080 next_word.c_str());
3081
3082 for (uint32_t i = 0; i < num_matches; ++i) {
3083 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3084 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003085 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003086 } else {
3087 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003088 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003089 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3090 next_word.c_str());
3091 }
3092 result.SetStatus(eReturnStatusFailed);
3093 return nullptr;
3094 }
3095
3096 if (cmd_obj->IsMultiwordObject()) {
3097 if (!suffix.empty()) {
3098 result.AppendErrorWithFormat(
3099 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3100 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003101 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003102 next_word.empty() ? "" : next_word.c_str(),
3103 next_word.empty() ? " -- " : " ", suffix.c_str());
3104 result.SetStatus(eReturnStatusFailed);
3105 return nullptr;
3106 }
3107 } else {
3108 // If we found a normal command, we are done
3109 done = true;
3110 if (!suffix.empty()) {
3111 switch (suffix[0]) {
3112 case '/':
3113 // GDB format suffixes
3114 {
3115 Options *command_options = cmd_obj->GetOptions();
3116 if (command_options &&
3117 command_options->SupportsLongOption("gdb-format")) {
3118 std::string gdb_format_option("--gdb-format=");
3119 gdb_format_option += (suffix.c_str() + 1);
3120
Zachary Turnerc1564272016-11-16 21:15:24 +00003121 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003122 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3123 if (arg_terminator_idx != std::string::npos) {
3124 // Insert the gdb format option before the "--" that terminates
3125 // options
3126 gdb_format_option.append(1, ' ');
3127 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003128 revised_command_line.Clear();
3129 revised_command_line.PutCString(cmd);
3130 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003131 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3132
3133 if (wants_raw_input &&
3134 FindArgumentTerminator(cmd) == std::string::npos)
3135 revised_command_line.PutCString(" --");
3136 } else {
3137 result.AppendErrorWithFormat(
3138 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003139 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003140 result.SetStatus(eReturnStatusFailed);
3141 return nullptr;
3142 }
3143 }
3144 break;
3145
3146 default:
3147 result.AppendErrorWithFormat(
3148 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3149 result.SetStatus(eReturnStatusFailed);
3150 return nullptr;
3151 }
3152 }
3153 }
3154 if (scratch_command.empty())
3155 done = true;
3156 }
3157
3158 if (!scratch_command.empty())
3159 revised_command_line.Printf(" %s", scratch_command.c_str());
3160
3161 if (cmd_obj != NULL)
Zachary Turnerc1564272016-11-16 21:15:24 +00003162 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003163
3164 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003165}