blob: 564e6e917400806df76a59ba1a9856dd006303ae [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 }
433
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000434}
435
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436void CommandInterpreter::Clear() {
437 m_command_io_handler_sp.reset();
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000438
Kate Stoneb9c1b512016-09-06 20:57:50 +0000439 if (m_script_interpreter_sp)
440 m_script_interpreter_sp->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000441}
442
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
444 // This function has not yet been implemented.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000445
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446 // Look for any embedded script command
447 // If found,
448 // get interpreter object from the command dictionary,
449 // call execute_one_command on it,
450 // get the results as a string,
451 // substitute that string for current stuff.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000452
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453 return arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000454}
455
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456void CommandInterpreter::LoadCommandDictionary() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000457 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
458 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000459
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000461
Kate Stoneb9c1b512016-09-06 20:57:50 +0000462 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
463 m_command_dict["breakpoint"] =
464 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
465 m_command_dict["bugreport"] =
466 CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
467 m_command_dict["command"] =
468 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
469 m_command_dict["disassemble"] =
470 CommandObjectSP(new CommandObjectDisassemble(*this));
471 m_command_dict["expression"] =
472 CommandObjectSP(new CommandObjectExpression(*this));
473 m_command_dict["frame"] =
474 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
475 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
476 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
477 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
478 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
479 m_command_dict["platform"] =
480 CommandObjectSP(new CommandObjectPlatform(*this));
481 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
482 m_command_dict["process"] =
483 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
484 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
485 m_command_dict["register"] =
486 CommandObjectSP(new CommandObjectRegister(*this));
487 m_command_dict["script"] =
488 CommandObjectSP(new CommandObjectScript(*this, script_language));
489 m_command_dict["settings"] =
490 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
491 m_command_dict["source"] =
492 CommandObjectSP(new CommandObjectMultiwordSource(*this));
Davide Italiano24fff242018-04-13 18:02:39 +0000493 m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 m_command_dict["target"] =
495 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
496 m_command_dict["thread"] =
497 CommandObjectSP(new CommandObjectMultiwordThread(*this));
498 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
499 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
500 m_command_dict["watchpoint"] =
501 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
502 m_command_dict["language"] =
503 CommandObjectSP(new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000504
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505 const char *break_regexes[][2] = {
506 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
507 "breakpoint set --file '%1' --line %2"},
508 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
509 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
510 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
511 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
512 "breakpoint set --name '%1'"},
513 {"^(-.*)$", "breakpoint set %1"},
514 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
515 "breakpoint set --name '%2' --shlib '%1'"},
516 {"^\\&(.*[^[:space:]])[[:space:]]*$",
517 "breakpoint set --name '%1' --skip-prologue=0"},
518 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
519 "breakpoint set --name '%1'"}};
Kate Stone7428a182016-07-14 22:03:10 +0000520
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000522
Kate Stoneb9c1b512016-09-06 20:57:50 +0000523 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap(
524 new CommandObjectRegexCommand(
525 *this, "_regexp-break",
Raphael Isemann129fe892018-07-30 21:41:13 +0000526 "Set a breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000527 "\n"
528 "_regexp-break <filename>:<linenum>\n"
529 " main.c:12 // Break at line 12 of "
530 "main.c\n\n"
531 "_regexp-break <linenum>\n"
532 " 12 // Break at line 12 of current "
533 "file\n\n"
534 "_regexp-break 0x<address>\n"
535 " 0x1234000 // Break at address "
536 "0x1234000\n\n"
537 "_regexp-break <name>\n"
538 " main // Break in 'main' after the "
539 "prologue\n\n"
540 "_regexp-break &<name>\n"
541 " &main // Break at first instruction "
542 "in 'main'\n\n"
543 "_regexp-break <module>`<name>\n"
544 " libc.so`malloc // Break in 'malloc' from "
545 "'libc.so'\n\n"
546 "_regexp-break /<source-regex>/\n"
547 " /break here/ // Break on source lines in "
548 "current file\n"
549 " // containing text 'break "
550 "here'.\n",
551 2, CommandCompletions::eSymbolCompletion |
552 CommandCompletions::eSourceFileCompletion,
553 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000554
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 if (break_regex_cmd_ap.get()) {
556 bool success = true;
557 for (size_t i = 0; i < num_regexes; i++) {
558 success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0],
559 break_regexes[i][1]);
560 if (!success)
561 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000562 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563 success =
564 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Jim Inghamffba2292011-03-22 02:29:32 +0000565
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566 if (success) {
567 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
568 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
Jim Inghamca36cd12012-10-05 19:16:31 +0000569 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570 }
Jim Inghamca36cd12012-10-05 19:16:31 +0000571
Kate Stoneb9c1b512016-09-06 20:57:50 +0000572 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap(
573 new CommandObjectRegexCommand(
574 *this, "_regexp-tbreak",
Raphael Isemann129fe892018-07-30 21:41:13 +0000575 "Set a one-shot breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000576 "\n"
577 "_regexp-break <filename>:<linenum>\n"
578 " main.c:12 // Break at line 12 of "
579 "main.c\n\n"
580 "_regexp-break <linenum>\n"
581 " 12 // Break at line 12 of current "
582 "file\n\n"
583 "_regexp-break 0x<address>\n"
584 " 0x1234000 // Break at address "
585 "0x1234000\n\n"
586 "_regexp-break <name>\n"
587 " main // Break in 'main' after the "
588 "prologue\n\n"
589 "_regexp-break &<name>\n"
590 " &main // Break at first instruction "
591 "in 'main'\n\n"
592 "_regexp-break <module>`<name>\n"
593 " libc.so`malloc // Break in 'malloc' from "
594 "'libc.so'\n\n"
595 "_regexp-break /<source-regex>/\n"
596 " /break here/ // Break on source lines in "
597 "current file\n"
598 " // containing text 'break "
599 "here'.\n",
600 2, CommandCompletions::eSymbolCompletion |
601 CommandCompletions::eSourceFileCompletion,
602 false));
603
604 if (tbreak_regex_cmd_ap.get()) {
605 bool success = true;
606 for (size_t i = 0; i < num_regexes; i++) {
607 // If you add a resultant command string longer than 1024 characters be
608 // sure to increase the size of this buffer.
609 char buffer[1024];
610 int num_printed =
Frederic Riss49c9d8b2018-06-18 04:34:33 +0000611 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1");
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000612 lldbassert(num_printed < 1024);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613 UNUSED_IF_ASSERT_DISABLED(num_printed);
614 success =
615 tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer);
616 if (!success)
617 break;
Johnny Chen6d675242012-08-24 18:15:45 +0000618 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000619 success =
620 tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Kate Stone7428a182016-07-14 22:03:10 +0000621
Kate Stoneb9c1b512016-09-06 20:57:50 +0000622 if (success) {
623 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
624 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
625 tbreak_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000626 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627 }
Kate Stone7428a182016-07-14 22:03:10 +0000628
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap(
630 new CommandObjectRegexCommand(
631 *this, "_regexp-attach", "Attach to process by ID or name.",
632 "_regexp-attach <pid> | <process-name>", 2, 0, false));
633 if (attach_regex_cmd_ap.get()) {
634 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
635 "process attach --pid %1") &&
636 attach_regex_cmd_ap->AddRegexCommand(
637 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
638 // specified get passed to
639 // 'process attach'
640 attach_regex_cmd_ap->AddRegexCommand("^(.+)$",
641 "process attach --name '%1'") &&
642 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) {
643 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
644 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
645 attach_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000646 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000647 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000648
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap(
650 new CommandObjectRegexCommand(*this, "_regexp-down",
651 "Select a newer stack frame. Defaults to "
652 "moving one frame, a numeric argument can "
653 "specify an arbitrary number.",
654 "_regexp-down [<count>]", 2, 0, false));
655 if (down_regex_cmd_ap.get()) {
656 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
657 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
658 "frame select -r -%1")) {
659 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
660 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000661 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000662 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000663
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap(
665 new CommandObjectRegexCommand(
666 *this, "_regexp-up",
667 "Select an older stack frame. Defaults to moving one "
668 "frame, a numeric argument can specify an arbitrary number.",
669 "_regexp-up [<count>]", 2, 0, false));
670 if (up_regex_cmd_ap.get()) {
671 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
672 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
673 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
674 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000675 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000676 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000677
Kate Stoneb9c1b512016-09-06 20:57:50 +0000678 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap(
679 new CommandObjectRegexCommand(
680 *this, "_regexp-display",
681 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
682 "_regexp-display expression", 2, 0, false));
683 if (display_regex_cmd_ap.get()) {
684 if (display_regex_cmd_ap->AddRegexCommand(
685 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
686 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
687 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
688 display_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000689 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000690 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000691
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap(
693 new CommandObjectRegexCommand(
694 *this, "_regexp-undisplay", "Stop displaying expression at every "
695 "stop (specified by stop-hook index.)",
696 "_regexp-undisplay stop-hook-number", 2, 0, false));
697 if (undisplay_regex_cmd_ap.get()) {
698 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
699 "target stop-hook delete %1")) {
700 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
701 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
702 undisplay_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000703 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000704 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000705
Kate Stoneb9c1b512016-09-06 20:57:50 +0000706 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap(
707 new CommandObjectRegexCommand(
708 *this, "gdb-remote", "Connect to a process via remote GDB server. "
709 "If no host is specifed, localhost is assumed.",
710 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
711 if (connect_gdb_remote_cmd_ap.get()) {
712 if (connect_gdb_remote_cmd_ap->AddRegexCommand(
Chris Bieneman51978f52017-04-27 16:13:58 +0000713 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
714 "process connect --plugin gdb-remote connect://%1:%2") &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000715 connect_gdb_remote_cmd_ap->AddRegexCommand(
716 "^([[:digit:]]+)$",
717 "process connect --plugin gdb-remote connect://localhost:%1")) {
718 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
719 m_command_dict[command_sp->GetCommandName()] = command_sp;
Jason Molenda4cddfed2012-10-05 05:29:32 +0000720 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000721 }
Jason Molenda4cddfed2012-10-05 05:29:32 +0000722
Kate Stoneb9c1b512016-09-06 20:57:50 +0000723 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap(
724 new CommandObjectRegexCommand(
725 *this, "kdp-remote", "Connect to a process via remote KDP server. "
726 "If no UDP port is specified, port 41139 is "
727 "assumed.",
728 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
729 if (connect_kdp_remote_cmd_ap.get()) {
730 if (connect_kdp_remote_cmd_ap->AddRegexCommand(
731 "^([^:]+:[[:digit:]]+)$",
732 "process connect --plugin kdp-remote udp://%1") &&
733 connect_kdp_remote_cmd_ap->AddRegexCommand(
734 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
735 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
736 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Clayton6bade322013-02-01 23:33:03 +0000737 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738 }
Greg Clayton6bade322013-02-01 23:33:03 +0000739
Kate Stoneb9c1b512016-09-06 20:57:50 +0000740 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap(
741 new CommandObjectRegexCommand(
742 *this, "_regexp-bt",
743 "Show the current thread's call stack. Any numeric argument "
744 "displays at most that many "
745 "frames. The argument 'all' displays all threads.",
746 "bt [<digit> | all]", 2, 0, false));
747 if (bt_regex_cmd_ap.get()) {
748 // accept but don't document "bt -c <number>" -- before bt was a regex
Adrian Prantl05097242018-04-30 16:49:04 +0000749 // command if you wanted to backtrace three frames you would do "bt -c 3"
750 // but the intention is to have this emulate the gdb "bt" command and so
751 // now "bt 3" is the preferred form, in line with gdb.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$",
753 "thread backtrace -c %1") &&
754 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$",
755 "thread backtrace -c %1") &&
756 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
757 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) {
758 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
759 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Claytonef5651d2013-02-12 18:52:24 +0000760 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000761 }
Greg Claytonef5651d2013-02-12 18:52:24 +0000762
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap(
764 new CommandObjectRegexCommand(
765 *this, "_regexp-list",
766 "List relevant source code using one of several shorthand formats.",
767 "\n"
768 "_regexp-list <file>:<line> // List around specific file/line\n"
769 "_regexp-list <line> // List current file around specified "
770 "line\n"
771 "_regexp-list <function-name> // List specified function\n"
772 "_regexp-list 0x<address> // List around specified address\n"
773 "_regexp-list -[<count>] // List previous <count> lines\n"
774 "_regexp-list // List subsequent lines",
775 2, CommandCompletions::eSourceFileCompletion, false));
776 if (list_regex_cmd_ap.get()) {
777 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
778 "source list --line %1") &&
779 list_regex_cmd_ap->AddRegexCommand(
780 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
781 "]*$",
782 "source list --file '%1' --line %2") &&
783 list_regex_cmd_ap->AddRegexCommand(
784 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
785 "source list --address %1") &&
786 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$",
787 "source list --reverse") &&
788 list_regex_cmd_ap->AddRegexCommand(
789 "^-([[:digit:]]+)[[:space:]]*$",
790 "source list --reverse --count %1") &&
791 list_regex_cmd_ap->AddRegexCommand("^(.+)$",
792 "source list --name \"%1\"") &&
793 list_regex_cmd_ap->AddRegexCommand("^$", "source list")) {
794 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
795 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
Richard Mittonf86248d2013-09-12 02:20:34 +0000796 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 }
Richard Mittonf86248d2013-09-12 02:20:34 +0000798
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap(
800 new CommandObjectRegexCommand(
801 *this, "_regexp-env",
802 "Shorthand for viewing and setting environment variables.",
803 "\n"
804 "_regexp-env // Show enrivonment\n"
805 "_regexp-env <name>=<value> // Set an environment variable",
806 2, 0, false));
807 if (env_regex_cmd_ap.get()) {
808 if (env_regex_cmd_ap->AddRegexCommand("^$",
809 "settings show target.env-vars") &&
810 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
811 "settings set target.env-vars %1")) {
812 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
813 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
814 }
815 }
816
817 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap(
818 new CommandObjectRegexCommand(
819 *this, "_regexp-jump", "Set the program counter to a new address.",
820 "\n"
821 "_regexp-jump <line>\n"
822 "_regexp-jump +<line-offset> | -<line-offset>\n"
823 "_regexp-jump <file>:<line>\n"
824 "_regexp-jump *<addr>\n",
825 2, 0, false));
826 if (jump_regex_cmd_ap.get()) {
827 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$",
828 "thread jump --addr %1") &&
829 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
830 "thread jump --line %1") &&
831 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$",
832 "thread jump --file %1 --line %2") &&
833 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$",
834 "thread jump --by %1")) {
835 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
836 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
837 }
838 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000839}
840
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841int CommandInterpreter::GetCommandNamesMatchingPartialString(
Raphael Isemann7f888292018-09-13 21:26:00 +0000842 const char *cmd_str, bool include_aliases, StringList &matches,
843 StringList &descriptions) {
844 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches,
845 &descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000846
Kate Stoneb9c1b512016-09-06 20:57:50 +0000847 if (include_aliases) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000848 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches,
849 &descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000851
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852 return matches.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000853}
854
Raphael Isemann7f888292018-09-13 21:26:00 +0000855CommandObjectSP
856CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases,
857 bool exact, StringList *matches,
858 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000859 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000860
Zachary Turnera4496982016-10-05 21:14:38 +0000861 std::string cmd = cmd_str;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000862
Kate Stoneb9c1b512016-09-06 20:57:50 +0000863 if (HasCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000864 auto pos = m_command_dict.find(cmd);
Greg Claytonb5472782015-01-09 19:08:20 +0000865 if (pos != m_command_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866 command_sp = pos->second;
867 }
868
869 if (include_aliases && HasAliases()) {
870 auto alias_pos = m_alias_dict.find(cmd);
871 if (alias_pos != m_alias_dict.end())
872 command_sp = alias_pos->second;
873 }
874
875 if (HasUserCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000876 auto pos = m_user_dict.find(cmd);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000877 if (pos != m_user_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000878 command_sp = pos->second;
879 }
880
881 if (!exact && !command_sp) {
882 // We will only get into here if we didn't find any exact matches.
883
884 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
885
886 StringList local_matches;
887 if (matches == nullptr)
888 matches = &local_matches;
889
890 unsigned int num_cmd_matches = 0;
891 unsigned int num_alias_matches = 0;
892 unsigned int num_user_matches = 0;
893
894 // Look through the command dictionaries one by one, and if we get only one
Adrian Prantl05097242018-04-30 16:49:04 +0000895 // match from any of them in toto, then return that, otherwise return an
896 // empty CommandObjectSP and the list of matches.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000897
898 if (HasCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000899 num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str,
900 *matches, descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000901 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000902
903 if (num_cmd_matches == 1) {
904 cmd.assign(matches->GetStringAtIndex(0));
Zachary Turnera4496982016-10-05 21:14:38 +0000905 auto pos = m_command_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000906 if (pos != m_command_dict.end())
907 real_match_sp = pos->second;
908 }
909
910 if (include_aliases && HasAliases()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000911 num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str,
912 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000913 }
914
915 if (num_alias_matches == 1) {
916 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
917 auto alias_pos = m_alias_dict.find(cmd);
918 if (alias_pos != m_alias_dict.end())
919 alias_match_sp = alias_pos->second;
920 }
921
922 if (HasUserCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000923 num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str,
924 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000925 }
926
927 if (num_user_matches == 1) {
928 cmd.assign(
929 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
930
Zachary Turnera4496982016-10-05 21:14:38 +0000931 auto pos = m_user_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000932 if (pos != m_user_dict.end())
933 user_match_sp = pos->second;
934 }
935
936 // If we got exactly one match, return that, otherwise return the match
937 // list.
938
939 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
940 if (num_cmd_matches)
941 return real_match_sp;
942 else if (num_alias_matches)
943 return alias_match_sp;
944 else
945 return user_match_sp;
946 }
947 } else if (matches && command_sp) {
Zachary Turnera4496982016-10-05 21:14:38 +0000948 matches->AppendString(cmd_str);
Raphael Isemann7f888292018-09-13 21:26:00 +0000949 if (descriptions)
950 descriptions->AppendString(command_sp->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000951 }
952
953 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000954}
955
Zachary Turnera4496982016-10-05 21:14:38 +0000956bool CommandInterpreter::AddCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957 const lldb::CommandObjectSP &cmd_sp,
958 bool can_replace) {
959 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000960 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
961 "tried to add a CommandObject from a different interpreter");
Kate Stonea487aa42015-01-15 00:52:41 +0000962
Zachary Turnera4496982016-10-05 21:14:38 +0000963 if (name.empty())
964 return false;
965
966 std::string name_sstr(name);
967 auto name_iter = m_command_dict.find(name_sstr);
968 if (name_iter != m_command_dict.end()) {
969 if (!can_replace || !name_iter->second->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000970 return false;
Zachary Turnera4496982016-10-05 21:14:38 +0000971 name_iter->second = cmd_sp;
972 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000973 m_command_dict[name_sstr] = cmd_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 }
Zachary Turnera4496982016-10-05 21:14:38 +0000975 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000976}
977
Zachary Turnera483f572016-10-05 21:14:49 +0000978bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000979 const lldb::CommandObjectSP &cmd_sp,
980 bool can_replace) {
981 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000982 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
983 "tried to add a CommandObject from a different interpreter");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000984
Kate Stoneb9c1b512016-09-06 20:57:50 +0000985 if (!name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000986 // do not allow replacement of internal commands
Zachary Turnera483f572016-10-05 21:14:49 +0000987 if (CommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000988 if (can_replace == false)
989 return false;
990 if (m_command_dict[name]->IsRemovable() == false)
Greg Clayton5a314712011-10-14 07:41:33 +0000991 return false;
992 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000993
Zachary Turnera483f572016-10-05 21:14:49 +0000994 if (UserCommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000995 if (can_replace == false)
996 return false;
997 if (m_user_dict[name]->IsRemovable() == false)
998 return false;
Caroline Tice844d2302010-12-09 22:52:49 +0000999 }
1000
Kate Stoneb9c1b512016-09-06 20:57:50 +00001001 m_user_dict[name] = cmd_sp;
1002 return true;
1003 }
1004 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001005}
1006
Zachary Turnera4496982016-10-05 21:14:38 +00001007CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
1008 bool include_aliases) const {
1009 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +00001010 // it's a multi-word command.
1011 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001012
Zachary Turnera4496982016-10-05 21:14:38 +00001013 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001014 return ret_val;
1015
1016 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +00001017 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 else {
1019 // We have a multi-word command (seemingly), so we need to do more work.
1020 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +00001021 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001022 include_aliases, true, nullptr);
1023 if (cmd_obj_sp.get() != nullptr) {
Adrian Prantl05097242018-04-30 16:49:04 +00001024 // Loop through the rest of the words in the command (everything passed
1025 // in was supposed to be part of a command name), and find the
1026 // appropriate sub-command SP for each command word....
Kate Stoneb9c1b512016-09-06 20:57:50 +00001027 size_t end = cmd_words.GetArgumentCount();
1028 for (size_t j = 1; j < end; ++j) {
1029 if (cmd_obj_sp->IsMultiwordObject()) {
1030 cmd_obj_sp =
1031 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
1032 if (cmd_obj_sp.get() == nullptr)
1033 // The sub-command name was invalid. Fail and return the empty
1034 // 'ret_val'.
1035 return ret_val;
1036 } else
1037 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +00001038 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001039 return ret_val;
1040 }
1041 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +00001042 // command objects for them. Assign the last object retrieved to
1043 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001044 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001045 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001046 }
1047 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001048}
1049
Raphael Isemann7f888292018-09-13 21:26:00 +00001050CommandObject *
1051CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
1052 StringList *matches,
1053 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001054 CommandObject *command_obj =
Raphael Isemann7f888292018-09-13 21:26:00 +00001055 GetCommandSP(cmd_str, false, true, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001056
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 // If we didn't find an exact match to the command string in the commands,
Adrian Prantl05097242018-04-30 16:49:04 +00001058 // look in the aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059
1060 if (command_obj)
1061 return command_obj;
1062
Raphael Isemann7f888292018-09-13 21:26:00 +00001063 command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001064
1065 if (command_obj)
1066 return command_obj;
1067
1068 // If there wasn't an exact match then look for an inexact one in just the
1069 // commands
Zachary Turnera4496982016-10-05 21:14:38 +00001070 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001071
1072 // Finally, if there wasn't an inexact match among the commands, look for an
Adrian Prantl05097242018-04-30 16:49:04 +00001073 // inexact match in both the commands and aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001074
1075 if (command_obj) {
1076 if (matches)
1077 matches->AppendString(command_obj->GetCommandName());
Raphael Isemann7f888292018-09-13 21:26:00 +00001078 if (descriptions)
1079 descriptions->AppendString(command_obj->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 return command_obj;
1081 }
1082
Raphael Isemann7f888292018-09-13 21:26:00 +00001083 return GetCommandSP(cmd_str, true, false, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001084}
1085
Zachary Turnera483f572016-10-05 21:14:49 +00001086bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001087 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001088}
1089
Zachary Turnera483f572016-10-05 21:14:49 +00001090bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1091 std::string &full_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001092 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1093 if (exact_match) {
1094 full_name.assign(cmd);
1095 return exact_match;
1096 } else {
1097 StringList matches;
1098 size_t num_alias_matches;
1099 num_alias_matches =
1100 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1101 if (num_alias_matches == 1) {
1102 // Make sure this isn't shadowing a command in the regular command space:
1103 StringList regular_matches;
1104 const bool include_aliases = false;
1105 const bool exact = false;
1106 CommandObjectSP cmd_obj_sp(
1107 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1108 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1109 return false;
1110 else {
1111 full_name.assign(matches.GetStringAtIndex(0));
1112 return true;
1113 }
1114 } else
1115 return false;
1116 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001117}
1118
Zachary Turnera483f572016-10-05 21:14:49 +00001119bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001120 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001121}
1122
Zachary Turnera483f572016-10-05 21:14:49 +00001123bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001125}
1126
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127CommandAlias *
Zachary Turnera483f572016-10-05 21:14:49 +00001128CommandInterpreter::AddAlias(llvm::StringRef alias_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001129 lldb::CommandObjectSP &command_obj_sp,
Zachary Turnera483f572016-10-05 21:14:49 +00001130 llvm::StringRef args_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001131 if (command_obj_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001132 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1133 "tried to add a CommandObject from a different interpreter");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001134
1135 std::unique_ptr<CommandAlias> command_alias_up(
1136 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1137
1138 if (command_alias_up && command_alias_up->IsValid()) {
1139 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1140 return command_alias_up.release();
1141 }
1142
1143 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001144}
1145
Zachary Turnera483f572016-10-05 21:14:49 +00001146bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001147 auto pos = m_alias_dict.find(alias_name);
1148 if (pos != m_alias_dict.end()) {
1149 m_alias_dict.erase(pos);
1150 return true;
1151 }
1152 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001153}
1154
Zachary Turnera483f572016-10-05 21:14:49 +00001155bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001156 auto pos = m_command_dict.find(cmd);
1157 if (pos != m_command_dict.end()) {
1158 if (pos->second->IsRemovable()) {
1159 // Only regular expression objects or python commands are removable
1160 m_command_dict.erase(pos);
1161 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001162 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163 }
1164 return false;
1165}
Zachary Turnera483f572016-10-05 21:14:49 +00001166bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001167 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1168 if (pos != m_user_dict.end()) {
1169 m_user_dict.erase(pos);
1170 return true;
1171 }
1172 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001173}
1174
Kate Stoneb9c1b512016-09-06 20:57:50 +00001175void CommandInterpreter::GetHelp(CommandReturnObject &result,
1176 uint32_t cmd_types) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001177 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1178 if (!help_prologue.empty()) {
1179 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1180 help_prologue);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001181 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001182
Kate Stoneb9c1b512016-09-06 20:57:50 +00001183 CommandObject::CommandMap::const_iterator pos;
1184 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001185
Kate Stoneb9c1b512016-09-06 20:57:50 +00001186 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1187 result.AppendMessage("Debugger commands:");
1188 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001189
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1191 if (!(cmd_types & eCommandTypesHidden) &&
1192 (pos->first.compare(0, 1, "_") == 0))
1193 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001194
Zachary Turner0ac5f982016-11-08 04:12:42 +00001195 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1196 pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001197 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001198 result.AppendMessage("");
1199 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001200
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201 if (!m_alias_dict.empty() &&
1202 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1203 result.AppendMessageWithFormat(
1204 "Current command abbreviations "
1205 "(type '%shelp command alias' for more info):\n",
1206 GetCommandPrefix());
1207 result.AppendMessage("");
1208 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001209
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1211 ++alias_pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001212 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001214 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001215 result.AppendMessage("");
1216 }
Greg Clayton14a35512011-09-11 00:01:44 +00001217
Kate Stoneb9c1b512016-09-06 20:57:50 +00001218 if (!m_user_dict.empty() &&
1219 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1220 result.AppendMessage("Current user-defined commands:");
1221 result.AppendMessage("");
1222 max_len = FindLongestCommandWord(m_user_dict);
1223 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001224 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1225 pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001226 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001227 result.AppendMessage("");
1228 }
Greg Clayton14a35512011-09-11 00:01:44 +00001229
Kate Stoneb9c1b512016-09-06 20:57:50 +00001230 result.AppendMessageWithFormat(
1231 "For more information on any command, type '%shelp <command-name>'.\n",
1232 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001233}
1234
Zachary Turnera01bccd2016-10-05 21:14:56 +00001235CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1236 llvm::StringRef &command_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001237 // This function finds the final, lowest-level, alias-resolved command object
Adrian Prantl05097242018-04-30 16:49:04 +00001238 // whose 'Execute' function will eventually be invoked by the given command
1239 // line.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001240
1241 CommandObject *cmd_obj = nullptr;
1242 size_t start = command_string.find_first_not_of(k_white_space);
1243 size_t end = 0;
1244 bool done = false;
1245 while (!done) {
1246 if (start != std::string::npos) {
1247 // Get the next word from command_string.
1248 end = command_string.find_first_of(k_white_space, start);
1249 if (end == std::string::npos)
1250 end = command_string.size();
1251 std::string cmd_word = command_string.substr(start, end - start);
1252
1253 if (cmd_obj == nullptr)
1254 // Since cmd_obj is NULL we are on our first time through this loop.
Zachary Turnera01bccd2016-10-05 21:14:56 +00001255 // Check to see if cmd_word is a valid command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001256 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257 else if (cmd_obj->IsMultiwordObject()) {
1258 // Our current object is a multi-word object; see if the cmd_word is a
1259 // valid sub-command for our object.
1260 CommandObject *sub_cmd_obj =
1261 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1262 if (sub_cmd_obj)
1263 cmd_obj = sub_cmd_obj;
1264 else // cmd_word was not a valid sub-command word, so we are done
1265 done = true;
1266 } else
1267 // We have a cmd_obj and it is not a multi-word object, so we are done.
1268 done = true;
1269
1270 // If we didn't find a valid command object, or our command object is not
Zachary Turnera01bccd2016-10-05 21:14:56 +00001271 // a multi-word object, or we are at the end of the command_string, then
1272 // we are done. Otherwise, find the start of the next word.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001273
1274 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1275 end >= command_string.size())
1276 done = true;
1277 else
1278 start = command_string.find_first_not_of(k_white_space, end);
1279 } else
1280 // Unable to find any more words.
1281 done = true;
1282 }
1283
Zachary Turnera01bccd2016-10-05 21:14:56 +00001284 command_string = command_string.substr(end);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001285 return cmd_obj;
1286}
1287
1288static const char *k_valid_command_chars =
1289 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1290static void StripLeadingSpaces(std::string &s) {
1291 if (!s.empty()) {
1292 size_t pos = s.find_first_not_of(k_white_space);
1293 if (pos == std::string::npos)
1294 s.clear();
1295 else if (pos == 0)
1296 return;
1297 s.erase(0, pos);
1298 }
1299}
1300
1301static size_t FindArgumentTerminator(const std::string &s) {
1302 const size_t s_len = s.size();
1303 size_t offset = 0;
1304 while (offset < s_len) {
1305 size_t pos = s.find("--", offset);
1306 if (pos == std::string::npos)
1307 break;
1308 if (pos > 0) {
1309 if (isspace(s[pos - 1])) {
Adrian Prantl05097242018-04-30 16:49:04 +00001310 // Check if the string ends "\s--" (where \s is a space character) or
1311 // if we have "\s--\s".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001312 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1313 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001314 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001315 }
1316 }
1317 offset = pos + 2;
1318 }
1319 return std::string::npos;
1320}
1321
1322static bool ExtractCommand(std::string &command_string, std::string &command,
1323 std::string &suffix, char &quote_char) {
1324 command.clear();
1325 suffix.clear();
1326 StripLeadingSpaces(command_string);
1327
1328 bool result = false;
1329 quote_char = '\0';
1330
1331 if (!command_string.empty()) {
1332 const char first_char = command_string[0];
1333 if (first_char == '\'' || first_char == '"') {
1334 quote_char = first_char;
1335 const size_t end_quote_pos = command_string.find(quote_char, 1);
1336 if (end_quote_pos == std::string::npos) {
1337 command.swap(command_string);
1338 command_string.erase();
1339 } else {
1340 command.assign(command_string, 1, end_quote_pos - 1);
1341 if (end_quote_pos + 1 < command_string.size())
1342 command_string.erase(0, command_string.find_first_not_of(
1343 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001344 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001345 command_string.erase();
1346 }
1347 } else {
1348 const size_t first_space_pos =
1349 command_string.find_first_of(k_white_space);
1350 if (first_space_pos == std::string::npos) {
1351 command.swap(command_string);
1352 command_string.erase();
1353 } else {
1354 command.assign(command_string, 0, first_space_pos);
1355 command_string.erase(0, command_string.find_first_not_of(
1356 k_white_space, first_space_pos));
1357 }
1358 }
1359 result = true;
1360 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001361
Kate Stoneb9c1b512016-09-06 20:57:50 +00001362 if (!command.empty()) {
1363 // actual commands can't start with '-' or '_'
1364 if (command[0] != '-' && command[0] != '_') {
1365 size_t pos = command.find_first_not_of(k_valid_command_chars);
1366 if (pos > 0 && pos != std::string::npos) {
1367 suffix.assign(command.begin() + pos, command.end());
1368 command.erase(pos);
1369 }
1370 }
1371 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001372
Kate Stoneb9c1b512016-09-06 20:57:50 +00001373 return result;
1374}
1375
1376CommandObject *CommandInterpreter::BuildAliasResult(
Zachary Turnera483f572016-10-05 21:14:49 +00001377 llvm::StringRef alias_name, std::string &raw_input_string,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001378 std::string &alias_result, CommandReturnObject &result) {
1379 CommandObject *alias_cmd_obj = nullptr;
1380 Args cmd_args(raw_input_string);
1381 alias_cmd_obj = GetCommandObject(alias_name);
1382 StreamString result_str;
1383
Zachary Turner5c28c662016-10-03 23:20:36 +00001384 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1385 alias_result.clear();
1386 return alias_cmd_obj;
1387 }
1388 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1389 ((CommandAlias *)alias_cmd_obj)->Desugar();
1390 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1391 alias_cmd_obj = desugared.first.get();
1392 std::string alias_name_str = alias_name;
1393 if ((cmd_args.GetArgumentCount() == 0) ||
1394 (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0))
1395 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001396
Zachary Turnera4496982016-10-05 21:14:38 +00001397 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001398
Zachary Turner5c28c662016-10-03 23:20:36 +00001399 if (!option_arg_vector_sp.get()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001400 alias_result = result_str.GetString();
Zachary Turner5c28c662016-10-03 23:20:36 +00001401 return alias_cmd_obj;
1402 }
1403 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001404
Zachary Turner5c28c662016-10-03 23:20:36 +00001405 int value_type;
1406 std::string option;
1407 std::string value;
1408 for (const auto &entry : *option_arg_vector) {
1409 std::tie(option, value_type, value) = entry;
1410 if (option == "<argument>") {
1411 result_str.Printf(" %s", value.c_str());
1412 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001413 }
1414
Zachary Turner5c28c662016-10-03 23:20:36 +00001415 result_str.Printf(" %s", option.c_str());
1416 if (value_type == OptionParser::eNoArgument)
1417 continue;
1418
1419 if (value_type != OptionParser::eOptionalArgument)
1420 result_str.Printf(" ");
1421 int index = GetOptionArgumentPosition(value.c_str());
1422 if (index == 0)
1423 result_str.Printf("%s", value.c_str());
1424 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1425
1426 result.AppendErrorWithFormat("Not enough arguments provided; you "
1427 "need at least %d arguments to use "
1428 "this alias.\n",
1429 index);
1430 result.SetStatus(eReturnStatusFailed);
1431 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001432 } else {
1433 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1434 if (strpos != std::string::npos)
1435 raw_input_string = raw_input_string.erase(
1436 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1437 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001438 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001439 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001440
Zachary Turnerc1564272016-11-16 21:15:24 +00001441 alias_result = result_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001442 return alias_cmd_obj;
1443}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001444
Zachary Turner97206d52017-05-12 04:51:55 +00001445Status CommandInterpreter::PreprocessCommand(std::string &command) {
Adrian Prantl05097242018-04-30 16:49:04 +00001446 // The command preprocessor needs to do things to the command line before any
1447 // parsing of arguments or anything else is done. The only current stuff that
1448 // gets preprocessed is anything enclosed in backtick ('`') characters is
1449 // evaluated as an expression and the result of the expression must be a
1450 // scalar that can be substituted into the command. An example would be:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001451 // (lldb) memory read `$rsp + 20`
Zachary Turner97206d52017-05-12 04:51:55 +00001452 Status error; // Status for any expressions that might not evaluate
Kate Stoneb9c1b512016-09-06 20:57:50 +00001453 size_t start_backtick;
1454 size_t pos = 0;
1455 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1456 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
Adrian Prantl05097242018-04-30 16:49:04 +00001457 // The backtick was preceded by a '\' character, remove the slash and
1458 // don't treat the backtick as the start of an expression
Kate Stoneb9c1b512016-09-06 20:57:50 +00001459 command.erase(start_backtick - 1, 1);
1460 // No need to add one to start_backtick since we just deleted a char
1461 pos = start_backtick;
1462 } else {
1463 const size_t expr_content_start = start_backtick + 1;
1464 const size_t end_backtick = command.find('`', expr_content_start);
1465 if (end_backtick == std::string::npos)
1466 return error;
1467 else if (end_backtick == expr_content_start) {
1468 // Empty expression (two backticks in a row)
1469 command.erase(start_backtick, 2);
1470 } else {
1471 std::string expr_str(command, expr_content_start,
1472 end_backtick - expr_content_start);
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001473
Kate Stoneb9c1b512016-09-06 20:57:50 +00001474 ExecutionContext exe_ctx(GetExecutionContext());
1475 Target *target = exe_ctx.GetTargetPtr();
1476 // Get a dummy target to allow for calculator mode while processing
Adrian Prantl05097242018-04-30 16:49:04 +00001477 // backticks. This also helps break the infinite loop caused when
1478 // target is null.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001479 if (!target)
1480 target = m_debugger.GetDummyTarget();
1481 if (target) {
1482 ValueObjectSP expr_result_valobj_sp;
1483
1484 EvaluateExpressionOptions options;
1485 options.SetCoerceToId(false);
1486 options.SetUnwindOnError(true);
1487 options.SetIgnoreBreakpoints(true);
1488 options.SetKeepInMemory(false);
1489 options.SetTryAllThreads(true);
Pavel Labath43d35412016-12-06 11:24:51 +00001490 options.SetTimeout(llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001491
1492 ExpressionResults expr_result = target->EvaluateExpression(
1493 expr_str.c_str(), exe_ctx.GetFramePtr(), expr_result_valobj_sp,
1494 options);
1495
1496 if (expr_result == eExpressionCompleted) {
1497 Scalar scalar;
1498 if (expr_result_valobj_sp)
1499 expr_result_valobj_sp =
1500 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1501 expr_result_valobj_sp->GetDynamicValueType(), true);
1502 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1503 command.erase(start_backtick, end_backtick - start_backtick + 1);
1504 StreamString value_strm;
1505 const bool show_type = false;
1506 scalar.GetValue(&value_strm, show_type);
1507 size_t value_string_size = value_strm.GetSize();
1508 if (value_string_size) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001509 command.insert(start_backtick, value_strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001510 pos = start_backtick + value_string_size;
1511 continue;
1512 } else {
1513 error.SetErrorStringWithFormat("expression value didn't result "
1514 "in a scalar value for the "
1515 "expression '%s'",
1516 expr_str.c_str());
1517 }
1518 } else {
1519 error.SetErrorStringWithFormat("expression value didn't result "
1520 "in a scalar value for the "
1521 "expression '%s'",
1522 expr_str.c_str());
1523 }
1524 } else {
1525 if (expr_result_valobj_sp)
1526 error = expr_result_valobj_sp->GetError();
1527 if (error.Success()) {
1528
1529 switch (expr_result) {
1530 case eExpressionSetupError:
1531 error.SetErrorStringWithFormat(
1532 "expression setup error for the expression '%s'",
1533 expr_str.c_str());
1534 break;
1535 case eExpressionParseError:
1536 error.SetErrorStringWithFormat(
1537 "expression parse error for the expression '%s'",
1538 expr_str.c_str());
1539 break;
1540 case eExpressionResultUnavailable:
1541 error.SetErrorStringWithFormat(
1542 "expression error fetching result for the expression '%s'",
1543 expr_str.c_str());
1544 break;
1545 case eExpressionCompleted:
1546 break;
1547 case eExpressionDiscarded:
1548 error.SetErrorStringWithFormat(
1549 "expression discarded for the expression '%s'",
1550 expr_str.c_str());
1551 break;
1552 case eExpressionInterrupted:
1553 error.SetErrorStringWithFormat(
1554 "expression interrupted for the expression '%s'",
1555 expr_str.c_str());
1556 break;
1557 case eExpressionHitBreakpoint:
1558 error.SetErrorStringWithFormat(
1559 "expression hit breakpoint for the expression '%s'",
1560 expr_str.c_str());
1561 break;
1562 case eExpressionTimedOut:
1563 error.SetErrorStringWithFormat(
1564 "expression timed out for the expression '%s'",
1565 expr_str.c_str());
1566 break;
1567 case eExpressionStoppedForDebug:
1568 error.SetErrorStringWithFormat("expression stop at entry point "
1569 "for debugging for the "
1570 "expression '%s'",
1571 expr_str.c_str());
1572 break;
1573 }
1574 }
1575 }
1576 }
1577 }
1578 if (error.Fail())
1579 break;
1580 }
1581 }
1582 return error;
1583}
1584
1585bool CommandInterpreter::HandleCommand(const char *command_line,
1586 LazyBool lazy_add_to_history,
1587 CommandReturnObject &result,
1588 ExecutionContext *override_context,
1589 bool repeat_on_empty_command,
1590 bool no_context_switching)
1591
1592{
1593
1594 std::string command_string(command_line);
1595 std::string original_command_string(command_line);
1596
1597 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
Jim Ingham8f7db522016-12-15 00:30:30 +00001598 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
Sean Callanan237c3ed2016-12-14 21:31:31 +00001599 command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001600
1601 if (log)
1602 log->Printf("Processing command: %s", command_line);
1603
Pavel Labathf9d16472017-05-15 13:02:37 +00001604 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1605 Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001606
1607 if (!no_context_switching)
1608 UpdateExecutionContext(override_context);
1609
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001610 if (WasInterrupted()) {
1611 result.AppendError("interrupted");
1612 result.SetStatus(eReturnStatusFailed);
1613 return false;
1614 }
1615
Kate Stoneb9c1b512016-09-06 20:57:50 +00001616 bool add_to_history;
1617 if (lazy_add_to_history == eLazyBoolCalculate)
1618 add_to_history = (m_command_source_depth == 0);
1619 else
1620 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1621
1622 bool empty_command = false;
1623 bool comment_command = false;
1624 if (command_string.empty())
1625 empty_command = true;
1626 else {
1627 const char *k_space_characters = "\t\n\v\f\r ";
1628
1629 size_t non_space = command_string.find_first_not_of(k_space_characters);
Adrian Prantl05097242018-04-30 16:49:04 +00001630 // Check for empty line or comment line (lines whose first non-space
1631 // character is the comment character for this interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001632 if (non_space == std::string::npos)
1633 empty_command = true;
1634 else if (command_string[non_space] == m_comment_char)
1635 comment_command = true;
1636 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001637 llvm::StringRef search_str(command_string);
1638 search_str = search_str.drop_front(non_space);
1639 if (auto hist_str = m_command_history.FindString(search_str)) {
1640 add_to_history = false;
1641 command_string = *hist_str;
1642 original_command_string = *hist_str;
1643 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001644 result.AppendErrorWithFormat("Could not find entry: %s in history",
1645 command_string.c_str());
1646 result.SetStatus(eReturnStatusFailed);
1647 return false;
1648 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001649 }
1650 }
1651
1652 if (empty_command) {
1653 if (repeat_on_empty_command) {
1654 if (m_command_history.IsEmpty()) {
1655 result.AppendError("empty command");
1656 result.SetStatus(eReturnStatusFailed);
1657 return false;
1658 } else {
1659 command_line = m_repeat_command.c_str();
1660 command_string = command_line;
1661 original_command_string = command_line;
1662 if (m_repeat_command.empty()) {
1663 result.AppendErrorWithFormat("No auto repeat.\n");
1664 result.SetStatus(eReturnStatusFailed);
1665 return false;
1666 }
1667 }
1668 add_to_history = false;
1669 } else {
1670 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1671 return true;
1672 }
1673 } else if (comment_command) {
1674 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1675 return true;
1676 }
1677
Zachary Turner97206d52017-05-12 04:51:55 +00001678 Status error(PreprocessCommand(command_string));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001679
1680 if (error.Fail()) {
1681 result.AppendError(error.AsCString());
1682 result.SetStatus(eReturnStatusFailed);
1683 return false;
1684 }
1685
1686 // Phase 1.
1687
1688 // Before we do ANY kind of argument processing, we need to figure out what
1689 // the real/final command object is for the specified command. This gets
1690 // complicated by the fact that the user could have specified an alias, and,
1691 // in translating the alias, there may also be command options and/or even
1692 // data (including raw text strings) that need to be found and inserted into
1693 // the command line as part of the translation. So this first step is plain
1694 // look-up and replacement, resulting in:
1695 // 1. the command object whose Execute method will actually be called
1696 // 2. a revised command string, with all substitutions and replacements
1697 // taken care of
1698 // From 1 above, we can determine whether the Execute function wants raw
1699 // input or not.
1700
1701 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1702
1703 // Although the user may have abbreviated the command, the command_string now
Adrian Prantl05097242018-04-30 16:49:04 +00001704 // has the command expanded to the full name. For example, if the input was
1705 // "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001706 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001707 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1708 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001709 log->Printf("HandleCommand, (revised) command_string: '%s'",
1710 command_string.c_str());
1711 const bool wants_raw_input =
1712 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1713 log->Printf("HandleCommand, wants_raw_input:'%s'",
1714 wants_raw_input ? "True" : "False");
1715 }
1716
1717 // Phase 2.
1718 // Take care of things like setting up the history command & calling the
Adrian Prantl05097242018-04-30 16:49:04 +00001719 // appropriate Execute method on the CommandObject, with the appropriate
1720 // arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001721
1722 if (cmd_obj != nullptr) {
1723 if (add_to_history) {
1724 Args command_args(command_string);
1725 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1726 if (repeat_command != nullptr)
1727 m_repeat_command.assign(repeat_command);
1728 else
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001729 m_repeat_command.assign(original_command_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730
1731 m_command_history.AppendString(original_command_string);
1732 }
1733
1734 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001735 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001736 if (actual_cmd_name_len < command_string.length())
1737 remainder = command_string.substr(actual_cmd_name_len);
1738
1739 // Remove any initial spaces
1740 size_t pos = remainder.find_first_not_of(k_white_space);
1741 if (pos != 0 && pos != std::string::npos)
1742 remainder.erase(0, pos);
1743
1744 if (log)
1745 log->Printf(
1746 "HandleCommand, command line after removing command name(s): '%s'",
1747 remainder.c_str());
1748
1749 cmd_obj->Execute(remainder.c_str(), result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001750 }
1751
1752 if (log)
1753 log->Printf("HandleCommand, command %s",
1754 (result.Succeeded() ? "succeeded" : "did not succeed"));
1755
1756 return result.Succeeded();
1757}
1758
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001759int CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001760 int num_command_matches = 0;
1761 bool look_for_subcommand = false;
1762
1763 // For any of the command completions a unique match will be a complete word.
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001764 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001765
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001766 if (request.GetCursorIndex() == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001767 // We got nothing on the command line, so return the list of commands
1768 bool include_aliases = true;
Raphael Isemann7f888292018-09-13 21:26:00 +00001769 StringList new_matches, descriptions;
1770 num_command_matches = GetCommandNamesMatchingPartialString(
1771 "", include_aliases, new_matches, descriptions);
1772 request.AddCompletions(new_matches, descriptions);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001773 } else if (request.GetCursorIndex() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001774 // The cursor is in the first argument, so just do a lookup in the
1775 // dictionary.
Raphael Isemann7f888292018-09-13 21:26:00 +00001776 StringList new_matches, new_descriptions;
1777 CommandObject *cmd_obj =
1778 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0),
1779 &new_matches, &new_descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001780
1781 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001782 new_matches.GetStringAtIndex(0) != nullptr &&
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001783 strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001784 new_matches.GetStringAtIndex(0)) == 0) {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001785 if (request.GetParsedLine().GetArgumentCount() == 1) {
1786 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001787 } else {
1788 look_for_subcommand = true;
1789 num_command_matches = 0;
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001790 new_matches.DeleteStringAtIndex(0);
Raphael Isemann7f888292018-09-13 21:26:00 +00001791 new_descriptions.DeleteStringAtIndex(0);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001792 request.GetParsedLine().AppendArgument(llvm::StringRef());
1793 request.SetCursorIndex(request.GetCursorIndex() + 1);
1794 request.SetCursorCharPosition(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001795 }
1796 }
Raphael Isemann7f888292018-09-13 21:26:00 +00001797 request.AddCompletions(new_matches, new_descriptions);
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001798 num_command_matches = request.GetNumberOfMatches();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001799 }
1800
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001801 if (request.GetCursorIndex() > 0 || look_for_subcommand) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001802 // We are completing further on into a commands arguments, so find the
Adrian Prantl05097242018-04-30 16:49:04 +00001803 // command and tell it to complete the command. First see if there is a
1804 // matching initial command:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001805 CommandObject *command_object =
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001806 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001807 if (command_object == nullptr) {
1808 return 0;
1809 } else {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001810 request.GetParsedLine().Shift();
1811 request.SetCursorIndex(request.GetCursorIndex() - 1);
1812 num_command_matches = command_object->HandleCompletion(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001813 }
1814 }
1815
1816 return num_command_matches;
1817}
1818
1819int CommandInterpreter::HandleCompletion(
1820 const char *current_line, const char *cursor, const char *last_char,
Raphael Isemann7f888292018-09-13 21:26:00 +00001821 int match_start_point, int max_return_elements, StringList &matches,
1822 StringList &descriptions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001823
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001824 llvm::StringRef command_line(current_line, last_char - current_line);
Raphael Isemann7f888292018-09-13 21:26:00 +00001825 CompletionResult result;
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001826 CompletionRequest request(command_line, cursor - current_line,
Raphael Isemann7f888292018-09-13 21:26:00 +00001827 match_start_point, max_return_elements, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001828 // Don't complete comments, and if the line we are completing is just the
Adrian Prantl05097242018-04-30 16:49:04 +00001829 // history repeat character, substitute the appropriate history line.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001830 const char *first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001831 if (first_arg) {
1832 if (first_arg[0] == m_comment_char)
1833 return 0;
1834 else if (first_arg[0] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001835 if (auto hist_str = m_command_history.FindString(first_arg)) {
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001836 matches.InsertStringAtIndex(0, *hist_str);
Raphael Isemann7f888292018-09-13 21:26:00 +00001837 descriptions.InsertStringAtIndex(0, "Previous command history event");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001838 return -2;
1839 } else
1840 return 0;
1841 }
1842 }
1843
Kate Stoneb9c1b512016-09-06 20:57:50 +00001844 // Only max_return_elements == -1 is supported at present:
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001845 lldbassert(max_return_elements == -1);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001846
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001847 int num_command_matches = HandleCompletionMatches(request);
Raphael Isemann7f888292018-09-13 21:26:00 +00001848 result.GetMatches(matches);
1849 result.GetDescriptions(descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001850
1851 if (num_command_matches <= 0)
1852 return num_command_matches;
1853
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001854 if (request.GetParsedLine().GetArgumentCount() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001855 // If we got an empty string, insert nothing.
1856 matches.InsertStringAtIndex(0, "");
Raphael Isemann7f888292018-09-13 21:26:00 +00001857 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001858 } else {
1859 // Now figure out if there is a common substring, and if so put that in
Adrian Prantl05097242018-04-30 16:49:04 +00001860 // element 0, otherwise put an empty string in element 0.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001861 std::string command_partial_str = request.GetCursorArgumentPrefix().str();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001862
1863 std::string common_prefix;
1864 matches.LongestCommonPrefix(common_prefix);
1865 const size_t partial_name_len = command_partial_str.size();
1866 common_prefix.erase(0, partial_name_len);
1867
Adrian Prantl05097242018-04-30 16:49:04 +00001868 // If we matched a unique single command, add a space... Only do this if
1869 // the completer told us this was a complete word, however...
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001870 if (num_command_matches == 1 && request.GetWordComplete()) {
1871 char quote_char = request.GetParsedLine()[request.GetCursorIndex()].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001872 common_prefix =
1873 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1874 if (quote_char != '\0')
1875 common_prefix.push_back(quote_char);
1876 common_prefix.push_back(' ');
1877 }
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001878 matches.InsertStringAtIndex(0, common_prefix.c_str());
Raphael Isemann7f888292018-09-13 21:26:00 +00001879 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001880 }
1881 return num_command_matches;
1882}
1883
1884CommandInterpreter::~CommandInterpreter() {}
1885
Zachary Turner514d8cd2016-09-23 18:06:53 +00001886void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001887 EventSP prompt_change_event_sp(
1888 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1889 ;
1890 BroadcastEvent(prompt_change_event_sp);
1891 if (m_command_io_handler_sp)
1892 m_command_io_handler_sp->SetPrompt(new_prompt);
1893}
1894
Zachary Turner7a120c82016-11-13 03:05:58 +00001895bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001896 // Check AutoConfirm first:
1897 if (m_debugger.GetAutoConfirm())
1898 return default_answer;
1899
1900 IOHandlerConfirm *confirm =
1901 new IOHandlerConfirm(m_debugger, message, default_answer);
1902 IOHandlerSP io_handler_sp(confirm);
1903 m_debugger.RunIOHandler(io_handler_sp);
1904 return confirm->GetResponse();
1905}
1906
Zachary Turnera483f572016-10-05 21:14:49 +00001907const CommandAlias *
1908CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001909 OptionArgVectorSP ret_val;
1910
Zachary Turnera483f572016-10-05 21:14:49 +00001911 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001912 if (pos != m_alias_dict.end())
1913 return (CommandAlias *)pos->second.get();
1914
1915 return nullptr;
1916}
1917
Zachary Turnera4496982016-10-05 21:14:38 +00001918bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001919
Zachary Turnera4496982016-10-05 21:14:38 +00001920bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001921
Zachary Turnera4496982016-10-05 21:14:38 +00001922bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001923
Zachary Turnera4496982016-10-05 21:14:38 +00001924bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001925
1926void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1927 const char *alias_name,
1928 Args &cmd_args,
1929 std::string &raw_input_string,
1930 CommandReturnObject &result) {
1931 OptionArgVectorSP option_arg_vector_sp =
1932 GetAlias(alias_name)->GetOptionArguments();
1933
1934 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1935
1936 // Make sure that the alias name is the 0th element in cmd_args
1937 std::string alias_name_str = alias_name;
1938 if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)
Zachary Turner5c725f32016-09-19 21:56:59 +00001939 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001940
1941 Args new_args(alias_cmd_obj->GetCommandName());
1942 if (new_args.GetArgumentCount() == 2)
1943 new_args.Shift();
1944
1945 if (option_arg_vector_sp.get()) {
1946 if (wants_raw_input) {
1947 // We have a command that both has command options and takes raw input.
Adrian Prantl05097242018-04-30 16:49:04 +00001948 // Make *sure* it has a " -- " in the right place in the
1949 // raw_input_string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001950 size_t pos = raw_input_string.find(" -- ");
1951 if (pos == std::string::npos) {
1952 // None found; assume it goes at the beginning of the raw input string
1953 raw_input_string.insert(0, " -- ");
1954 }
1955 }
1956
1957 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1958 const size_t old_size = cmd_args.GetArgumentCount();
1959 std::vector<bool> used(old_size + 1, false);
1960
1961 used[0] = true;
1962
Zachary Turner5c28c662016-10-03 23:20:36 +00001963 int value_type;
1964 std::string option;
1965 std::string value;
1966 for (const auto &option_entry : *option_arg_vector) {
1967 std::tie(option, value_type, value) = option_entry;
1968 if (option == "<argument>") {
1969 if (!wants_raw_input || (value != "--")) {
1970 // Since we inserted this above, make sure we don't insert it twice
1971 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001972 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001973 continue;
1974 }
1975
1976 if (value_type != OptionParser::eOptionalArgument)
1977 new_args.AppendArgument(option);
1978
1979 if (value == "<no-argument>")
1980 continue;
1981
1982 int index = GetOptionArgumentPosition(value.c_str());
1983 if (index == 0) {
1984 // value was NOT a positional argument; must be a real value
1985 if (value_type != OptionParser::eOptionalArgument)
1986 new_args.AppendArgument(value);
1987 else {
1988 char buffer[255];
1989 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1990 value.c_str());
1991 new_args.AppendArgument(llvm::StringRef(buffer));
1992 }
1993
1994 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1995 result.AppendErrorWithFormat("Not enough arguments provided; you "
1996 "need at least %d arguments to use "
1997 "this alias.\n",
1998 index);
1999 result.SetStatus(eReturnStatusFailed);
2000 return;
2001 } else {
2002 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2003 size_t strpos =
2004 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
2005 if (strpos != std::string::npos) {
2006 raw_input_string = raw_input_string.erase(
2007 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2008 }
2009
2010 if (value_type != OptionParser::eOptionalArgument)
2011 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2012 else {
2013 char buffer[255];
2014 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2015 cmd_args.GetArgumentAtIndex(index));
2016 new_args.AppendArgument(buffer);
2017 }
2018 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002019 }
2020 }
2021
Zachary Turner97d2c402016-10-05 23:40:23 +00002022 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00002023 if (!used[entry.index()] && !wants_raw_input)
2024 new_args.AppendArgument(entry.value().ref);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002025 }
2026
2027 cmd_args.Clear();
2028 cmd_args.SetArguments(new_args.GetArgumentCount(),
2029 new_args.GetConstArgumentVector());
2030 } else {
2031 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2032 // This alias was not created with any options; nothing further needs to be
Adrian Prantl05097242018-04-30 16:49:04 +00002033 // done, unless it is a command that wants raw input, in which case we need
2034 // to clear the rest of the data from cmd_args, since its in the raw input
2035 // string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002036 if (wants_raw_input) {
2037 cmd_args.Clear();
2038 cmd_args.SetArguments(new_args.GetArgumentCount(),
2039 new_args.GetConstArgumentVector());
2040 }
2041 return;
2042 }
2043
2044 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2045 return;
2046}
2047
2048int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2049 int position = 0; // Any string that isn't an argument position, i.e. '%'
2050 // followed by an integer, gets a position
2051 // of zero.
2052
2053 const char *cptr = in_string;
2054
2055 // Does it start with '%'
2056 if (cptr[0] == '%') {
2057 ++cptr;
2058
2059 // Is the rest of it entirely digits?
2060 if (isdigit(cptr[0])) {
2061 const char *start = cptr;
2062 while (isdigit(cptr[0]))
2063 ++cptr;
2064
Adrian Prantl05097242018-04-30 16:49:04 +00002065 // We've gotten to the end of the digits; are we at the end of the
2066 // string?
Kate Stoneb9c1b512016-09-06 20:57:50 +00002067 if (cptr[0] == '\0')
2068 position = atoi(start);
2069 }
2070 }
2071
2072 return position;
2073}
2074
2075void CommandInterpreter::SourceInitFile(bool in_cwd,
2076 CommandReturnObject &result) {
2077 FileSpec init_file;
2078 if (in_cwd) {
2079 ExecutionContext exe_ctx(GetExecutionContext());
2080 Target *target = exe_ctx.GetTargetPtr();
2081 if (target) {
2082 // In the current working directory we don't load any program specific
2083 // .lldbinit files, we only look for a ".lldbinit" file.
2084 if (m_skip_lldbinit_files)
2085 return;
2086
2087 LoadCWDlldbinitFile should_load =
2088 target->TargetProperties::GetLoadCWDlldbinitFile();
2089 if (should_load == eLoadCWDlldbinitWarn) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002090 FileSpec dot_lldb(".lldbinit");
2091 FileSystem::Instance().Resolve(dot_lldb);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002092 llvm::SmallString<64> home_dir_path;
2093 llvm::sys::path::home_directory(home_dir_path);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002094 FileSpec homedir_dot_lldb(home_dir_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002095 homedir_dot_lldb.AppendPathComponent(".lldbinit");
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002096 FileSystem::Instance().Resolve(homedir_dot_lldb);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002097 if (FileSystem::Instance().Exists(dot_lldb) &&
Kate Stoneb9c1b512016-09-06 20:57:50 +00002098 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2099 result.AppendErrorWithFormat(
2100 "There is a .lldbinit file in the current directory which is not "
2101 "being read.\n"
2102 "To silence this warning without sourcing in the local "
2103 ".lldbinit,\n"
2104 "add the following to the lldbinit file in your home directory:\n"
2105 " settings set target.load-cwd-lldbinit false\n"
2106 "To allow lldb to source .lldbinit files in the current working "
2107 "directory,\n"
2108 "set the value of this variable to true. Only do so if you "
2109 "understand and\n"
2110 "accept the security risk.");
2111 result.SetStatus(eReturnStatusFailed);
2112 return;
2113 }
2114 } else if (should_load == eLoadCWDlldbinitTrue) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002115 init_file.SetFile("./.lldbinit", FileSpec::Style::native);
2116 FileSystem::Instance().Resolve(init_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002117 }
2118 }
2119 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002120 // If we aren't looking in the current working directory we are looking in
2121 // the home directory. We will first see if there is an application
2122 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a "-"
2123 // and the name of the program. If this file doesn't exist, we fall back to
2124 // just the "~/.lldbinit" file. We also obey any requests to not load the
2125 // init files.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002126 llvm::SmallString<64> home_dir_path;
2127 llvm::sys::path::home_directory(home_dir_path);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002128 FileSpec profilePath(home_dir_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002129 profilePath.AppendPathComponent(".lldbinit");
2130 std::string init_file_path = profilePath.GetPath();
2131
2132 if (m_skip_app_init_files == false) {
2133 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2134 const char *program_name = program_file_spec.GetFilename().AsCString();
2135
2136 if (program_name) {
2137 char program_init_file_name[PATH_MAX];
2138 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2139 "%s-%s", init_file_path.c_str(), program_name);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002140 init_file.SetFile(program_init_file_name, FileSpec::Style::native);
2141 FileSystem::Instance().Resolve(init_file);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002142 if (!FileSystem::Instance().Exists(init_file))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002143 init_file.Clear();
2144 }
2145 }
2146
2147 if (!init_file && !m_skip_lldbinit_files)
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002148 init_file.SetFile(init_file_path, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002149 }
2150
2151 // If the file exists, tell HandleCommand to 'source' it; this will do the
Adrian Prantl05097242018-04-30 16:49:04 +00002152 // actual broadcasting of the commands back to any appropriate listener (see
Kate Stoneb9c1b512016-09-06 20:57:50 +00002153 // CommandObjectSource::Execute for more details).
2154
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002155 if (FileSystem::Instance().Exists(init_file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002156 const bool saved_batch = SetBatchCommandMode(true);
2157 CommandInterpreterRunOptions options;
2158 options.SetSilent(true);
2159 options.SetStopOnError(false);
2160 options.SetStopOnContinue(true);
2161
2162 HandleCommandsFromFile(init_file,
2163 nullptr, // Execution context
2164 options, result);
2165 SetBatchCommandMode(saved_batch);
2166 } else {
2167 // nothing to be done if the file doesn't exist
2168 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2169 }
2170}
2171
2172const char *CommandInterpreter::GetCommandPrefix() {
2173 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2174 return prefix == NULL ? "" : prefix;
2175}
2176
2177PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2178 PlatformSP platform_sp;
2179 if (prefer_target_platform) {
2180 ExecutionContext exe_ctx(GetExecutionContext());
2181 Target *target = exe_ctx.GetTargetPtr();
2182 if (target)
2183 platform_sp = target->GetPlatform();
2184 }
2185
2186 if (!platform_sp)
2187 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2188 return platform_sp;
2189}
2190
2191void CommandInterpreter::HandleCommands(const StringList &commands,
2192 ExecutionContext *override_context,
2193 CommandInterpreterRunOptions &options,
2194 CommandReturnObject &result) {
2195 size_t num_lines = commands.GetSize();
2196
2197 // If we are going to continue past a "continue" then we need to run the
Adrian Prantl05097242018-04-30 16:49:04 +00002198 // commands synchronously. Make sure you reset this value anywhere you return
2199 // from the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002200
2201 bool old_async_execution = m_debugger.GetAsyncExecution();
2202
2203 // If we've been given an execution context, set it at the start, but don't
Adrian Prantl05097242018-04-30 16:49:04 +00002204 // keep resetting it or we will cause series of commands that change the
2205 // context, then do an operation that relies on that context to fail.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002206
2207 if (override_context != nullptr)
2208 UpdateExecutionContext(override_context);
2209
2210 if (!options.GetStopOnContinue()) {
2211 m_debugger.SetAsyncExecution(false);
2212 }
2213
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002214 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002215 const char *cmd = commands.GetStringAtIndex(idx);
2216 if (cmd[0] == '\0')
2217 continue;
2218
2219 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002220 // TODO: Add Stream support.
2221 result.AppendMessageWithFormat("%s %s\n",
2222 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002223 }
2224
2225 CommandReturnObject tmp_result;
2226 // If override_context is not NULL, pass no_context_switching = true for
2227 // HandleCommand() since we updated our context already.
2228
2229 // We might call into a regex or alias command, in which case the
Adrian Prantl05097242018-04-30 16:49:04 +00002230 // add_to_history will get lost. This m_command_source_depth dingus is the
2231 // way we turn off adding to the history in that case, so set it up here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002232 if (!options.GetAddToHistory())
2233 m_command_source_depth++;
2234 bool success =
2235 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2236 nullptr, /* override_context */
2237 true, /* repeat_on_empty_command */
2238 override_context != nullptr /* no_context_switching */);
2239 if (!options.GetAddToHistory())
2240 m_command_source_depth--;
2241
2242 if (options.GetPrintResults()) {
2243 if (tmp_result.Succeeded())
Zachary Turner03c9f362016-11-14 23:23:31 +00002244 result.AppendMessage(tmp_result.GetOutputData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002245 }
2246
2247 if (!success || !tmp_result.Succeeded()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002248 llvm::StringRef error_msg = tmp_result.GetErrorData();
2249 if (error_msg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002250 error_msg = "<unknown error>.\n";
2251 if (options.GetStopOnError()) {
2252 result.AppendErrorWithFormat(
2253 "Aborting reading of commands after command #%" PRIu64
2254 ": '%s' failed with %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00002255 (uint64_t)idx, cmd, error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002256 result.SetStatus(eReturnStatusFailed);
2257 m_debugger.SetAsyncExecution(old_async_execution);
2258 return;
2259 } else if (options.GetPrintResults()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002260 result.AppendMessageWithFormat(
2261 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2262 error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002263 }
2264 }
2265
2266 if (result.GetImmediateOutputStream())
2267 result.GetImmediateOutputStream()->Flush();
2268
2269 if (result.GetImmediateErrorStream())
2270 result.GetImmediateErrorStream()->Flush();
2271
Adrian Prantl05097242018-04-30 16:49:04 +00002272 // N.B. Can't depend on DidChangeProcessState, because the state coming
2273 // into the command execution could be running (for instance in Breakpoint
2274 // Commands. So we check the return value to see if it is has running in
2275 // it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002276 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2277 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2278 if (options.GetStopOnContinue()) {
2279 // If we caused the target to proceed, and we're going to stop in that
Adrian Prantl05097242018-04-30 16:49:04 +00002280 // case, set the status in our real result before returning. This is
2281 // an error if the continue was not the last command in the set of
2282 // commands to be run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002283 if (idx != num_lines - 1)
2284 result.AppendErrorWithFormat(
2285 "Aborting reading of commands after command #%" PRIu64
2286 ": '%s' continued the target.\n",
2287 (uint64_t)idx + 1, cmd);
2288 else
2289 result.AppendMessageWithFormat("Command #%" PRIu64
2290 " '%s' continued the target.\n",
2291 (uint64_t)idx + 1, cmd);
2292
2293 result.SetStatus(tmp_result.GetStatus());
2294 m_debugger.SetAsyncExecution(old_async_execution);
2295
2296 return;
2297 }
2298 }
2299
2300 // Also check for "stop on crash here:
2301 bool should_stop = false;
2302 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2303 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2304 if (target_sp) {
2305 ProcessSP process_sp(target_sp->GetProcessSP());
2306 if (process_sp) {
2307 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2308 StopReason reason = thread_sp->GetStopReason();
2309 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2310 reason == eStopReasonInstrumentation) {
2311 should_stop = true;
2312 break;
2313 }
2314 }
2315 }
2316 }
2317 if (should_stop) {
2318 if (idx != num_lines - 1)
2319 result.AppendErrorWithFormat(
2320 "Aborting reading of commands after command #%" PRIu64
2321 ": '%s' stopped with a signal or exception.\n",
2322 (uint64_t)idx + 1, cmd);
2323 else
2324 result.AppendMessageWithFormat(
2325 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2326 (uint64_t)idx + 1, cmd);
2327
2328 result.SetStatus(tmp_result.GetStatus());
2329 m_debugger.SetAsyncExecution(old_async_execution);
2330
2331 return;
2332 }
2333 }
2334 }
2335
2336 result.SetStatus(eReturnStatusSuccessFinishResult);
2337 m_debugger.SetAsyncExecution(old_async_execution);
2338
2339 return;
2340}
2341
2342// Make flags that we can pass into the IOHandler so our delegates can do the
2343// right thing
2344enum {
2345 eHandleCommandFlagStopOnContinue = (1u << 0),
2346 eHandleCommandFlagStopOnError = (1u << 1),
2347 eHandleCommandFlagEchoCommand = (1u << 2),
Stefan Granitzc678ed72018-10-05 16:49:47 +00002348 eHandleCommandFlagEchoCommentCommand = (1u << 3),
2349 eHandleCommandFlagPrintResult = (1u << 4),
2350 eHandleCommandFlagStopOnCrash = (1u << 5)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002351};
2352
2353void CommandInterpreter::HandleCommandsFromFile(
2354 FileSpec &cmd_file, ExecutionContext *context,
2355 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002356 if (FileSystem::Instance().Exists(cmd_file)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002357 StreamFileSP input_file_sp(new StreamFile());
2358
2359 std::string cmd_file_path = cmd_file.GetPath();
Zachary Turner97206d52017-05-12 04:51:55 +00002360 Status error = input_file_sp->GetFile().Open(cmd_file_path.c_str(),
2361 File::eOpenOptionRead);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002362
2363 if (error.Success()) {
2364 Debugger &debugger = GetDebugger();
2365
2366 uint32_t flags = 0;
2367
2368 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2369 if (m_command_source_flags.empty()) {
2370 // Stop on continue by default
2371 flags |= eHandleCommandFlagStopOnContinue;
2372 } else if (m_command_source_flags.back() &
2373 eHandleCommandFlagStopOnContinue) {
2374 flags |= eHandleCommandFlagStopOnContinue;
2375 }
2376 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2377 flags |= eHandleCommandFlagStopOnContinue;
2378 }
2379
2380 if (options.m_stop_on_error == eLazyBoolCalculate) {
2381 if (m_command_source_flags.empty()) {
2382 if (GetStopCmdSourceOnError())
2383 flags |= eHandleCommandFlagStopOnError;
2384 } else if (m_command_source_flags.back() &
2385 eHandleCommandFlagStopOnError) {
2386 flags |= eHandleCommandFlagStopOnError;
2387 }
2388 } else if (options.m_stop_on_error == eLazyBoolYes) {
2389 flags |= eHandleCommandFlagStopOnError;
2390 }
2391
Stefan Granitzc678ed72018-10-05 16:49:47 +00002392 // stop-on-crash can only be set, if it is present in all levels of
2393 // pushed flag sets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002394 if (options.GetStopOnCrash()) {
2395 if (m_command_source_flags.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002396 flags |= eHandleCommandFlagStopOnCrash;
2397 } else if (m_command_source_flags.back() &
2398 eHandleCommandFlagStopOnCrash) {
2399 flags |= eHandleCommandFlagStopOnCrash;
2400 }
2401 }
2402
2403 if (options.m_echo_commands == eLazyBoolCalculate) {
2404 if (m_command_source_flags.empty()) {
2405 // Echo command by default
2406 flags |= eHandleCommandFlagEchoCommand;
2407 } else if (m_command_source_flags.back() &
2408 eHandleCommandFlagEchoCommand) {
2409 flags |= eHandleCommandFlagEchoCommand;
2410 }
2411 } else if (options.m_echo_commands == eLazyBoolYes) {
2412 flags |= eHandleCommandFlagEchoCommand;
2413 }
2414
Stefan Granitzc678ed72018-10-05 16:49:47 +00002415 // We will only ever ask for this flag, if we echo commands in general.
2416 if (options.m_echo_comment_commands == eLazyBoolCalculate) {
2417 if (m_command_source_flags.empty()) {
2418 // Echo comments by default
2419 flags |= eHandleCommandFlagEchoCommentCommand;
2420 } else if (m_command_source_flags.back() &
2421 eHandleCommandFlagEchoCommentCommand) {
2422 flags |= eHandleCommandFlagEchoCommentCommand;
2423 }
2424 } else if (options.m_echo_comment_commands == eLazyBoolYes) {
2425 flags |= eHandleCommandFlagEchoCommentCommand;
2426 }
2427
Kate Stoneb9c1b512016-09-06 20:57:50 +00002428 if (options.m_print_results == eLazyBoolCalculate) {
2429 if (m_command_source_flags.empty()) {
2430 // Print output by default
2431 flags |= eHandleCommandFlagPrintResult;
2432 } else if (m_command_source_flags.back() &
2433 eHandleCommandFlagPrintResult) {
2434 flags |= eHandleCommandFlagPrintResult;
2435 }
2436 } else if (options.m_print_results == eLazyBoolYes) {
2437 flags |= eHandleCommandFlagPrintResult;
2438 }
2439
2440 if (flags & eHandleCommandFlagPrintResult) {
2441 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2442 cmd_file_path.c_str());
2443 }
2444
Adrian Prantl05097242018-04-30 16:49:04 +00002445 // Used for inheriting the right settings when "command source" might
2446 // have nested "command source" commands
Kate Stoneb9c1b512016-09-06 20:57:50 +00002447 lldb::StreamFileSP empty_stream_sp;
2448 m_command_source_flags.push_back(flags);
2449 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2450 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2451 empty_stream_sp, // Pass in an empty stream so we inherit the top
2452 // input reader output stream
2453 empty_stream_sp, // Pass in an empty stream so we inherit the top
2454 // input reader error stream
2455 flags,
2456 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2457 // or written
Zachary Turner514d8cd2016-09-23 18:06:53 +00002458 debugger.GetPrompt(), llvm::StringRef(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00002459 false, // Not multi-line
2460 debugger.GetUseColor(), 0, *this));
2461 const bool old_async_execution = debugger.GetAsyncExecution();
2462
2463 // Set synchronous execution if we are not stopping on continue
2464 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2465 debugger.SetAsyncExecution(false);
2466
2467 m_command_source_depth++;
2468
2469 debugger.RunIOHandler(io_handler_sp);
2470 if (!m_command_source_flags.empty())
2471 m_command_source_flags.pop_back();
2472 m_command_source_depth--;
2473 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2474 debugger.SetAsyncExecution(old_async_execution);
2475 } else {
2476 result.AppendErrorWithFormat(
2477 "error: an error occurred read file '%s': %s\n",
2478 cmd_file_path.c_str(), error.AsCString());
2479 result.SetStatus(eReturnStatusFailed);
2480 }
2481
2482 } else {
2483 result.AppendErrorWithFormat(
2484 "Error reading commands from file %s - file not found.\n",
2485 cmd_file.GetFilename().AsCString("<Unknown>"));
2486 result.SetStatus(eReturnStatusFailed);
2487 return;
2488 }
2489}
2490
2491ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
Jim Ingham30bac792017-07-13 19:45:54 +00002492 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
Greg Clayton79040462016-12-09 01:21:14 +00002493 if (!m_script_interpreter_sp) {
2494 if (!can_create)
2495 return nullptr;
2496 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2497 m_script_interpreter_sp =
2498 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2499 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002500 return m_script_interpreter_sp.get();
2501}
2502
2503bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2504
2505void CommandInterpreter::SetSynchronous(bool value) {
2506 m_synchronous_execution = value;
2507}
2508
2509void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002510 llvm::StringRef prefix,
2511 llvm::StringRef help_text) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002512 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002513
Zachary Turner0ac5f982016-11-08 04:12:42 +00002514 size_t line_width_max = max_columns - prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002515 if (line_width_max < 16)
Zachary Turner0ac5f982016-11-08 04:12:42 +00002516 line_width_max = help_text.size() + prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002517
Zachary Turner0ac5f982016-11-08 04:12:42 +00002518 strm.IndentMore(prefix.size());
2519 bool prefixed_yet = false;
2520 while (!help_text.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002521 // Prefix the first line, indent subsequent lines to line up
Zachary Turner0ac5f982016-11-08 04:12:42 +00002522 if (!prefixed_yet) {
2523 strm << prefix;
2524 prefixed_yet = true;
2525 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002526 strm.Indent();
Zachary Turner0ac5f982016-11-08 04:12:42 +00002527
2528 // Never print more than the maximum on one line.
2529 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2530
2531 // Always break on an explicit newline.
2532 std::size_t first_newline = this_line.find_first_of("\n");
2533
2534 // Don't break on space/tab unless the text is too long to fit on one line.
2535 std::size_t last_space = llvm::StringRef::npos;
2536 if (this_line.size() != help_text.size())
2537 last_space = this_line.find_last_of(" \t");
2538
2539 // Break at whichever condition triggered first.
2540 this_line = this_line.substr(0, std::min(first_newline, last_space));
2541 strm.PutCString(this_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002542 strm.EOL();
2543
Zachary Turner0ac5f982016-11-08 04:12:42 +00002544 // Remove whitespace / newlines after breaking.
2545 help_text = help_text.drop_front(this_line.size()).ltrim();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002546 }
Zachary Turner0ac5f982016-11-08 04:12:42 +00002547 strm.IndentLess(prefix.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002548}
2549
2550void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002551 llvm::StringRef word_text,
2552 llvm::StringRef separator,
2553 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002554 size_t max_word_len) {
2555 StreamString prefix_stream;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002556 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2557 (int)separator.size(), separator.data());
Zachary Turnerc1564272016-11-16 21:15:24 +00002558 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2559}
2560
Zachary Turner0ac5f982016-11-08 04:12:42 +00002561void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2562 llvm::StringRef separator,
2563 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002564 uint32_t max_word_len) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00002565 int indent_size = max_word_len + separator.size() + 2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002566
2567 strm.IndentMore(indent_size);
2568
2569 StreamString text_strm;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002570 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2571 text_strm << separator << " " << help_text;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002572
2573 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2574
Zachary Turnerc1564272016-11-16 21:15:24 +00002575 llvm::StringRef text = text_strm.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002576
2577 uint32_t chars_left = max_columns;
2578
Davide Italianocf8a8292017-04-14 22:36:08 +00002579 auto nextWordLength = [](llvm::StringRef S) {
2580 size_t pos = S.find_first_of(' ');
2581 return pos == llvm::StringRef::npos ? S.size() : pos;
2582 };
2583
Zachary Turnerc1564272016-11-16 21:15:24 +00002584 while (!text.empty()) {
2585 if (text.front() == '\n' ||
Jim Inghama81bd7f2017-07-27 00:18:18 +00002586 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002587 strm.EOL();
2588 strm.Indent();
Zachary Turnerc1564272016-11-16 21:15:24 +00002589 chars_left = max_columns - indent_size;
2590 if (text.front() == '\n')
2591 text = text.drop_front();
2592 else
2593 text = text.ltrim(' ');
Kate Stoneb9c1b512016-09-06 20:57:50 +00002594 } else {
Zachary Turnerc1564272016-11-16 21:15:24 +00002595 strm.PutChar(text.front());
2596 --chars_left;
2597 text = text.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002598 }
2599 }
2600
2601 strm.EOL();
2602 strm.IndentLess(indent_size);
2603}
2604
2605void CommandInterpreter::FindCommandsForApropos(
Zachary Turner067d1db2016-11-16 21:45:04 +00002606 llvm::StringRef search_word, StringList &commands_found,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002607 StringList &commands_help, CommandObject::CommandMap &command_map) {
2608 CommandObject::CommandMap::const_iterator pos;
2609
2610 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
Zachary Turner067d1db2016-11-16 21:45:04 +00002611 llvm::StringRef command_name = pos->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002612 CommandObject *cmd_obj = pos->second.get();
2613
2614 const bool search_short_help = true;
2615 const bool search_long_help = false;
2616 const bool search_syntax = false;
2617 const bool search_options = false;
Zachary Turner067d1db2016-11-16 21:45:04 +00002618 if (command_name.contains_lower(search_word) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002619 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2620 search_long_help, search_syntax,
2621 search_options)) {
2622 commands_found.AppendString(cmd_obj->GetCommandName());
2623 commands_help.AppendString(cmd_obj->GetHelp());
2624 }
2625
2626 if (cmd_obj->IsMultiwordObject()) {
2627 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2628 FindCommandsForApropos(search_word, commands_found, commands_help,
2629 cmd_multiword->GetSubcommandDictionary());
2630 }
2631 }
2632}
2633
Zachary Turner067d1db2016-11-16 21:45:04 +00002634void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002635 StringList &commands_found,
2636 StringList &commands_help,
2637 bool search_builtin_commands,
2638 bool search_user_commands,
2639 bool search_alias_commands) {
2640 CommandObject::CommandMap::const_iterator pos;
2641
2642 if (search_builtin_commands)
2643 FindCommandsForApropos(search_word, commands_found, commands_help,
2644 m_command_dict);
2645
2646 if (search_user_commands)
2647 FindCommandsForApropos(search_word, commands_found, commands_help,
2648 m_user_dict);
2649
2650 if (search_alias_commands)
2651 FindCommandsForApropos(search_word, commands_found, commands_help,
2652 m_alias_dict);
2653}
2654
2655void CommandInterpreter::UpdateExecutionContext(
2656 ExecutionContext *override_context) {
2657 if (override_context != nullptr) {
2658 m_exe_ctx_ref = *override_context;
2659 } else {
2660 const bool adopt_selected = true;
2661 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2662 adopt_selected);
2663 }
2664}
2665
2666size_t CommandInterpreter::GetProcessOutput() {
2667 // The process has stuff waiting for stderr; get it and write it out to the
2668 // appropriate place.
2669 char stdio_buffer[1024];
2670 size_t len;
2671 size_t total_bytes = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002672 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002673 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2674 if (target_sp) {
2675 ProcessSP process_sp(target_sp->GetProcessSP());
2676 if (process_sp) {
2677 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2678 error)) > 0) {
2679 size_t bytes_written = len;
2680 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2681 total_bytes += len;
2682 }
2683 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2684 error)) > 0) {
2685 size_t bytes_written = len;
2686 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2687 total_bytes += len;
2688 }
2689 }
2690 }
2691 return total_bytes;
2692}
2693
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002694void CommandInterpreter::StartHandlingCommand() {
2695 auto idle_state = CommandHandlingState::eIdle;
2696 if (m_command_state.compare_exchange_strong(
2697 idle_state, CommandHandlingState::eInProgress))
2698 lldbassert(m_iohandler_nesting_level == 0);
2699 else
2700 lldbassert(m_iohandler_nesting_level > 0);
2701 ++m_iohandler_nesting_level;
2702}
2703
2704void CommandInterpreter::FinishHandlingCommand() {
2705 lldbassert(m_iohandler_nesting_level > 0);
2706 if (--m_iohandler_nesting_level == 0) {
2707 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2708 lldbassert(prev_state != CommandHandlingState::eIdle);
2709 }
2710}
2711
2712bool CommandInterpreter::InterruptCommand() {
2713 auto in_progress = CommandHandlingState::eInProgress;
2714 return m_command_state.compare_exchange_strong(
2715 in_progress, CommandHandlingState::eInterrupted);
2716}
2717
2718bool CommandInterpreter::WasInterrupted() const {
2719 bool was_interrupted =
2720 (m_command_state == CommandHandlingState::eInterrupted);
2721 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2722 return was_interrupted;
2723}
2724
2725void CommandInterpreter::PrintCommandOutput(Stream &stream,
2726 llvm::StringRef str) {
2727 // Split the output into lines and poll for interrupt requests
2728 const char *data = str.data();
2729 size_t size = str.size();
2730 while (size > 0 && !WasInterrupted()) {
2731 size_t chunk_size = 0;
2732 for (; chunk_size < size; ++chunk_size) {
2733 lldbassert(data[chunk_size] != '\0');
2734 if (data[chunk_size] == '\n') {
2735 ++chunk_size;
2736 break;
2737 }
2738 }
2739 chunk_size = stream.Write(data, chunk_size);
2740 lldbassert(size >= chunk_size);
2741 data += chunk_size;
2742 size -= chunk_size;
2743 }
2744 if (size > 0) {
2745 stream.Printf("\n... Interrupted.\n");
2746 }
2747}
2748
Stefan Granitzc678ed72018-10-05 16:49:47 +00002749bool CommandInterpreter::EchoCommandNonInteractive(
2750 llvm::StringRef line, const Flags &io_handler_flags) const {
2751 if (!io_handler_flags.Test(eHandleCommandFlagEchoCommand))
2752 return false;
2753
2754 llvm::StringRef command = line.trim();
2755 if (command.empty())
2756 return true;
2757
2758 if (command.front() == m_comment_char)
2759 return io_handler_flags.Test(eHandleCommandFlagEchoCommentCommand);
2760
2761 return true;
2762}
2763
Kate Stoneb9c1b512016-09-06 20:57:50 +00002764void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2765 std::string &line) {
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002766 // If we were interrupted, bail out...
2767 if (WasInterrupted())
2768 return;
2769
Kate Stoneb9c1b512016-09-06 20:57:50 +00002770 const bool is_interactive = io_handler.GetIsInteractive();
2771 if (is_interactive == false) {
2772 // When we are not interactive, don't execute blank lines. This will happen
2773 // sourcing a commands file. We don't want blank lines to repeat the
Adrian Prantl05097242018-04-30 16:49:04 +00002774 // previous command and cause any errors to occur (like redefining an
2775 // alias, get an error and stop parsing the commands file).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002776 if (line.empty())
2777 return;
2778
2779 // When using a non-interactive file handle (like when sourcing commands
Adrian Prantl05097242018-04-30 16:49:04 +00002780 // from a file) we need to echo the command out so we don't just see the
2781 // command output and no command...
Stefan Granitzc678ed72018-10-05 16:49:47 +00002782 if (EchoCommandNonInteractive(line, io_handler.GetFlags()))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002783 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2784 line.c_str());
2785 }
2786
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002787 StartHandlingCommand();
2788
Kate Stoneb9c1b512016-09-06 20:57:50 +00002789 lldb_private::CommandReturnObject result;
2790 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2791
2792 // Now emit the command output text from the command we just executed
2793 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2794 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2795 GetProcessOutput();
2796
2797 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002798 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002799 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002800 }
2801
2802 // Now emit the command error text from the command we just executed
2803 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002804 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002805 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002806 }
2807 }
2808
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002809 FinishHandlingCommand();
2810
Kate Stoneb9c1b512016-09-06 20:57:50 +00002811 switch (result.GetStatus()) {
2812 case eReturnStatusInvalid:
2813 case eReturnStatusSuccessFinishNoResult:
2814 case eReturnStatusSuccessFinishResult:
2815 case eReturnStatusStarted:
2816 break;
2817
2818 case eReturnStatusSuccessContinuingNoResult:
2819 case eReturnStatusSuccessContinuingResult:
2820 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2821 io_handler.SetIsDone(true);
2822 break;
2823
2824 case eReturnStatusFailed:
2825 m_num_errors++;
2826 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2827 io_handler.SetIsDone(true);
2828 break;
2829
2830 case eReturnStatusQuit:
2831 m_quit_requested = true;
2832 io_handler.SetIsDone(true);
2833 break;
2834 }
2835
2836 // Finally, if we're going to stop on crash, check that here:
2837 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2838 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2839 bool should_stop = false;
2840 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2841 if (target_sp) {
2842 ProcessSP process_sp(target_sp->GetProcessSP());
2843 if (process_sp) {
2844 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2845 StopReason reason = thread_sp->GetStopReason();
2846 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2847 reason == eStopReasonInstrumentation) &&
2848 !result.GetAbnormalStopWasExpected()) {
2849 should_stop = true;
2850 break;
2851 }
2852 }
2853 }
2854 }
2855 if (should_stop) {
2856 io_handler.SetIsDone(true);
2857 m_stopped_for_crash = true;
2858 }
2859 }
2860}
2861
2862bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2863 ExecutionContext exe_ctx(GetExecutionContext());
2864 Process *process = exe_ctx.GetProcessPtr();
2865
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002866 if (InterruptCommand())
2867 return true;
2868
Kate Stoneb9c1b512016-09-06 20:57:50 +00002869 if (process) {
2870 StateType state = process->GetState();
2871 if (StateIsRunningState(state)) {
2872 process->Halt();
2873 return true; // Don't do any updating when we are running
2874 }
2875 }
2876
2877 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2878 if (script_interpreter) {
2879 if (script_interpreter->Interrupt())
2880 return true;
2881 }
2882 return false;
2883}
2884
2885void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2886 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2887 void *baton) {
2888 Debugger &debugger = GetDebugger();
2889 IOHandlerSP io_handler_sp(
2890 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2891 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002892 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2893 llvm::StringRef(), // Continuation prompt
2894 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002895 debugger.GetUseColor(),
2896 0, // Don't show line numbers
2897 delegate)); // IOHandlerDelegate
2898
2899 if (io_handler_sp) {
2900 io_handler_sp->SetUserData(baton);
2901 if (asynchronously)
2902 debugger.PushIOHandler(io_handler_sp);
2903 else
2904 debugger.RunIOHandler(io_handler_sp);
2905 }
2906}
2907
2908void CommandInterpreter::GetPythonCommandsFromIOHandler(
2909 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2910 void *baton) {
2911 Debugger &debugger = GetDebugger();
2912 IOHandlerSP io_handler_sp(
2913 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2914 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002915 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2916 llvm::StringRef(), // Continuation prompt
2917 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002918 debugger.GetUseColor(),
2919 0, // Don't show line numbers
2920 delegate)); // IOHandlerDelegate
2921
2922 if (io_handler_sp) {
2923 io_handler_sp->SetUserData(baton);
2924 if (asynchronously)
2925 debugger.PushIOHandler(io_handler_sp);
2926 else
2927 debugger.RunIOHandler(io_handler_sp);
2928 }
2929}
2930
2931bool CommandInterpreter::IsActive() {
2932 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2933}
2934
2935lldb::IOHandlerSP
2936CommandInterpreter::GetIOHandler(bool force_create,
2937 CommandInterpreterRunOptions *options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002938 // Always re-create the IOHandlerEditline in case the input changed. The old
2939 // instance might have had a non-interactive input and now it does or vice
2940 // versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002941 if (force_create || !m_command_io_handler_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002942 // Always re-create the IOHandlerEditline in case the input changed. The
2943 // old instance might have had a non-interactive input and now it does or
2944 // vice versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002945 uint32_t flags = 0;
2946
2947 if (options) {
2948 if (options->m_stop_on_continue == eLazyBoolYes)
2949 flags |= eHandleCommandFlagStopOnContinue;
2950 if (options->m_stop_on_error == eLazyBoolYes)
2951 flags |= eHandleCommandFlagStopOnError;
2952 if (options->m_stop_on_crash == eLazyBoolYes)
2953 flags |= eHandleCommandFlagStopOnCrash;
2954 if (options->m_echo_commands != eLazyBoolNo)
2955 flags |= eHandleCommandFlagEchoCommand;
Stefan Granitzc678ed72018-10-05 16:49:47 +00002956 if (options->m_echo_comment_commands != eLazyBoolNo)
2957 flags |= eHandleCommandFlagEchoCommentCommand;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002958 if (options->m_print_results != eLazyBoolNo)
2959 flags |= eHandleCommandFlagPrintResult;
2960 } else {
2961 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2962 }
2963
2964 m_command_io_handler_sp.reset(new IOHandlerEditline(
2965 m_debugger, IOHandler::Type::CommandInterpreter,
2966 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2967 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002968 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002969 false, // Don't enable multiple line input, just single line commands
2970 m_debugger.GetUseColor(),
2971 0, // Don't show line numbers
2972 *this));
2973 }
2974 return m_command_io_handler_sp;
2975}
2976
2977void CommandInterpreter::RunCommandInterpreter(
2978 bool auto_handle_events, bool spawn_thread,
2979 CommandInterpreterRunOptions &options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002980 // Always re-create the command interpreter when we run it in case any file
2981 // handles have changed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002982 bool force_create = true;
2983 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2984 m_stopped_for_crash = false;
2985
2986 if (auto_handle_events)
2987 m_debugger.StartEventHandlerThread();
2988
2989 if (spawn_thread) {
2990 m_debugger.StartIOHandlerThread();
2991 } else {
2992 m_debugger.ExecuteIOHandlers();
2993
2994 if (auto_handle_events)
2995 m_debugger.StopEventHandlerThread();
2996 }
2997}
2998
2999CommandObject *
3000CommandInterpreter::ResolveCommandImpl(std::string &command_line,
3001 CommandReturnObject &result) {
3002 std::string scratch_command(command_line); // working copy so we don't modify
3003 // command_line unless we succeed
3004 CommandObject *cmd_obj = nullptr;
3005 StreamString revised_command_line;
3006 bool wants_raw_input = false;
3007 size_t actual_cmd_name_len = 0;
3008 std::string next_word;
3009 StringList matches;
3010 bool done = false;
3011 while (!done) {
3012 char quote_char = '\0';
3013 std::string suffix;
3014 ExtractCommand(scratch_command, next_word, suffix, quote_char);
3015 if (cmd_obj == nullptr) {
3016 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003017 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00003018 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003019 bool is_real_command =
3020 (is_alias == false) ||
3021 (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
3022 if (!is_real_command) {
3023 matches.Clear();
3024 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003025 cmd_obj =
3026 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003027 revised_command_line.Printf("%s", alias_result.c_str());
3028 if (cmd_obj) {
3029 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00003030 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003031 }
3032 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003033 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00003034 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
3035 actual_cmd_name_len += cmd_name.size();
3036 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003037 wants_raw_input = cmd_obj->WantsRawCommandString();
3038 } else {
3039 revised_command_line.Printf("%s", next_word.c_str());
3040 }
3041 }
3042 } else {
3043 if (cmd_obj->IsMultiwordObject()) {
3044 CommandObject *sub_cmd_obj =
3045 cmd_obj->GetSubcommandObject(next_word.c_str());
3046 if (sub_cmd_obj) {
Adrian Prantl05097242018-04-30 16:49:04 +00003047 // The subcommand's name includes the parent command's name, so
3048 // restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00003049 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3050 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003051 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00003052 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003053 cmd_obj = sub_cmd_obj;
3054 wants_raw_input = cmd_obj->WantsRawCommandString();
3055 } else {
3056 if (quote_char)
3057 revised_command_line.Printf(" %c%s%s%c", quote_char,
3058 next_word.c_str(), suffix.c_str(),
3059 quote_char);
3060 else
3061 revised_command_line.Printf(" %s%s", next_word.c_str(),
3062 suffix.c_str());
3063 done = true;
3064 }
3065 } else {
3066 if (quote_char)
3067 revised_command_line.Printf(" %c%s%s%c", quote_char,
3068 next_word.c_str(), suffix.c_str(),
3069 quote_char);
3070 else
3071 revised_command_line.Printf(" %s%s", next_word.c_str(),
3072 suffix.c_str());
3073 done = true;
3074 }
3075 }
3076
3077 if (cmd_obj == nullptr) {
3078 const size_t num_matches = matches.GetSize();
3079 if (matches.GetSize() > 1) {
3080 StreamString error_msg;
3081 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3082 next_word.c_str());
3083
3084 for (uint32_t i = 0; i < num_matches; ++i) {
3085 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3086 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003087 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003088 } else {
3089 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003090 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003091 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3092 next_word.c_str());
3093 }
3094 result.SetStatus(eReturnStatusFailed);
3095 return nullptr;
3096 }
3097
3098 if (cmd_obj->IsMultiwordObject()) {
3099 if (!suffix.empty()) {
3100 result.AppendErrorWithFormat(
3101 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3102 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003103 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003104 next_word.empty() ? "" : next_word.c_str(),
3105 next_word.empty() ? " -- " : " ", suffix.c_str());
3106 result.SetStatus(eReturnStatusFailed);
3107 return nullptr;
3108 }
3109 } else {
3110 // If we found a normal command, we are done
3111 done = true;
3112 if (!suffix.empty()) {
3113 switch (suffix[0]) {
3114 case '/':
3115 // GDB format suffixes
3116 {
3117 Options *command_options = cmd_obj->GetOptions();
3118 if (command_options &&
3119 command_options->SupportsLongOption("gdb-format")) {
3120 std::string gdb_format_option("--gdb-format=");
3121 gdb_format_option += (suffix.c_str() + 1);
3122
Zachary Turnerc1564272016-11-16 21:15:24 +00003123 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003124 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3125 if (arg_terminator_idx != std::string::npos) {
3126 // Insert the gdb format option before the "--" that terminates
3127 // options
3128 gdb_format_option.append(1, ' ');
3129 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003130 revised_command_line.Clear();
3131 revised_command_line.PutCString(cmd);
3132 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003133 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3134
3135 if (wants_raw_input &&
3136 FindArgumentTerminator(cmd) == std::string::npos)
3137 revised_command_line.PutCString(" --");
3138 } else {
3139 result.AppendErrorWithFormat(
3140 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003141 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003142 result.SetStatus(eReturnStatusFailed);
3143 return nullptr;
3144 }
3145 }
3146 break;
3147
3148 default:
3149 result.AppendErrorWithFormat(
3150 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3151 result.SetStatus(eReturnStatusFailed);
3152 return nullptr;
3153 }
3154 }
3155 }
3156 if (scratch_command.empty())
3157 done = true;
3158 }
3159
3160 if (!scratch_command.empty())
3161 revised_command_line.Printf(" %s", scratch_command.c_str());
3162
3163 if (cmd_obj != NULL)
Zachary Turnerc1564272016-11-16 21:15:24 +00003164 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003165
3166 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003167}