blob: 77fdeb1d8489e00e17250eb1ac6ba09d86d23cdc [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
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000079static constexpr PropertyDefinition g_properties[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +000080 {"expand-regex-aliases", OptionValue::eTypeBoolean, true, false, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000081 {}, "If true, regular expression alias commands will show the "
Kate Stoneb9c1b512016-09-06 20:57:50 +000082 "expanded command that will be executed. This can be used to "
83 "debug new regular expression alias commands."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000084 {"prompt-on-quit", OptionValue::eTypeBoolean, true, true, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +000085 "If true, LLDB will prompt you before quitting if there are any live "
86 "processes being debugged. If false, LLDB will quit without asking in any "
87 "case."},
88 {"stop-command-source-on-error", OptionValue::eTypeBoolean, true, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000089 nullptr, {}, "If true, LLDB will stop running a 'command source' "
90 "script upon encountering an error."},
91 {"space-repl-prompts", OptionValue::eTypeBoolean, true, false, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +000092 "If true, blank lines will be printed between between REPL submissions."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000093 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, {}, nullptr}};
Kate Stoneb9c1b512016-09-06 20:57:50 +000094
95enum {
96 ePropertyExpandRegexAliases = 0,
97 ePropertyPromptOnQuit = 1,
98 ePropertyStopCmdSourceOnError = 2,
99 eSpaceReplPrompts = 3
Greg Clayton754a9362012-08-23 00:22:02 +0000100};
101
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102ConstString &CommandInterpreter::GetStaticBroadcasterClass() {
103 static ConstString class_name("lldb.commandInterpreter");
104 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000105}
106
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107CommandInterpreter::CommandInterpreter(Debugger &debugger,
108 ScriptLanguage script_language,
109 bool synchronous_execution)
110 : Broadcaster(debugger.GetBroadcasterManager(),
111 CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
112 Properties(OptionValuePropertiesSP(
113 new OptionValueProperties(ConstString("interpreter")))),
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000114 IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000115 m_debugger(debugger), m_synchronous_execution(synchronous_execution),
116 m_skip_lldbinit_files(false), m_skip_app_init_files(false),
117 m_script_interpreter_sp(), m_command_io_handler_sp(), m_comment_char('#'),
118 m_batch_command_mode(false), m_truncation_warning(eNoTruncation),
119 m_command_source_depth(0), m_num_errors(0), m_quit_requested(false),
120 m_stopped_for_crash(false) {
121 debugger.SetScriptLanguage(script_language);
122 SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit");
123 SetEventName(eBroadcastBitResetPrompt, "reset-prompt");
124 SetEventName(eBroadcastBitQuitCommandReceived, "quit");
125 CheckInWithManager();
126 m_collection_sp->Initialize(g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000127}
128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129bool CommandInterpreter::GetExpandRegexAliases() const {
130 const uint32_t idx = ePropertyExpandRegexAliases;
131 return m_collection_sp->GetPropertyAtIndexAsBoolean(
132 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000133}
134
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135bool CommandInterpreter::GetPromptOnQuit() const {
136 const uint32_t idx = ePropertyPromptOnQuit;
137 return m_collection_sp->GetPropertyAtIndexAsBoolean(
138 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000139}
Greg Clayton754a9362012-08-23 00:22:02 +0000140
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141void CommandInterpreter::SetPromptOnQuit(bool b) {
142 const uint32_t idx = ePropertyPromptOnQuit;
143 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ilia Kacf28be2015-03-23 22:45:13 +0000144}
145
Raphael Isemannc094d232018-07-11 17:18:01 +0000146void CommandInterpreter::AllowExitCodeOnQuit(bool allow) {
147 m_allow_exit_code = allow;
148 if (!allow)
149 m_quit_exit_code.reset();
150}
151
152bool CommandInterpreter::SetQuitExitCode(int exit_code) {
153 if (!m_allow_exit_code)
154 return false;
155 m_quit_exit_code = exit_code;
156 return true;
157}
158
159int CommandInterpreter::GetQuitExitCode(bool &exited) const {
160 exited = m_quit_exit_code.hasValue();
161 if (exited)
162 return *m_quit_exit_code;
163 return 0;
164}
165
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166void CommandInterpreter::ResolveCommand(const char *command_line,
167 CommandReturnObject &result) {
168 std::string command = command_line;
169 if (ResolveCommandImpl(command, result) != nullptr) {
170 result.AppendMessageWithFormat("%s", command.c_str());
171 result.SetStatus(eReturnStatusSuccessFinishResult);
172 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000173}
174
Kate Stoneb9c1b512016-09-06 20:57:50 +0000175bool CommandInterpreter::GetStopCmdSourceOnError() const {
176 const uint32_t idx = ePropertyStopCmdSourceOnError;
177 return m_collection_sp->GetPropertyAtIndexAsBoolean(
178 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000179}
180
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181bool CommandInterpreter::GetSpaceReplPrompts() const {
182 const uint32_t idx = eSpaceReplPrompts;
183 return m_collection_sp->GetPropertyAtIndexAsBoolean(
184 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callanan66810412015-10-19 23:11:07 +0000185}
186
Kate Stoneb9c1b512016-09-06 20:57:50 +0000187void CommandInterpreter::Initialize() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000188 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
189 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000190
Kate Stoneb9c1b512016-09-06 20:57:50 +0000191 CommandReturnObject result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000192
Kate Stoneb9c1b512016-09-06 20:57:50 +0000193 LoadCommandDictionary();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195 // An alias arguments vector to reuse - reset it before use...
196 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
197
198 // Set up some initial aliases.
199 CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
200 if (cmd_obj_sp) {
201 AddAlias("q", cmd_obj_sp);
202 AddAlias("exit", cmd_obj_sp);
203 }
204
205 cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
206 if (cmd_obj_sp)
207 AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
208
209 cmd_obj_sp = GetCommandSPExact("process detach", false);
210 if (cmd_obj_sp) {
211 AddAlias("detach", cmd_obj_sp);
212 }
213
214 cmd_obj_sp = GetCommandSPExact("process continue", false);
215 if (cmd_obj_sp) {
216 AddAlias("c", cmd_obj_sp);
217 AddAlias("continue", cmd_obj_sp);
218 }
219
220 cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
221 if (cmd_obj_sp)
222 AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
223
224 cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
225 if (cmd_obj_sp)
226 AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
227
228 cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
229 if (cmd_obj_sp) {
230 AddAlias("stepi", cmd_obj_sp);
231 AddAlias("si", cmd_obj_sp);
232 }
233
234 cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
235 if (cmd_obj_sp) {
236 AddAlias("nexti", cmd_obj_sp);
237 AddAlias("ni", cmd_obj_sp);
238 }
239
240 cmd_obj_sp = GetCommandSPExact("thread step-in", false);
241 if (cmd_obj_sp) {
242 AddAlias("s", cmd_obj_sp);
243 AddAlias("step", cmd_obj_sp);
244 CommandAlias *sif_alias = AddAlias(
245 "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
246 if (sif_alias) {
247 sif_alias->SetHelp("Step through the current block, stopping if you step "
248 "directly into a function whose name matches the "
249 "TargetFunctionName.");
250 sif_alias->SetSyntax("sif <TargetFunctionName>");
Caroline Ticeca90c472011-05-06 21:37:15 +0000251 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000252 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000253
Kate Stoneb9c1b512016-09-06 20:57:50 +0000254 cmd_obj_sp = GetCommandSPExact("thread step-over", false);
255 if (cmd_obj_sp) {
256 AddAlias("n", cmd_obj_sp);
257 AddAlias("next", cmd_obj_sp);
258 }
259
260 cmd_obj_sp = GetCommandSPExact("thread step-out", false);
261 if (cmd_obj_sp) {
262 AddAlias("finish", cmd_obj_sp);
263 }
264
265 cmd_obj_sp = GetCommandSPExact("frame select", false);
266 if (cmd_obj_sp) {
267 AddAlias("f", cmd_obj_sp);
268 }
269
270 cmd_obj_sp = GetCommandSPExact("thread select", false);
271 if (cmd_obj_sp) {
272 AddAlias("t", cmd_obj_sp);
273 }
274
275 cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
276 if (cmd_obj_sp) {
277 AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
278 AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
279 }
280
281 cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
282 if (cmd_obj_sp) {
283 AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
284 AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
285 }
286
287 cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
288 if (cmd_obj_sp)
289 AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
290
291 cmd_obj_sp = GetCommandSPExact("memory read", false);
292 if (cmd_obj_sp)
293 AddAlias("x", cmd_obj_sp);
294
295 cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
296 if (cmd_obj_sp)
297 AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
298
299 cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
300 if (cmd_obj_sp)
301 AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
302
303 cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
304 if (cmd_obj_sp)
305 AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
306
307 cmd_obj_sp = GetCommandSPExact("disassemble", false);
308 if (cmd_obj_sp)
309 AddAlias("dis", cmd_obj_sp);
310
311 cmd_obj_sp = GetCommandSPExact("disassemble", false);
312 if (cmd_obj_sp)
313 AddAlias("di", cmd_obj_sp);
314
315 cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
316 if (cmd_obj_sp)
317 AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
318
319 cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
320 if (cmd_obj_sp)
321 AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
322
323 cmd_obj_sp = GetCommandSPExact("target create", false);
324 if (cmd_obj_sp)
325 AddAlias("file", cmd_obj_sp);
326
327 cmd_obj_sp = GetCommandSPExact("target modules", false);
328 if (cmd_obj_sp)
329 AddAlias("image", cmd_obj_sp);
330
331 alias_arguments_vector_sp.reset(new OptionArgVector);
332
333 cmd_obj_sp = GetCommandSPExact("expression", false);
334 if (cmd_obj_sp) {
335 AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
336 AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
337 AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
338 if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
339 po->SetHelp("Evaluate an expression on the current thread. Displays any "
340 "returned value with formatting "
341 "controlled by the type's author.");
342 po->SetHelpLong("");
Johnny Chen6d675242012-08-24 18:15:45 +0000343 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
345 AddAlias("poarray", cmd_obj_sp,
346 "--object-description --element-count %1 --")
347 ->SetHelpLong("");
348 }
Johnny Chen6d675242012-08-24 18:15:45 +0000349
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350 cmd_obj_sp = GetCommandSPExact("process kill", false);
351 if (cmd_obj_sp) {
352 AddAlias("kill", cmd_obj_sp);
353 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000354
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 cmd_obj_sp = GetCommandSPExact("process launch", false);
356 if (cmd_obj_sp) {
Chaoren Lin6fc5c7f2016-02-26 03:36:27 +0000357 alias_arguments_vector_sp.reset(new OptionArgVector);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
359 AddAlias("r", cmd_obj_sp, "--");
360 AddAlias("run", cmd_obj_sp, "--");
Jason Molenda85da3122012-07-06 02:46:23 +0000361#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362#if defined(__APPLE__)
363 std::string shell_option;
364 shell_option.append("--shell-expand-args");
365 shell_option.append(" true");
366 shell_option.append(" --");
367 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
368 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
369#else
370 StreamString defaultshell;
371 defaultshell.Printf("--shell=%s --",
372 HostInfo::GetDefaultShell().GetPath().c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +0000373 AddAlias("r", cmd_obj_sp, defaultshell.GetString());
374 AddAlias("run", cmd_obj_sp, defaultshell.GetString());
Jason Molenda85da3122012-07-06 02:46:23 +0000375#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000376#endif
377 }
378
379 cmd_obj_sp = GetCommandSPExact("target symbols add", false);
380 if (cmd_obj_sp) {
381 AddAlias("add-dsym", cmd_obj_sp);
382 }
383
384 cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
385 if (cmd_obj_sp) {
386 AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
387 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000388}
389
Kate Stoneb9c1b512016-09-06 20:57:50 +0000390void CommandInterpreter::Clear() {
391 m_command_io_handler_sp.reset();
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000392
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 if (m_script_interpreter_sp)
394 m_script_interpreter_sp->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000395}
396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
398 // This function has not yet been implemented.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000399
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400 // Look for any embedded script command
401 // If found,
402 // get interpreter object from the command dictionary,
403 // call execute_one_command on it,
404 // get the results as a string,
405 // substitute that string for current stuff.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000406
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407 return arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000408}
409
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410void CommandInterpreter::LoadCommandDictionary() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000411 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
412 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000413
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000415
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
417 m_command_dict["breakpoint"] =
418 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
419 m_command_dict["bugreport"] =
420 CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
421 m_command_dict["command"] =
422 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
423 m_command_dict["disassemble"] =
424 CommandObjectSP(new CommandObjectDisassemble(*this));
425 m_command_dict["expression"] =
426 CommandObjectSP(new CommandObjectExpression(*this));
427 m_command_dict["frame"] =
428 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
429 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
430 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
431 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
432 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
433 m_command_dict["platform"] =
434 CommandObjectSP(new CommandObjectPlatform(*this));
435 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
436 m_command_dict["process"] =
437 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
438 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
439 m_command_dict["register"] =
440 CommandObjectSP(new CommandObjectRegister(*this));
441 m_command_dict["script"] =
442 CommandObjectSP(new CommandObjectScript(*this, script_language));
443 m_command_dict["settings"] =
444 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
445 m_command_dict["source"] =
446 CommandObjectSP(new CommandObjectMultiwordSource(*this));
Davide Italiano24fff242018-04-13 18:02:39 +0000447 m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448 m_command_dict["target"] =
449 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
450 m_command_dict["thread"] =
451 CommandObjectSP(new CommandObjectMultiwordThread(*this));
452 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
453 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
454 m_command_dict["watchpoint"] =
455 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
456 m_command_dict["language"] =
457 CommandObjectSP(new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000458
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459 const char *break_regexes[][2] = {
460 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
461 "breakpoint set --file '%1' --line %2"},
462 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
463 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
464 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
465 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
466 "breakpoint set --name '%1'"},
467 {"^(-.*)$", "breakpoint set %1"},
468 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
469 "breakpoint set --name '%2' --shlib '%1'"},
470 {"^\\&(.*[^[:space:]])[[:space:]]*$",
471 "breakpoint set --name '%1' --skip-prologue=0"},
472 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
473 "breakpoint set --name '%1'"}};
Kate Stone7428a182016-07-14 22:03:10 +0000474
Kate Stoneb9c1b512016-09-06 20:57:50 +0000475 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000476
Kate Stoneb9c1b512016-09-06 20:57:50 +0000477 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap(
478 new CommandObjectRegexCommand(
479 *this, "_regexp-break",
Raphael Isemann129fe892018-07-30 21:41:13 +0000480 "Set a breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000481 "\n"
482 "_regexp-break <filename>:<linenum>\n"
483 " main.c:12 // Break at line 12 of "
484 "main.c\n\n"
485 "_regexp-break <linenum>\n"
486 " 12 // Break at line 12 of current "
487 "file\n\n"
488 "_regexp-break 0x<address>\n"
489 " 0x1234000 // Break at address "
490 "0x1234000\n\n"
491 "_regexp-break <name>\n"
492 " main // Break in 'main' after the "
493 "prologue\n\n"
494 "_regexp-break &<name>\n"
495 " &main // Break at first instruction "
496 "in 'main'\n\n"
497 "_regexp-break <module>`<name>\n"
498 " libc.so`malloc // Break in 'malloc' from "
499 "'libc.so'\n\n"
500 "_regexp-break /<source-regex>/\n"
501 " /break here/ // Break on source lines in "
502 "current file\n"
503 " // containing text 'break "
504 "here'.\n",
505 2, CommandCompletions::eSymbolCompletion |
506 CommandCompletions::eSourceFileCompletion,
507 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000508
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509 if (break_regex_cmd_ap.get()) {
510 bool success = true;
511 for (size_t i = 0; i < num_regexes; i++) {
512 success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0],
513 break_regexes[i][1]);
514 if (!success)
515 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000516 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517 success =
518 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Jim Inghamffba2292011-03-22 02:29:32 +0000519
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520 if (success) {
521 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
522 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
Jim Inghamca36cd12012-10-05 19:16:31 +0000523 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524 }
Jim Inghamca36cd12012-10-05 19:16:31 +0000525
Kate Stoneb9c1b512016-09-06 20:57:50 +0000526 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap(
527 new CommandObjectRegexCommand(
528 *this, "_regexp-tbreak",
Raphael Isemann129fe892018-07-30 21:41:13 +0000529 "Set a one-shot breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530 "\n"
531 "_regexp-break <filename>:<linenum>\n"
532 " main.c:12 // Break at line 12 of "
533 "main.c\n\n"
534 "_regexp-break <linenum>\n"
535 " 12 // Break at line 12 of current "
536 "file\n\n"
537 "_regexp-break 0x<address>\n"
538 " 0x1234000 // Break at address "
539 "0x1234000\n\n"
540 "_regexp-break <name>\n"
541 " main // Break in 'main' after the "
542 "prologue\n\n"
543 "_regexp-break &<name>\n"
544 " &main // Break at first instruction "
545 "in 'main'\n\n"
546 "_regexp-break <module>`<name>\n"
547 " libc.so`malloc // Break in 'malloc' from "
548 "'libc.so'\n\n"
549 "_regexp-break /<source-regex>/\n"
550 " /break here/ // Break on source lines in "
551 "current file\n"
552 " // containing text 'break "
553 "here'.\n",
554 2, CommandCompletions::eSymbolCompletion |
555 CommandCompletions::eSourceFileCompletion,
556 false));
557
558 if (tbreak_regex_cmd_ap.get()) {
559 bool success = true;
560 for (size_t i = 0; i < num_regexes; i++) {
561 // If you add a resultant command string longer than 1024 characters be
562 // sure to increase the size of this buffer.
563 char buffer[1024];
564 int num_printed =
Frederic Riss49c9d8b2018-06-18 04:34:33 +0000565 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1");
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000566 lldbassert(num_printed < 1024);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567 UNUSED_IF_ASSERT_DISABLED(num_printed);
568 success =
569 tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer);
570 if (!success)
571 break;
Johnny Chen6d675242012-08-24 18:15:45 +0000572 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000573 success =
574 tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Kate Stone7428a182016-07-14 22:03:10 +0000575
Kate Stoneb9c1b512016-09-06 20:57:50 +0000576 if (success) {
577 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
578 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
579 tbreak_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000580 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000581 }
Kate Stone7428a182016-07-14 22:03:10 +0000582
Kate Stoneb9c1b512016-09-06 20:57:50 +0000583 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap(
584 new CommandObjectRegexCommand(
585 *this, "_regexp-attach", "Attach to process by ID or name.",
586 "_regexp-attach <pid> | <process-name>", 2, 0, false));
587 if (attach_regex_cmd_ap.get()) {
588 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
589 "process attach --pid %1") &&
590 attach_regex_cmd_ap->AddRegexCommand(
591 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
592 // specified get passed to
593 // 'process attach'
594 attach_regex_cmd_ap->AddRegexCommand("^(.+)$",
595 "process attach --name '%1'") &&
596 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) {
597 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
598 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
599 attach_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000600 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000601 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000602
Kate Stoneb9c1b512016-09-06 20:57:50 +0000603 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap(
604 new CommandObjectRegexCommand(*this, "_regexp-down",
605 "Select a newer stack frame. Defaults to "
606 "moving one frame, a numeric argument can "
607 "specify an arbitrary number.",
608 "_regexp-down [<count>]", 2, 0, false));
609 if (down_regex_cmd_ap.get()) {
610 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
611 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
612 "frame select -r -%1")) {
613 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
614 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000615 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000616 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000617
Kate Stoneb9c1b512016-09-06 20:57:50 +0000618 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap(
619 new CommandObjectRegexCommand(
620 *this, "_regexp-up",
621 "Select an older stack frame. Defaults to moving one "
622 "frame, a numeric argument can specify an arbitrary number.",
623 "_regexp-up [<count>]", 2, 0, false));
624 if (up_regex_cmd_ap.get()) {
625 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
626 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
627 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
628 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000629 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000631
Kate Stoneb9c1b512016-09-06 20:57:50 +0000632 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap(
633 new CommandObjectRegexCommand(
634 *this, "_regexp-display",
635 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
636 "_regexp-display expression", 2, 0, false));
637 if (display_regex_cmd_ap.get()) {
638 if (display_regex_cmd_ap->AddRegexCommand(
639 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
640 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
641 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
642 display_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000643 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000645
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap(
647 new CommandObjectRegexCommand(
648 *this, "_regexp-undisplay", "Stop displaying expression at every "
649 "stop (specified by stop-hook index.)",
650 "_regexp-undisplay stop-hook-number", 2, 0, false));
651 if (undisplay_regex_cmd_ap.get()) {
652 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
653 "target stop-hook delete %1")) {
654 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
655 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
656 undisplay_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000657 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000659
Kate Stoneb9c1b512016-09-06 20:57:50 +0000660 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap(
661 new CommandObjectRegexCommand(
662 *this, "gdb-remote", "Connect to a process via remote GDB server. "
663 "If no host is specifed, localhost is assumed.",
664 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
665 if (connect_gdb_remote_cmd_ap.get()) {
666 if (connect_gdb_remote_cmd_ap->AddRegexCommand(
Chris Bieneman51978f52017-04-27 16:13:58 +0000667 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
668 "process connect --plugin gdb-remote connect://%1:%2") &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000669 connect_gdb_remote_cmd_ap->AddRegexCommand(
670 "^([[:digit:]]+)$",
671 "process connect --plugin gdb-remote connect://localhost:%1")) {
672 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
673 m_command_dict[command_sp->GetCommandName()] = command_sp;
Jason Molenda4cddfed2012-10-05 05:29:32 +0000674 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000675 }
Jason Molenda4cddfed2012-10-05 05:29:32 +0000676
Kate Stoneb9c1b512016-09-06 20:57:50 +0000677 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap(
678 new CommandObjectRegexCommand(
679 *this, "kdp-remote", "Connect to a process via remote KDP server. "
680 "If no UDP port is specified, port 41139 is "
681 "assumed.",
682 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
683 if (connect_kdp_remote_cmd_ap.get()) {
684 if (connect_kdp_remote_cmd_ap->AddRegexCommand(
685 "^([^:]+:[[:digit:]]+)$",
686 "process connect --plugin kdp-remote udp://%1") &&
687 connect_kdp_remote_cmd_ap->AddRegexCommand(
688 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
689 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
690 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Clayton6bade322013-02-01 23:33:03 +0000691 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692 }
Greg Clayton6bade322013-02-01 23:33:03 +0000693
Kate Stoneb9c1b512016-09-06 20:57:50 +0000694 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap(
695 new CommandObjectRegexCommand(
696 *this, "_regexp-bt",
697 "Show the current thread's call stack. Any numeric argument "
698 "displays at most that many "
699 "frames. The argument 'all' displays all threads.",
700 "bt [<digit> | all]", 2, 0, false));
701 if (bt_regex_cmd_ap.get()) {
702 // accept but don't document "bt -c <number>" -- before bt was a regex
Adrian Prantl05097242018-04-30 16:49:04 +0000703 // command if you wanted to backtrace three frames you would do "bt -c 3"
704 // but the intention is to have this emulate the gdb "bt" command and so
705 // now "bt 3" is the preferred form, in line with gdb.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000706 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$",
707 "thread backtrace -c %1") &&
708 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$",
709 "thread backtrace -c %1") &&
710 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
711 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) {
712 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
713 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Claytonef5651d2013-02-12 18:52:24 +0000714 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000715 }
Greg Claytonef5651d2013-02-12 18:52:24 +0000716
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap(
718 new CommandObjectRegexCommand(
719 *this, "_regexp-list",
720 "List relevant source code using one of several shorthand formats.",
721 "\n"
722 "_regexp-list <file>:<line> // List around specific file/line\n"
723 "_regexp-list <line> // List current file around specified "
724 "line\n"
725 "_regexp-list <function-name> // List specified function\n"
726 "_regexp-list 0x<address> // List around specified address\n"
727 "_regexp-list -[<count>] // List previous <count> lines\n"
728 "_regexp-list // List subsequent lines",
729 2, CommandCompletions::eSourceFileCompletion, false));
730 if (list_regex_cmd_ap.get()) {
731 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
732 "source list --line %1") &&
733 list_regex_cmd_ap->AddRegexCommand(
734 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
735 "]*$",
736 "source list --file '%1' --line %2") &&
737 list_regex_cmd_ap->AddRegexCommand(
738 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
739 "source list --address %1") &&
740 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$",
741 "source list --reverse") &&
742 list_regex_cmd_ap->AddRegexCommand(
743 "^-([[:digit:]]+)[[:space:]]*$",
744 "source list --reverse --count %1") &&
745 list_regex_cmd_ap->AddRegexCommand("^(.+)$",
746 "source list --name \"%1\"") &&
747 list_regex_cmd_ap->AddRegexCommand("^$", "source list")) {
748 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
749 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
Richard Mittonf86248d2013-09-12 02:20:34 +0000750 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000751 }
Richard Mittonf86248d2013-09-12 02:20:34 +0000752
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap(
754 new CommandObjectRegexCommand(
755 *this, "_regexp-env",
756 "Shorthand for viewing and setting environment variables.",
757 "\n"
758 "_regexp-env // Show enrivonment\n"
759 "_regexp-env <name>=<value> // Set an environment variable",
760 2, 0, false));
761 if (env_regex_cmd_ap.get()) {
762 if (env_regex_cmd_ap->AddRegexCommand("^$",
763 "settings show target.env-vars") &&
764 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
765 "settings set target.env-vars %1")) {
766 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
767 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
768 }
769 }
770
771 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap(
772 new CommandObjectRegexCommand(
773 *this, "_regexp-jump", "Set the program counter to a new address.",
774 "\n"
775 "_regexp-jump <line>\n"
776 "_regexp-jump +<line-offset> | -<line-offset>\n"
777 "_regexp-jump <file>:<line>\n"
778 "_regexp-jump *<addr>\n",
779 2, 0, false));
780 if (jump_regex_cmd_ap.get()) {
781 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$",
782 "thread jump --addr %1") &&
783 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
784 "thread jump --line %1") &&
785 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$",
786 "thread jump --file %1 --line %2") &&
787 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$",
788 "thread jump --by %1")) {
789 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
790 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
791 }
792 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000793}
794
Kate Stoneb9c1b512016-09-06 20:57:50 +0000795int CommandInterpreter::GetCommandNamesMatchingPartialString(
Raphael Isemann7f888292018-09-13 21:26:00 +0000796 const char *cmd_str, bool include_aliases, StringList &matches,
797 StringList &descriptions) {
798 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches,
799 &descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000800
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801 if (include_aliases) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000802 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches,
803 &descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000804 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000805
Kate Stoneb9c1b512016-09-06 20:57:50 +0000806 return matches.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000807}
808
Raphael Isemann7f888292018-09-13 21:26:00 +0000809CommandObjectSP
810CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases,
811 bool exact, StringList *matches,
812 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000814
Zachary Turnera4496982016-10-05 21:14:38 +0000815 std::string cmd = cmd_str;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000816
Kate Stoneb9c1b512016-09-06 20:57:50 +0000817 if (HasCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000818 auto pos = m_command_dict.find(cmd);
Greg Claytonb5472782015-01-09 19:08:20 +0000819 if (pos != m_command_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000820 command_sp = pos->second;
821 }
822
823 if (include_aliases && HasAliases()) {
824 auto alias_pos = m_alias_dict.find(cmd);
825 if (alias_pos != m_alias_dict.end())
826 command_sp = alias_pos->second;
827 }
828
829 if (HasUserCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000830 auto pos = m_user_dict.find(cmd);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000831 if (pos != m_user_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000832 command_sp = pos->second;
833 }
834
835 if (!exact && !command_sp) {
836 // We will only get into here if we didn't find any exact matches.
837
838 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
839
840 StringList local_matches;
841 if (matches == nullptr)
842 matches = &local_matches;
843
844 unsigned int num_cmd_matches = 0;
845 unsigned int num_alias_matches = 0;
846 unsigned int num_user_matches = 0;
847
848 // Look through the command dictionaries one by one, and if we get only one
Adrian Prantl05097242018-04-30 16:49:04 +0000849 // match from any of them in toto, then return that, otherwise return an
850 // empty CommandObjectSP and the list of matches.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851
852 if (HasCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000853 num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str,
854 *matches, descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000855 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000856
857 if (num_cmd_matches == 1) {
858 cmd.assign(matches->GetStringAtIndex(0));
Zachary Turnera4496982016-10-05 21:14:38 +0000859 auto pos = m_command_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860 if (pos != m_command_dict.end())
861 real_match_sp = pos->second;
862 }
863
864 if (include_aliases && HasAliases()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000865 num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str,
866 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000867 }
868
869 if (num_alias_matches == 1) {
870 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
871 auto alias_pos = m_alias_dict.find(cmd);
872 if (alias_pos != m_alias_dict.end())
873 alias_match_sp = alias_pos->second;
874 }
875
876 if (HasUserCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000877 num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str,
878 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879 }
880
881 if (num_user_matches == 1) {
882 cmd.assign(
883 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
884
Zachary Turnera4496982016-10-05 21:14:38 +0000885 auto pos = m_user_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000886 if (pos != m_user_dict.end())
887 user_match_sp = pos->second;
888 }
889
890 // If we got exactly one match, return that, otherwise return the match
891 // list.
892
893 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
894 if (num_cmd_matches)
895 return real_match_sp;
896 else if (num_alias_matches)
897 return alias_match_sp;
898 else
899 return user_match_sp;
900 }
901 } else if (matches && command_sp) {
Zachary Turnera4496982016-10-05 21:14:38 +0000902 matches->AppendString(cmd_str);
Raphael Isemann7f888292018-09-13 21:26:00 +0000903 if (descriptions)
904 descriptions->AppendString(command_sp->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000905 }
906
907 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000908}
909
Zachary Turnera4496982016-10-05 21:14:38 +0000910bool CommandInterpreter::AddCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000911 const lldb::CommandObjectSP &cmd_sp,
912 bool can_replace) {
913 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000914 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
915 "tried to add a CommandObject from a different interpreter");
Kate Stonea487aa42015-01-15 00:52:41 +0000916
Zachary Turnera4496982016-10-05 21:14:38 +0000917 if (name.empty())
918 return false;
919
920 std::string name_sstr(name);
921 auto name_iter = m_command_dict.find(name_sstr);
922 if (name_iter != m_command_dict.end()) {
923 if (!can_replace || !name_iter->second->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 return false;
Zachary Turnera4496982016-10-05 21:14:38 +0000925 name_iter->second = cmd_sp;
926 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000927 m_command_dict[name_sstr] = cmd_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000928 }
Zachary Turnera4496982016-10-05 21:14:38 +0000929 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000930}
931
Zachary Turnera483f572016-10-05 21:14:49 +0000932bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000933 const lldb::CommandObjectSP &cmd_sp,
934 bool can_replace) {
935 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000936 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
937 "tried to add a CommandObject from a different interpreter");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000938
Kate Stoneb9c1b512016-09-06 20:57:50 +0000939 if (!name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000940 // do not allow replacement of internal commands
Zachary Turnera483f572016-10-05 21:14:49 +0000941 if (CommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942 if (can_replace == false)
943 return false;
944 if (m_command_dict[name]->IsRemovable() == false)
Greg Clayton5a314712011-10-14 07:41:33 +0000945 return false;
946 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000947
Zachary Turnera483f572016-10-05 21:14:49 +0000948 if (UserCommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949 if (can_replace == false)
950 return false;
951 if (m_user_dict[name]->IsRemovable() == false)
952 return false;
Caroline Tice844d2302010-12-09 22:52:49 +0000953 }
954
Kate Stoneb9c1b512016-09-06 20:57:50 +0000955 m_user_dict[name] = cmd_sp;
956 return true;
957 }
958 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000959}
960
Zachary Turnera4496982016-10-05 21:14:38 +0000961CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
962 bool include_aliases) const {
963 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964 // it's a multi-word command.
965 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000966
Zachary Turnera4496982016-10-05 21:14:38 +0000967 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968 return ret_val;
969
970 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +0000971 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000972 else {
973 // We have a multi-word command (seemingly), so we need to do more work.
974 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +0000975 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 include_aliases, true, nullptr);
977 if (cmd_obj_sp.get() != nullptr) {
Adrian Prantl05097242018-04-30 16:49:04 +0000978 // Loop through the rest of the words in the command (everything passed
979 // in was supposed to be part of a command name), and find the
980 // appropriate sub-command SP for each command word....
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 size_t end = cmd_words.GetArgumentCount();
982 for (size_t j = 1; j < end; ++j) {
983 if (cmd_obj_sp->IsMultiwordObject()) {
984 cmd_obj_sp =
985 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
986 if (cmd_obj_sp.get() == nullptr)
987 // The sub-command name was invalid. Fail and return the empty
988 // 'ret_val'.
989 return ret_val;
990 } else
991 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +0000992 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993 return ret_val;
994 }
995 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +0000996 // command objects for them. Assign the last object retrieved to
997 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000999 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 }
1001 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001002}
1003
Raphael Isemann7f888292018-09-13 21:26:00 +00001004CommandObject *
1005CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
1006 StringList *matches,
1007 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001008 CommandObject *command_obj =
Raphael Isemann7f888292018-09-13 21:26:00 +00001009 GetCommandSP(cmd_str, false, true, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001010
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011 // If we didn't find an exact match to the command string in the commands,
Adrian Prantl05097242018-04-30 16:49:04 +00001012 // look in the aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001013
1014 if (command_obj)
1015 return command_obj;
1016
Raphael Isemann7f888292018-09-13 21:26:00 +00001017 command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018
1019 if (command_obj)
1020 return command_obj;
1021
1022 // If there wasn't an exact match then look for an inexact one in just the
1023 // commands
Zachary Turnera4496982016-10-05 21:14:38 +00001024 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001025
1026 // Finally, if there wasn't an inexact match among the commands, look for an
Adrian Prantl05097242018-04-30 16:49:04 +00001027 // inexact match in both the commands and aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001028
1029 if (command_obj) {
1030 if (matches)
1031 matches->AppendString(command_obj->GetCommandName());
Raphael Isemann7f888292018-09-13 21:26:00 +00001032 if (descriptions)
1033 descriptions->AppendString(command_obj->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001034 return command_obj;
1035 }
1036
Raphael Isemann7f888292018-09-13 21:26:00 +00001037 return GetCommandSP(cmd_str, true, false, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001038}
1039
Zachary Turnera483f572016-10-05 21:14:49 +00001040bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001041 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001042}
1043
Zachary Turnera483f572016-10-05 21:14:49 +00001044bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1045 std::string &full_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001046 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1047 if (exact_match) {
1048 full_name.assign(cmd);
1049 return exact_match;
1050 } else {
1051 StringList matches;
1052 size_t num_alias_matches;
1053 num_alias_matches =
1054 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1055 if (num_alias_matches == 1) {
1056 // Make sure this isn't shadowing a command in the regular command space:
1057 StringList regular_matches;
1058 const bool include_aliases = false;
1059 const bool exact = false;
1060 CommandObjectSP cmd_obj_sp(
1061 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1062 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1063 return false;
1064 else {
1065 full_name.assign(matches.GetStringAtIndex(0));
1066 return true;
1067 }
1068 } else
1069 return false;
1070 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071}
1072
Zachary Turnera483f572016-10-05 21:14:49 +00001073bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001074 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001075}
1076
Zachary Turnera483f572016-10-05 21:14:49 +00001077bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001078 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001079}
1080
Kate Stoneb9c1b512016-09-06 20:57:50 +00001081CommandAlias *
Zachary Turnera483f572016-10-05 21:14:49 +00001082CommandInterpreter::AddAlias(llvm::StringRef alias_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001083 lldb::CommandObjectSP &command_obj_sp,
Zachary Turnera483f572016-10-05 21:14:49 +00001084 llvm::StringRef args_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001085 if (command_obj_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001086 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1087 "tried to add a CommandObject from a different interpreter");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001088
1089 std::unique_ptr<CommandAlias> command_alias_up(
1090 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1091
1092 if (command_alias_up && command_alias_up->IsValid()) {
1093 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1094 return command_alias_up.release();
1095 }
1096
1097 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001098}
1099
Zachary Turnera483f572016-10-05 21:14:49 +00001100bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001101 auto pos = m_alias_dict.find(alias_name);
1102 if (pos != m_alias_dict.end()) {
1103 m_alias_dict.erase(pos);
1104 return true;
1105 }
1106 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001107}
1108
Zachary Turnera483f572016-10-05 21:14:49 +00001109bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001110 auto pos = m_command_dict.find(cmd);
1111 if (pos != m_command_dict.end()) {
1112 if (pos->second->IsRemovable()) {
1113 // Only regular expression objects or python commands are removable
1114 m_command_dict.erase(pos);
1115 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001117 }
1118 return false;
1119}
Zachary Turnera483f572016-10-05 21:14:49 +00001120bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001121 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1122 if (pos != m_user_dict.end()) {
1123 m_user_dict.erase(pos);
1124 return true;
1125 }
1126 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001127}
1128
Kate Stoneb9c1b512016-09-06 20:57:50 +00001129void CommandInterpreter::GetHelp(CommandReturnObject &result,
1130 uint32_t cmd_types) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001131 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1132 if (!help_prologue.empty()) {
1133 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1134 help_prologue);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001135 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001136
Kate Stoneb9c1b512016-09-06 20:57:50 +00001137 CommandObject::CommandMap::const_iterator pos;
1138 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001139
Kate Stoneb9c1b512016-09-06 20:57:50 +00001140 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1141 result.AppendMessage("Debugger commands:");
1142 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001143
Kate Stoneb9c1b512016-09-06 20:57:50 +00001144 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1145 if (!(cmd_types & eCommandTypesHidden) &&
1146 (pos->first.compare(0, 1, "_") == 0))
1147 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001148
Zachary Turner0ac5f982016-11-08 04:12:42 +00001149 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1150 pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001151 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001152 result.AppendMessage("");
1153 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001154
Kate Stoneb9c1b512016-09-06 20:57:50 +00001155 if (!m_alias_dict.empty() &&
1156 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1157 result.AppendMessageWithFormat(
1158 "Current command abbreviations "
1159 "(type '%shelp command alias' for more info):\n",
1160 GetCommandPrefix());
1161 result.AppendMessage("");
1162 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001163
Kate Stoneb9c1b512016-09-06 20:57:50 +00001164 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1165 ++alias_pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001166 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
Kate Stoneb9c1b512016-09-06 20:57:50 +00001167 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001168 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001169 result.AppendMessage("");
1170 }
Greg Clayton14a35512011-09-11 00:01:44 +00001171
Kate Stoneb9c1b512016-09-06 20:57:50 +00001172 if (!m_user_dict.empty() &&
1173 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1174 result.AppendMessage("Current user-defined commands:");
1175 result.AppendMessage("");
1176 max_len = FindLongestCommandWord(m_user_dict);
1177 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001178 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1179 pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001180 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001181 result.AppendMessage("");
1182 }
Greg Clayton14a35512011-09-11 00:01:44 +00001183
Kate Stoneb9c1b512016-09-06 20:57:50 +00001184 result.AppendMessageWithFormat(
1185 "For more information on any command, type '%shelp <command-name>'.\n",
1186 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001187}
1188
Zachary Turnera01bccd2016-10-05 21:14:56 +00001189CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1190 llvm::StringRef &command_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001191 // This function finds the final, lowest-level, alias-resolved command object
Adrian Prantl05097242018-04-30 16:49:04 +00001192 // whose 'Execute' function will eventually be invoked by the given command
1193 // line.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001194
1195 CommandObject *cmd_obj = nullptr;
1196 size_t start = command_string.find_first_not_of(k_white_space);
1197 size_t end = 0;
1198 bool done = false;
1199 while (!done) {
1200 if (start != std::string::npos) {
1201 // Get the next word from command_string.
1202 end = command_string.find_first_of(k_white_space, start);
1203 if (end == std::string::npos)
1204 end = command_string.size();
1205 std::string cmd_word = command_string.substr(start, end - start);
1206
1207 if (cmd_obj == nullptr)
1208 // Since cmd_obj is NULL we are on our first time through this loop.
Zachary Turnera01bccd2016-10-05 21:14:56 +00001209 // Check to see if cmd_word is a valid command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001210 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001211 else if (cmd_obj->IsMultiwordObject()) {
1212 // Our current object is a multi-word object; see if the cmd_word is a
1213 // valid sub-command for our object.
1214 CommandObject *sub_cmd_obj =
1215 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1216 if (sub_cmd_obj)
1217 cmd_obj = sub_cmd_obj;
1218 else // cmd_word was not a valid sub-command word, so we are done
1219 done = true;
1220 } else
1221 // We have a cmd_obj and it is not a multi-word object, so we are done.
1222 done = true;
1223
1224 // If we didn't find a valid command object, or our command object is not
Zachary Turnera01bccd2016-10-05 21:14:56 +00001225 // a multi-word object, or we are at the end of the command_string, then
1226 // we are done. Otherwise, find the start of the next word.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001227
1228 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1229 end >= command_string.size())
1230 done = true;
1231 else
1232 start = command_string.find_first_not_of(k_white_space, end);
1233 } else
1234 // Unable to find any more words.
1235 done = true;
1236 }
1237
Zachary Turnera01bccd2016-10-05 21:14:56 +00001238 command_string = command_string.substr(end);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001239 return cmd_obj;
1240}
1241
1242static const char *k_valid_command_chars =
1243 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1244static void StripLeadingSpaces(std::string &s) {
1245 if (!s.empty()) {
1246 size_t pos = s.find_first_not_of(k_white_space);
1247 if (pos == std::string::npos)
1248 s.clear();
1249 else if (pos == 0)
1250 return;
1251 s.erase(0, pos);
1252 }
1253}
1254
1255static size_t FindArgumentTerminator(const std::string &s) {
1256 const size_t s_len = s.size();
1257 size_t offset = 0;
1258 while (offset < s_len) {
1259 size_t pos = s.find("--", offset);
1260 if (pos == std::string::npos)
1261 break;
1262 if (pos > 0) {
1263 if (isspace(s[pos - 1])) {
Adrian Prantl05097242018-04-30 16:49:04 +00001264 // Check if the string ends "\s--" (where \s is a space character) or
1265 // if we have "\s--\s".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1267 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001268 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001269 }
1270 }
1271 offset = pos + 2;
1272 }
1273 return std::string::npos;
1274}
1275
1276static bool ExtractCommand(std::string &command_string, std::string &command,
1277 std::string &suffix, char &quote_char) {
1278 command.clear();
1279 suffix.clear();
1280 StripLeadingSpaces(command_string);
1281
1282 bool result = false;
1283 quote_char = '\0';
1284
1285 if (!command_string.empty()) {
1286 const char first_char = command_string[0];
1287 if (first_char == '\'' || first_char == '"') {
1288 quote_char = first_char;
1289 const size_t end_quote_pos = command_string.find(quote_char, 1);
1290 if (end_quote_pos == std::string::npos) {
1291 command.swap(command_string);
1292 command_string.erase();
1293 } else {
1294 command.assign(command_string, 1, end_quote_pos - 1);
1295 if (end_quote_pos + 1 < command_string.size())
1296 command_string.erase(0, command_string.find_first_not_of(
1297 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001298 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 command_string.erase();
1300 }
1301 } else {
1302 const size_t first_space_pos =
1303 command_string.find_first_of(k_white_space);
1304 if (first_space_pos == std::string::npos) {
1305 command.swap(command_string);
1306 command_string.erase();
1307 } else {
1308 command.assign(command_string, 0, first_space_pos);
1309 command_string.erase(0, command_string.find_first_not_of(
1310 k_white_space, first_space_pos));
1311 }
1312 }
1313 result = true;
1314 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001315
Kate Stoneb9c1b512016-09-06 20:57:50 +00001316 if (!command.empty()) {
1317 // actual commands can't start with '-' or '_'
1318 if (command[0] != '-' && command[0] != '_') {
1319 size_t pos = command.find_first_not_of(k_valid_command_chars);
1320 if (pos > 0 && pos != std::string::npos) {
1321 suffix.assign(command.begin() + pos, command.end());
1322 command.erase(pos);
1323 }
1324 }
1325 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001326
Kate Stoneb9c1b512016-09-06 20:57:50 +00001327 return result;
1328}
1329
1330CommandObject *CommandInterpreter::BuildAliasResult(
Zachary Turnera483f572016-10-05 21:14:49 +00001331 llvm::StringRef alias_name, std::string &raw_input_string,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001332 std::string &alias_result, CommandReturnObject &result) {
1333 CommandObject *alias_cmd_obj = nullptr;
1334 Args cmd_args(raw_input_string);
1335 alias_cmd_obj = GetCommandObject(alias_name);
1336 StreamString result_str;
1337
Zachary Turner5c28c662016-10-03 23:20:36 +00001338 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1339 alias_result.clear();
1340 return alias_cmd_obj;
1341 }
1342 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1343 ((CommandAlias *)alias_cmd_obj)->Desugar();
1344 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1345 alias_cmd_obj = desugared.first.get();
1346 std::string alias_name_str = alias_name;
1347 if ((cmd_args.GetArgumentCount() == 0) ||
1348 (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0))
1349 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001350
Zachary Turnera4496982016-10-05 21:14:38 +00001351 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001352
Zachary Turner5c28c662016-10-03 23:20:36 +00001353 if (!option_arg_vector_sp.get()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001354 alias_result = result_str.GetString();
Zachary Turner5c28c662016-10-03 23:20:36 +00001355 return alias_cmd_obj;
1356 }
1357 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001358
Zachary Turner5c28c662016-10-03 23:20:36 +00001359 int value_type;
1360 std::string option;
1361 std::string value;
1362 for (const auto &entry : *option_arg_vector) {
1363 std::tie(option, value_type, value) = entry;
1364 if (option == "<argument>") {
1365 result_str.Printf(" %s", value.c_str());
1366 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001367 }
1368
Zachary Turner5c28c662016-10-03 23:20:36 +00001369 result_str.Printf(" %s", option.c_str());
1370 if (value_type == OptionParser::eNoArgument)
1371 continue;
1372
1373 if (value_type != OptionParser::eOptionalArgument)
1374 result_str.Printf(" ");
1375 int index = GetOptionArgumentPosition(value.c_str());
1376 if (index == 0)
1377 result_str.Printf("%s", value.c_str());
1378 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1379
1380 result.AppendErrorWithFormat("Not enough arguments provided; you "
1381 "need at least %d arguments to use "
1382 "this alias.\n",
1383 index);
1384 result.SetStatus(eReturnStatusFailed);
1385 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001386 } else {
1387 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1388 if (strpos != std::string::npos)
1389 raw_input_string = raw_input_string.erase(
1390 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1391 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001392 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001393 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001394
Zachary Turnerc1564272016-11-16 21:15:24 +00001395 alias_result = result_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001396 return alias_cmd_obj;
1397}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001398
Zachary Turner97206d52017-05-12 04:51:55 +00001399Status CommandInterpreter::PreprocessCommand(std::string &command) {
Adrian Prantl05097242018-04-30 16:49:04 +00001400 // The command preprocessor needs to do things to the command line before any
1401 // parsing of arguments or anything else is done. The only current stuff that
1402 // gets preprocessed is anything enclosed in backtick ('`') characters is
1403 // evaluated as an expression and the result of the expression must be a
1404 // scalar that can be substituted into the command. An example would be:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001405 // (lldb) memory read `$rsp + 20`
Zachary Turner97206d52017-05-12 04:51:55 +00001406 Status error; // Status for any expressions that might not evaluate
Kate Stoneb9c1b512016-09-06 20:57:50 +00001407 size_t start_backtick;
1408 size_t pos = 0;
1409 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1410 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
Adrian Prantl05097242018-04-30 16:49:04 +00001411 // The backtick was preceded by a '\' character, remove the slash and
1412 // don't treat the backtick as the start of an expression
Kate Stoneb9c1b512016-09-06 20:57:50 +00001413 command.erase(start_backtick - 1, 1);
1414 // No need to add one to start_backtick since we just deleted a char
1415 pos = start_backtick;
1416 } else {
1417 const size_t expr_content_start = start_backtick + 1;
1418 const size_t end_backtick = command.find('`', expr_content_start);
1419 if (end_backtick == std::string::npos)
1420 return error;
1421 else if (end_backtick == expr_content_start) {
1422 // Empty expression (two backticks in a row)
1423 command.erase(start_backtick, 2);
1424 } else {
1425 std::string expr_str(command, expr_content_start,
1426 end_backtick - expr_content_start);
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001427
Kate Stoneb9c1b512016-09-06 20:57:50 +00001428 ExecutionContext exe_ctx(GetExecutionContext());
1429 Target *target = exe_ctx.GetTargetPtr();
1430 // Get a dummy target to allow for calculator mode while processing
Adrian Prantl05097242018-04-30 16:49:04 +00001431 // backticks. This also helps break the infinite loop caused when
1432 // target is null.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001433 if (!target)
1434 target = m_debugger.GetDummyTarget();
1435 if (target) {
1436 ValueObjectSP expr_result_valobj_sp;
1437
1438 EvaluateExpressionOptions options;
1439 options.SetCoerceToId(false);
1440 options.SetUnwindOnError(true);
1441 options.SetIgnoreBreakpoints(true);
1442 options.SetKeepInMemory(false);
1443 options.SetTryAllThreads(true);
Pavel Labath43d35412016-12-06 11:24:51 +00001444 options.SetTimeout(llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001445
1446 ExpressionResults expr_result = target->EvaluateExpression(
1447 expr_str.c_str(), exe_ctx.GetFramePtr(), expr_result_valobj_sp,
1448 options);
1449
1450 if (expr_result == eExpressionCompleted) {
1451 Scalar scalar;
1452 if (expr_result_valobj_sp)
1453 expr_result_valobj_sp =
1454 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1455 expr_result_valobj_sp->GetDynamicValueType(), true);
1456 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1457 command.erase(start_backtick, end_backtick - start_backtick + 1);
1458 StreamString value_strm;
1459 const bool show_type = false;
1460 scalar.GetValue(&value_strm, show_type);
1461 size_t value_string_size = value_strm.GetSize();
1462 if (value_string_size) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001463 command.insert(start_backtick, value_strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001464 pos = start_backtick + value_string_size;
1465 continue;
1466 } else {
1467 error.SetErrorStringWithFormat("expression value didn't result "
1468 "in a scalar value for the "
1469 "expression '%s'",
1470 expr_str.c_str());
1471 }
1472 } else {
1473 error.SetErrorStringWithFormat("expression value didn't result "
1474 "in a scalar value for the "
1475 "expression '%s'",
1476 expr_str.c_str());
1477 }
1478 } else {
1479 if (expr_result_valobj_sp)
1480 error = expr_result_valobj_sp->GetError();
1481 if (error.Success()) {
1482
1483 switch (expr_result) {
1484 case eExpressionSetupError:
1485 error.SetErrorStringWithFormat(
1486 "expression setup error for the expression '%s'",
1487 expr_str.c_str());
1488 break;
1489 case eExpressionParseError:
1490 error.SetErrorStringWithFormat(
1491 "expression parse error for the expression '%s'",
1492 expr_str.c_str());
1493 break;
1494 case eExpressionResultUnavailable:
1495 error.SetErrorStringWithFormat(
1496 "expression error fetching result for the expression '%s'",
1497 expr_str.c_str());
1498 break;
1499 case eExpressionCompleted:
1500 break;
1501 case eExpressionDiscarded:
1502 error.SetErrorStringWithFormat(
1503 "expression discarded for the expression '%s'",
1504 expr_str.c_str());
1505 break;
1506 case eExpressionInterrupted:
1507 error.SetErrorStringWithFormat(
1508 "expression interrupted for the expression '%s'",
1509 expr_str.c_str());
1510 break;
1511 case eExpressionHitBreakpoint:
1512 error.SetErrorStringWithFormat(
1513 "expression hit breakpoint for the expression '%s'",
1514 expr_str.c_str());
1515 break;
1516 case eExpressionTimedOut:
1517 error.SetErrorStringWithFormat(
1518 "expression timed out for the expression '%s'",
1519 expr_str.c_str());
1520 break;
1521 case eExpressionStoppedForDebug:
1522 error.SetErrorStringWithFormat("expression stop at entry point "
1523 "for debugging for the "
1524 "expression '%s'",
1525 expr_str.c_str());
1526 break;
1527 }
1528 }
1529 }
1530 }
1531 }
1532 if (error.Fail())
1533 break;
1534 }
1535 }
1536 return error;
1537}
1538
1539bool CommandInterpreter::HandleCommand(const char *command_line,
1540 LazyBool lazy_add_to_history,
1541 CommandReturnObject &result,
1542 ExecutionContext *override_context,
1543 bool repeat_on_empty_command,
1544 bool no_context_switching)
1545
1546{
1547
1548 std::string command_string(command_line);
1549 std::string original_command_string(command_line);
1550
1551 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
Jim Ingham8f7db522016-12-15 00:30:30 +00001552 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
Sean Callanan237c3ed2016-12-14 21:31:31 +00001553 command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001554
1555 if (log)
1556 log->Printf("Processing command: %s", command_line);
1557
Pavel Labathf9d16472017-05-15 13:02:37 +00001558 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1559 Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001560
1561 if (!no_context_switching)
1562 UpdateExecutionContext(override_context);
1563
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001564 if (WasInterrupted()) {
1565 result.AppendError("interrupted");
1566 result.SetStatus(eReturnStatusFailed);
1567 return false;
1568 }
1569
Kate Stoneb9c1b512016-09-06 20:57:50 +00001570 bool add_to_history;
1571 if (lazy_add_to_history == eLazyBoolCalculate)
1572 add_to_history = (m_command_source_depth == 0);
1573 else
1574 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1575
1576 bool empty_command = false;
1577 bool comment_command = false;
1578 if (command_string.empty())
1579 empty_command = true;
1580 else {
1581 const char *k_space_characters = "\t\n\v\f\r ";
1582
1583 size_t non_space = command_string.find_first_not_of(k_space_characters);
Adrian Prantl05097242018-04-30 16:49:04 +00001584 // Check for empty line or comment line (lines whose first non-space
1585 // character is the comment character for this interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001586 if (non_space == std::string::npos)
1587 empty_command = true;
1588 else if (command_string[non_space] == m_comment_char)
1589 comment_command = true;
1590 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001591 llvm::StringRef search_str(command_string);
1592 search_str = search_str.drop_front(non_space);
1593 if (auto hist_str = m_command_history.FindString(search_str)) {
1594 add_to_history = false;
1595 command_string = *hist_str;
1596 original_command_string = *hist_str;
1597 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001598 result.AppendErrorWithFormat("Could not find entry: %s in history",
1599 command_string.c_str());
1600 result.SetStatus(eReturnStatusFailed);
1601 return false;
1602 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001603 }
1604 }
1605
1606 if (empty_command) {
1607 if (repeat_on_empty_command) {
1608 if (m_command_history.IsEmpty()) {
1609 result.AppendError("empty command");
1610 result.SetStatus(eReturnStatusFailed);
1611 return false;
1612 } else {
1613 command_line = m_repeat_command.c_str();
1614 command_string = command_line;
1615 original_command_string = command_line;
1616 if (m_repeat_command.empty()) {
1617 result.AppendErrorWithFormat("No auto repeat.\n");
1618 result.SetStatus(eReturnStatusFailed);
1619 return false;
1620 }
1621 }
1622 add_to_history = false;
1623 } else {
1624 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1625 return true;
1626 }
1627 } else if (comment_command) {
1628 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1629 return true;
1630 }
1631
Zachary Turner97206d52017-05-12 04:51:55 +00001632 Status error(PreprocessCommand(command_string));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001633
1634 if (error.Fail()) {
1635 result.AppendError(error.AsCString());
1636 result.SetStatus(eReturnStatusFailed);
1637 return false;
1638 }
1639
1640 // Phase 1.
1641
1642 // Before we do ANY kind of argument processing, we need to figure out what
1643 // the real/final command object is for the specified command. This gets
1644 // complicated by the fact that the user could have specified an alias, and,
1645 // in translating the alias, there may also be command options and/or even
1646 // data (including raw text strings) that need to be found and inserted into
1647 // the command line as part of the translation. So this first step is plain
1648 // look-up and replacement, resulting in:
1649 // 1. the command object whose Execute method will actually be called
1650 // 2. a revised command string, with all substitutions and replacements
1651 // taken care of
1652 // From 1 above, we can determine whether the Execute function wants raw
1653 // input or not.
1654
1655 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1656
1657 // Although the user may have abbreviated the command, the command_string now
Adrian Prantl05097242018-04-30 16:49:04 +00001658 // has the command expanded to the full name. For example, if the input was
1659 // "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001660 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001661 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1662 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001663 log->Printf("HandleCommand, (revised) command_string: '%s'",
1664 command_string.c_str());
1665 const bool wants_raw_input =
1666 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1667 log->Printf("HandleCommand, wants_raw_input:'%s'",
1668 wants_raw_input ? "True" : "False");
1669 }
1670
1671 // Phase 2.
1672 // Take care of things like setting up the history command & calling the
Adrian Prantl05097242018-04-30 16:49:04 +00001673 // appropriate Execute method on the CommandObject, with the appropriate
1674 // arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001675
1676 if (cmd_obj != nullptr) {
1677 if (add_to_history) {
1678 Args command_args(command_string);
1679 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1680 if (repeat_command != nullptr)
1681 m_repeat_command.assign(repeat_command);
1682 else
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001683 m_repeat_command.assign(original_command_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001684
1685 m_command_history.AppendString(original_command_string);
1686 }
1687
1688 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001689 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001690 if (actual_cmd_name_len < command_string.length())
1691 remainder = command_string.substr(actual_cmd_name_len);
1692
1693 // Remove any initial spaces
1694 size_t pos = remainder.find_first_not_of(k_white_space);
1695 if (pos != 0 && pos != std::string::npos)
1696 remainder.erase(0, pos);
1697
1698 if (log)
1699 log->Printf(
1700 "HandleCommand, command line after removing command name(s): '%s'",
1701 remainder.c_str());
1702
1703 cmd_obj->Execute(remainder.c_str(), result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001704 }
1705
1706 if (log)
1707 log->Printf("HandleCommand, command %s",
1708 (result.Succeeded() ? "succeeded" : "did not succeed"));
1709
1710 return result.Succeeded();
1711}
1712
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001713int CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001714 int num_command_matches = 0;
1715 bool look_for_subcommand = false;
1716
1717 // For any of the command completions a unique match will be a complete word.
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001718 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001719
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001720 if (request.GetCursorIndex() == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001721 // We got nothing on the command line, so return the list of commands
1722 bool include_aliases = true;
Raphael Isemann7f888292018-09-13 21:26:00 +00001723 StringList new_matches, descriptions;
1724 num_command_matches = GetCommandNamesMatchingPartialString(
1725 "", include_aliases, new_matches, descriptions);
1726 request.AddCompletions(new_matches, descriptions);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001727 } else if (request.GetCursorIndex() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001728 // The cursor is in the first argument, so just do a lookup in the
1729 // dictionary.
Raphael Isemann7f888292018-09-13 21:26:00 +00001730 StringList new_matches, new_descriptions;
1731 CommandObject *cmd_obj =
1732 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0),
1733 &new_matches, &new_descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001734
1735 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001736 new_matches.GetStringAtIndex(0) != nullptr &&
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001737 strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001738 new_matches.GetStringAtIndex(0)) == 0) {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001739 if (request.GetParsedLine().GetArgumentCount() == 1) {
1740 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001741 } else {
1742 look_for_subcommand = true;
1743 num_command_matches = 0;
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001744 new_matches.DeleteStringAtIndex(0);
Raphael Isemann7f888292018-09-13 21:26:00 +00001745 new_descriptions.DeleteStringAtIndex(0);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001746 request.GetParsedLine().AppendArgument(llvm::StringRef());
1747 request.SetCursorIndex(request.GetCursorIndex() + 1);
1748 request.SetCursorCharPosition(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001749 }
1750 }
Raphael Isemann7f888292018-09-13 21:26:00 +00001751 request.AddCompletions(new_matches, new_descriptions);
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001752 num_command_matches = request.GetNumberOfMatches();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001753 }
1754
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001755 if (request.GetCursorIndex() > 0 || look_for_subcommand) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001756 // We are completing further on into a commands arguments, so find the
Adrian Prantl05097242018-04-30 16:49:04 +00001757 // command and tell it to complete the command. First see if there is a
1758 // matching initial command:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001759 CommandObject *command_object =
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001760 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001761 if (command_object == nullptr) {
1762 return 0;
1763 } else {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001764 request.GetParsedLine().Shift();
1765 request.SetCursorIndex(request.GetCursorIndex() - 1);
1766 num_command_matches = command_object->HandleCompletion(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001767 }
1768 }
1769
1770 return num_command_matches;
1771}
1772
1773int CommandInterpreter::HandleCompletion(
1774 const char *current_line, const char *cursor, const char *last_char,
Raphael Isemann7f888292018-09-13 21:26:00 +00001775 int match_start_point, int max_return_elements, StringList &matches,
1776 StringList &descriptions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001777
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001778 llvm::StringRef command_line(current_line, last_char - current_line);
Raphael Isemann7f888292018-09-13 21:26:00 +00001779 CompletionResult result;
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001780 CompletionRequest request(command_line, cursor - current_line,
Raphael Isemann7f888292018-09-13 21:26:00 +00001781 match_start_point, max_return_elements, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001782 // Don't complete comments, and if the line we are completing is just the
Adrian Prantl05097242018-04-30 16:49:04 +00001783 // history repeat character, substitute the appropriate history line.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001784 const char *first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001785 if (first_arg) {
1786 if (first_arg[0] == m_comment_char)
1787 return 0;
1788 else if (first_arg[0] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001789 if (auto hist_str = m_command_history.FindString(first_arg)) {
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001790 matches.InsertStringAtIndex(0, *hist_str);
Raphael Isemann7f888292018-09-13 21:26:00 +00001791 descriptions.InsertStringAtIndex(0, "Previous command history event");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001792 return -2;
1793 } else
1794 return 0;
1795 }
1796 }
1797
Kate Stoneb9c1b512016-09-06 20:57:50 +00001798 // Only max_return_elements == -1 is supported at present:
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001799 lldbassert(max_return_elements == -1);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001800
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001801 int num_command_matches = HandleCompletionMatches(request);
Raphael Isemann7f888292018-09-13 21:26:00 +00001802 result.GetMatches(matches);
1803 result.GetDescriptions(descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001804
1805 if (num_command_matches <= 0)
1806 return num_command_matches;
1807
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001808 if (request.GetParsedLine().GetArgumentCount() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001809 // If we got an empty string, insert nothing.
1810 matches.InsertStringAtIndex(0, "");
Raphael Isemann7f888292018-09-13 21:26:00 +00001811 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001812 } else {
1813 // Now figure out if there is a common substring, and if so put that in
Adrian Prantl05097242018-04-30 16:49:04 +00001814 // element 0, otherwise put an empty string in element 0.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001815 std::string command_partial_str = request.GetCursorArgumentPrefix().str();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001816
1817 std::string common_prefix;
1818 matches.LongestCommonPrefix(common_prefix);
1819 const size_t partial_name_len = command_partial_str.size();
1820 common_prefix.erase(0, partial_name_len);
1821
Adrian Prantl05097242018-04-30 16:49:04 +00001822 // If we matched a unique single command, add a space... Only do this if
1823 // the completer told us this was a complete word, however...
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001824 if (num_command_matches == 1 && request.GetWordComplete()) {
1825 char quote_char = request.GetParsedLine()[request.GetCursorIndex()].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001826 common_prefix =
1827 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1828 if (quote_char != '\0')
1829 common_prefix.push_back(quote_char);
1830 common_prefix.push_back(' ');
1831 }
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001832 matches.InsertStringAtIndex(0, common_prefix.c_str());
Raphael Isemann7f888292018-09-13 21:26:00 +00001833 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001834 }
1835 return num_command_matches;
1836}
1837
1838CommandInterpreter::~CommandInterpreter() {}
1839
Zachary Turner514d8cd2016-09-23 18:06:53 +00001840void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001841 EventSP prompt_change_event_sp(
1842 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1843 ;
1844 BroadcastEvent(prompt_change_event_sp);
1845 if (m_command_io_handler_sp)
1846 m_command_io_handler_sp->SetPrompt(new_prompt);
1847}
1848
Zachary Turner7a120c82016-11-13 03:05:58 +00001849bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001850 // Check AutoConfirm first:
1851 if (m_debugger.GetAutoConfirm())
1852 return default_answer;
1853
1854 IOHandlerConfirm *confirm =
1855 new IOHandlerConfirm(m_debugger, message, default_answer);
1856 IOHandlerSP io_handler_sp(confirm);
1857 m_debugger.RunIOHandler(io_handler_sp);
1858 return confirm->GetResponse();
1859}
1860
Zachary Turnera483f572016-10-05 21:14:49 +00001861const CommandAlias *
1862CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001863 OptionArgVectorSP ret_val;
1864
Zachary Turnera483f572016-10-05 21:14:49 +00001865 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001866 if (pos != m_alias_dict.end())
1867 return (CommandAlias *)pos->second.get();
1868
1869 return nullptr;
1870}
1871
Zachary Turnera4496982016-10-05 21:14:38 +00001872bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001873
Zachary Turnera4496982016-10-05 21:14:38 +00001874bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001875
Zachary Turnera4496982016-10-05 21:14:38 +00001876bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001877
Zachary Turnera4496982016-10-05 21:14:38 +00001878bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001879
1880void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1881 const char *alias_name,
1882 Args &cmd_args,
1883 std::string &raw_input_string,
1884 CommandReturnObject &result) {
1885 OptionArgVectorSP option_arg_vector_sp =
1886 GetAlias(alias_name)->GetOptionArguments();
1887
1888 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1889
1890 // Make sure that the alias name is the 0th element in cmd_args
1891 std::string alias_name_str = alias_name;
1892 if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)
Zachary Turner5c725f32016-09-19 21:56:59 +00001893 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001894
1895 Args new_args(alias_cmd_obj->GetCommandName());
1896 if (new_args.GetArgumentCount() == 2)
1897 new_args.Shift();
1898
1899 if (option_arg_vector_sp.get()) {
1900 if (wants_raw_input) {
1901 // We have a command that both has command options and takes raw input.
Adrian Prantl05097242018-04-30 16:49:04 +00001902 // Make *sure* it has a " -- " in the right place in the
1903 // raw_input_string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001904 size_t pos = raw_input_string.find(" -- ");
1905 if (pos == std::string::npos) {
1906 // None found; assume it goes at the beginning of the raw input string
1907 raw_input_string.insert(0, " -- ");
1908 }
1909 }
1910
1911 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1912 const size_t old_size = cmd_args.GetArgumentCount();
1913 std::vector<bool> used(old_size + 1, false);
1914
1915 used[0] = true;
1916
Zachary Turner5c28c662016-10-03 23:20:36 +00001917 int value_type;
1918 std::string option;
1919 std::string value;
1920 for (const auto &option_entry : *option_arg_vector) {
1921 std::tie(option, value_type, value) = option_entry;
1922 if (option == "<argument>") {
1923 if (!wants_raw_input || (value != "--")) {
1924 // Since we inserted this above, make sure we don't insert it twice
1925 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001926 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001927 continue;
1928 }
1929
1930 if (value_type != OptionParser::eOptionalArgument)
1931 new_args.AppendArgument(option);
1932
1933 if (value == "<no-argument>")
1934 continue;
1935
1936 int index = GetOptionArgumentPosition(value.c_str());
1937 if (index == 0) {
1938 // value was NOT a positional argument; must be a real value
1939 if (value_type != OptionParser::eOptionalArgument)
1940 new_args.AppendArgument(value);
1941 else {
1942 char buffer[255];
1943 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1944 value.c_str());
1945 new_args.AppendArgument(llvm::StringRef(buffer));
1946 }
1947
1948 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1949 result.AppendErrorWithFormat("Not enough arguments provided; you "
1950 "need at least %d arguments to use "
1951 "this alias.\n",
1952 index);
1953 result.SetStatus(eReturnStatusFailed);
1954 return;
1955 } else {
1956 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1957 size_t strpos =
1958 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1959 if (strpos != std::string::npos) {
1960 raw_input_string = raw_input_string.erase(
1961 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1962 }
1963
1964 if (value_type != OptionParser::eOptionalArgument)
1965 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
1966 else {
1967 char buffer[255];
1968 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1969 cmd_args.GetArgumentAtIndex(index));
1970 new_args.AppendArgument(buffer);
1971 }
1972 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001973 }
1974 }
1975
Zachary Turner97d2c402016-10-05 23:40:23 +00001976 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00001977 if (!used[entry.index()] && !wants_raw_input)
1978 new_args.AppendArgument(entry.value().ref);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001979 }
1980
1981 cmd_args.Clear();
1982 cmd_args.SetArguments(new_args.GetArgumentCount(),
1983 new_args.GetConstArgumentVector());
1984 } else {
1985 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1986 // This alias was not created with any options; nothing further needs to be
Adrian Prantl05097242018-04-30 16:49:04 +00001987 // done, unless it is a command that wants raw input, in which case we need
1988 // to clear the rest of the data from cmd_args, since its in the raw input
1989 // string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001990 if (wants_raw_input) {
1991 cmd_args.Clear();
1992 cmd_args.SetArguments(new_args.GetArgumentCount(),
1993 new_args.GetConstArgumentVector());
1994 }
1995 return;
1996 }
1997
1998 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1999 return;
2000}
2001
2002int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2003 int position = 0; // Any string that isn't an argument position, i.e. '%'
2004 // followed by an integer, gets a position
2005 // of zero.
2006
2007 const char *cptr = in_string;
2008
2009 // Does it start with '%'
2010 if (cptr[0] == '%') {
2011 ++cptr;
2012
2013 // Is the rest of it entirely digits?
2014 if (isdigit(cptr[0])) {
2015 const char *start = cptr;
2016 while (isdigit(cptr[0]))
2017 ++cptr;
2018
Adrian Prantl05097242018-04-30 16:49:04 +00002019 // We've gotten to the end of the digits; are we at the end of the
2020 // string?
Kate Stoneb9c1b512016-09-06 20:57:50 +00002021 if (cptr[0] == '\0')
2022 position = atoi(start);
2023 }
2024 }
2025
2026 return position;
2027}
2028
2029void CommandInterpreter::SourceInitFile(bool in_cwd,
2030 CommandReturnObject &result) {
2031 FileSpec init_file;
2032 if (in_cwd) {
2033 ExecutionContext exe_ctx(GetExecutionContext());
2034 Target *target = exe_ctx.GetTargetPtr();
2035 if (target) {
2036 // In the current working directory we don't load any program specific
2037 // .lldbinit files, we only look for a ".lldbinit" file.
2038 if (m_skip_lldbinit_files)
2039 return;
2040
2041 LoadCWDlldbinitFile should_load =
2042 target->TargetProperties::GetLoadCWDlldbinitFile();
2043 if (should_load == eLoadCWDlldbinitWarn) {
2044 FileSpec dot_lldb(".lldbinit", true);
2045 llvm::SmallString<64> home_dir_path;
2046 llvm::sys::path::home_directory(home_dir_path);
2047 FileSpec homedir_dot_lldb(home_dir_path.c_str(), false);
2048 homedir_dot_lldb.AppendPathComponent(".lldbinit");
2049 homedir_dot_lldb.ResolvePath();
2050 if (dot_lldb.Exists() &&
2051 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2052 result.AppendErrorWithFormat(
2053 "There is a .lldbinit file in the current directory which is not "
2054 "being read.\n"
2055 "To silence this warning without sourcing in the local "
2056 ".lldbinit,\n"
2057 "add the following to the lldbinit file in your home directory:\n"
2058 " settings set target.load-cwd-lldbinit false\n"
2059 "To allow lldb to source .lldbinit files in the current working "
2060 "directory,\n"
2061 "set the value of this variable to true. Only do so if you "
2062 "understand and\n"
2063 "accept the security risk.");
2064 result.SetStatus(eReturnStatusFailed);
2065 return;
2066 }
2067 } else if (should_load == eLoadCWDlldbinitTrue) {
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002068 init_file.SetFile("./.lldbinit", true, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002069 }
2070 }
2071 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002072 // If we aren't looking in the current working directory we are looking in
2073 // the home directory. We will first see if there is an application
2074 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a "-"
2075 // and the name of the program. If this file doesn't exist, we fall back to
2076 // just the "~/.lldbinit" file. We also obey any requests to not load the
2077 // init files.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002078 llvm::SmallString<64> home_dir_path;
2079 llvm::sys::path::home_directory(home_dir_path);
2080 FileSpec profilePath(home_dir_path.c_str(), false);
2081 profilePath.AppendPathComponent(".lldbinit");
2082 std::string init_file_path = profilePath.GetPath();
2083
2084 if (m_skip_app_init_files == false) {
2085 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2086 const char *program_name = program_file_spec.GetFilename().AsCString();
2087
2088 if (program_name) {
2089 char program_init_file_name[PATH_MAX];
2090 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2091 "%s-%s", init_file_path.c_str(), program_name);
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002092 init_file.SetFile(program_init_file_name, true,
2093 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002094 if (!init_file.Exists())
2095 init_file.Clear();
2096 }
2097 }
2098
2099 if (!init_file && !m_skip_lldbinit_files)
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002100 init_file.SetFile(init_file_path, false, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002101 }
2102
2103 // If the file exists, tell HandleCommand to 'source' it; this will do the
Adrian Prantl05097242018-04-30 16:49:04 +00002104 // actual broadcasting of the commands back to any appropriate listener (see
Kate Stoneb9c1b512016-09-06 20:57:50 +00002105 // CommandObjectSource::Execute for more details).
2106
2107 if (init_file.Exists()) {
2108 const bool saved_batch = SetBatchCommandMode(true);
2109 CommandInterpreterRunOptions options;
2110 options.SetSilent(true);
2111 options.SetStopOnError(false);
2112 options.SetStopOnContinue(true);
2113
2114 HandleCommandsFromFile(init_file,
2115 nullptr, // Execution context
2116 options, result);
2117 SetBatchCommandMode(saved_batch);
2118 } else {
2119 // nothing to be done if the file doesn't exist
2120 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2121 }
2122}
2123
2124const char *CommandInterpreter::GetCommandPrefix() {
2125 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2126 return prefix == NULL ? "" : prefix;
2127}
2128
2129PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2130 PlatformSP platform_sp;
2131 if (prefer_target_platform) {
2132 ExecutionContext exe_ctx(GetExecutionContext());
2133 Target *target = exe_ctx.GetTargetPtr();
2134 if (target)
2135 platform_sp = target->GetPlatform();
2136 }
2137
2138 if (!platform_sp)
2139 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2140 return platform_sp;
2141}
2142
2143void CommandInterpreter::HandleCommands(const StringList &commands,
2144 ExecutionContext *override_context,
2145 CommandInterpreterRunOptions &options,
2146 CommandReturnObject &result) {
2147 size_t num_lines = commands.GetSize();
2148
2149 // If we are going to continue past a "continue" then we need to run the
Adrian Prantl05097242018-04-30 16:49:04 +00002150 // commands synchronously. Make sure you reset this value anywhere you return
2151 // from the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002152
2153 bool old_async_execution = m_debugger.GetAsyncExecution();
2154
2155 // If we've been given an execution context, set it at the start, but don't
Adrian Prantl05097242018-04-30 16:49:04 +00002156 // keep resetting it or we will cause series of commands that change the
2157 // context, then do an operation that relies on that context to fail.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002158
2159 if (override_context != nullptr)
2160 UpdateExecutionContext(override_context);
2161
2162 if (!options.GetStopOnContinue()) {
2163 m_debugger.SetAsyncExecution(false);
2164 }
2165
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002166 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002167 const char *cmd = commands.GetStringAtIndex(idx);
2168 if (cmd[0] == '\0')
2169 continue;
2170
2171 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002172 // TODO: Add Stream support.
2173 result.AppendMessageWithFormat("%s %s\n",
2174 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002175 }
2176
2177 CommandReturnObject tmp_result;
2178 // If override_context is not NULL, pass no_context_switching = true for
2179 // HandleCommand() since we updated our context already.
2180
2181 // We might call into a regex or alias command, in which case the
Adrian Prantl05097242018-04-30 16:49:04 +00002182 // add_to_history will get lost. This m_command_source_depth dingus is the
2183 // way we turn off adding to the history in that case, so set it up here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002184 if (!options.GetAddToHistory())
2185 m_command_source_depth++;
2186 bool success =
2187 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2188 nullptr, /* override_context */
2189 true, /* repeat_on_empty_command */
2190 override_context != nullptr /* no_context_switching */);
2191 if (!options.GetAddToHistory())
2192 m_command_source_depth--;
2193
2194 if (options.GetPrintResults()) {
2195 if (tmp_result.Succeeded())
Zachary Turner03c9f362016-11-14 23:23:31 +00002196 result.AppendMessage(tmp_result.GetOutputData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002197 }
2198
2199 if (!success || !tmp_result.Succeeded()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002200 llvm::StringRef error_msg = tmp_result.GetErrorData();
2201 if (error_msg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002202 error_msg = "<unknown error>.\n";
2203 if (options.GetStopOnError()) {
2204 result.AppendErrorWithFormat(
2205 "Aborting reading of commands after command #%" PRIu64
2206 ": '%s' failed with %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00002207 (uint64_t)idx, cmd, error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002208 result.SetStatus(eReturnStatusFailed);
2209 m_debugger.SetAsyncExecution(old_async_execution);
2210 return;
2211 } else if (options.GetPrintResults()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002212 result.AppendMessageWithFormat(
2213 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2214 error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002215 }
2216 }
2217
2218 if (result.GetImmediateOutputStream())
2219 result.GetImmediateOutputStream()->Flush();
2220
2221 if (result.GetImmediateErrorStream())
2222 result.GetImmediateErrorStream()->Flush();
2223
Adrian Prantl05097242018-04-30 16:49:04 +00002224 // N.B. Can't depend on DidChangeProcessState, because the state coming
2225 // into the command execution could be running (for instance in Breakpoint
2226 // Commands. So we check the return value to see if it is has running in
2227 // it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002228 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2229 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2230 if (options.GetStopOnContinue()) {
2231 // If we caused the target to proceed, and we're going to stop in that
Adrian Prantl05097242018-04-30 16:49:04 +00002232 // case, set the status in our real result before returning. This is
2233 // an error if the continue was not the last command in the set of
2234 // commands to be run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 if (idx != num_lines - 1)
2236 result.AppendErrorWithFormat(
2237 "Aborting reading of commands after command #%" PRIu64
2238 ": '%s' continued the target.\n",
2239 (uint64_t)idx + 1, cmd);
2240 else
2241 result.AppendMessageWithFormat("Command #%" PRIu64
2242 " '%s' continued the target.\n",
2243 (uint64_t)idx + 1, cmd);
2244
2245 result.SetStatus(tmp_result.GetStatus());
2246 m_debugger.SetAsyncExecution(old_async_execution);
2247
2248 return;
2249 }
2250 }
2251
2252 // Also check for "stop on crash here:
2253 bool should_stop = false;
2254 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2255 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2256 if (target_sp) {
2257 ProcessSP process_sp(target_sp->GetProcessSP());
2258 if (process_sp) {
2259 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2260 StopReason reason = thread_sp->GetStopReason();
2261 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2262 reason == eStopReasonInstrumentation) {
2263 should_stop = true;
2264 break;
2265 }
2266 }
2267 }
2268 }
2269 if (should_stop) {
2270 if (idx != num_lines - 1)
2271 result.AppendErrorWithFormat(
2272 "Aborting reading of commands after command #%" PRIu64
2273 ": '%s' stopped with a signal or exception.\n",
2274 (uint64_t)idx + 1, cmd);
2275 else
2276 result.AppendMessageWithFormat(
2277 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2278 (uint64_t)idx + 1, cmd);
2279
2280 result.SetStatus(tmp_result.GetStatus());
2281 m_debugger.SetAsyncExecution(old_async_execution);
2282
2283 return;
2284 }
2285 }
2286 }
2287
2288 result.SetStatus(eReturnStatusSuccessFinishResult);
2289 m_debugger.SetAsyncExecution(old_async_execution);
2290
2291 return;
2292}
2293
2294// Make flags that we can pass into the IOHandler so our delegates can do the
2295// right thing
2296enum {
2297 eHandleCommandFlagStopOnContinue = (1u << 0),
2298 eHandleCommandFlagStopOnError = (1u << 1),
2299 eHandleCommandFlagEchoCommand = (1u << 2),
2300 eHandleCommandFlagPrintResult = (1u << 3),
2301 eHandleCommandFlagStopOnCrash = (1u << 4)
2302};
2303
2304void CommandInterpreter::HandleCommandsFromFile(
2305 FileSpec &cmd_file, ExecutionContext *context,
2306 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2307 if (cmd_file.Exists()) {
2308 StreamFileSP input_file_sp(new StreamFile());
2309
2310 std::string cmd_file_path = cmd_file.GetPath();
Zachary Turner97206d52017-05-12 04:51:55 +00002311 Status error = input_file_sp->GetFile().Open(cmd_file_path.c_str(),
2312 File::eOpenOptionRead);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002313
2314 if (error.Success()) {
2315 Debugger &debugger = GetDebugger();
2316
2317 uint32_t flags = 0;
2318
2319 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2320 if (m_command_source_flags.empty()) {
2321 // Stop on continue by default
2322 flags |= eHandleCommandFlagStopOnContinue;
2323 } else if (m_command_source_flags.back() &
2324 eHandleCommandFlagStopOnContinue) {
2325 flags |= eHandleCommandFlagStopOnContinue;
2326 }
2327 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2328 flags |= eHandleCommandFlagStopOnContinue;
2329 }
2330
2331 if (options.m_stop_on_error == eLazyBoolCalculate) {
2332 if (m_command_source_flags.empty()) {
2333 if (GetStopCmdSourceOnError())
2334 flags |= eHandleCommandFlagStopOnError;
2335 } else if (m_command_source_flags.back() &
2336 eHandleCommandFlagStopOnError) {
2337 flags |= eHandleCommandFlagStopOnError;
2338 }
2339 } else if (options.m_stop_on_error == eLazyBoolYes) {
2340 flags |= eHandleCommandFlagStopOnError;
2341 }
2342
2343 if (options.GetStopOnCrash()) {
2344 if (m_command_source_flags.empty()) {
2345 // Echo command by default
2346 flags |= eHandleCommandFlagStopOnCrash;
2347 } else if (m_command_source_flags.back() &
2348 eHandleCommandFlagStopOnCrash) {
2349 flags |= eHandleCommandFlagStopOnCrash;
2350 }
2351 }
2352
2353 if (options.m_echo_commands == eLazyBoolCalculate) {
2354 if (m_command_source_flags.empty()) {
2355 // Echo command by default
2356 flags |= eHandleCommandFlagEchoCommand;
2357 } else if (m_command_source_flags.back() &
2358 eHandleCommandFlagEchoCommand) {
2359 flags |= eHandleCommandFlagEchoCommand;
2360 }
2361 } else if (options.m_echo_commands == eLazyBoolYes) {
2362 flags |= eHandleCommandFlagEchoCommand;
2363 }
2364
2365 if (options.m_print_results == eLazyBoolCalculate) {
2366 if (m_command_source_flags.empty()) {
2367 // Print output by default
2368 flags |= eHandleCommandFlagPrintResult;
2369 } else if (m_command_source_flags.back() &
2370 eHandleCommandFlagPrintResult) {
2371 flags |= eHandleCommandFlagPrintResult;
2372 }
2373 } else if (options.m_print_results == eLazyBoolYes) {
2374 flags |= eHandleCommandFlagPrintResult;
2375 }
2376
2377 if (flags & eHandleCommandFlagPrintResult) {
2378 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2379 cmd_file_path.c_str());
2380 }
2381
Adrian Prantl05097242018-04-30 16:49:04 +00002382 // Used for inheriting the right settings when "command source" might
2383 // have nested "command source" commands
Kate Stoneb9c1b512016-09-06 20:57:50 +00002384 lldb::StreamFileSP empty_stream_sp;
2385 m_command_source_flags.push_back(flags);
2386 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2387 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2388 empty_stream_sp, // Pass in an empty stream so we inherit the top
2389 // input reader output stream
2390 empty_stream_sp, // Pass in an empty stream so we inherit the top
2391 // input reader error stream
2392 flags,
2393 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2394 // or written
Zachary Turner514d8cd2016-09-23 18:06:53 +00002395 debugger.GetPrompt(), llvm::StringRef(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00002396 false, // Not multi-line
2397 debugger.GetUseColor(), 0, *this));
2398 const bool old_async_execution = debugger.GetAsyncExecution();
2399
2400 // Set synchronous execution if we are not stopping on continue
2401 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2402 debugger.SetAsyncExecution(false);
2403
2404 m_command_source_depth++;
2405
2406 debugger.RunIOHandler(io_handler_sp);
2407 if (!m_command_source_flags.empty())
2408 m_command_source_flags.pop_back();
2409 m_command_source_depth--;
2410 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2411 debugger.SetAsyncExecution(old_async_execution);
2412 } else {
2413 result.AppendErrorWithFormat(
2414 "error: an error occurred read file '%s': %s\n",
2415 cmd_file_path.c_str(), error.AsCString());
2416 result.SetStatus(eReturnStatusFailed);
2417 }
2418
2419 } else {
2420 result.AppendErrorWithFormat(
2421 "Error reading commands from file %s - file not found.\n",
2422 cmd_file.GetFilename().AsCString("<Unknown>"));
2423 result.SetStatus(eReturnStatusFailed);
2424 return;
2425 }
2426}
2427
2428ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
Jim Ingham30bac792017-07-13 19:45:54 +00002429 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
Greg Clayton79040462016-12-09 01:21:14 +00002430 if (!m_script_interpreter_sp) {
2431 if (!can_create)
2432 return nullptr;
2433 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2434 m_script_interpreter_sp =
2435 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2436 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002437 return m_script_interpreter_sp.get();
2438}
2439
2440bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2441
2442void CommandInterpreter::SetSynchronous(bool value) {
2443 m_synchronous_execution = value;
2444}
2445
2446void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002447 llvm::StringRef prefix,
2448 llvm::StringRef help_text) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002449 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002450
Zachary Turner0ac5f982016-11-08 04:12:42 +00002451 size_t line_width_max = max_columns - prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002452 if (line_width_max < 16)
Zachary Turner0ac5f982016-11-08 04:12:42 +00002453 line_width_max = help_text.size() + prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002454
Zachary Turner0ac5f982016-11-08 04:12:42 +00002455 strm.IndentMore(prefix.size());
2456 bool prefixed_yet = false;
2457 while (!help_text.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002458 // Prefix the first line, indent subsequent lines to line up
Zachary Turner0ac5f982016-11-08 04:12:42 +00002459 if (!prefixed_yet) {
2460 strm << prefix;
2461 prefixed_yet = true;
2462 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002463 strm.Indent();
Zachary Turner0ac5f982016-11-08 04:12:42 +00002464
2465 // Never print more than the maximum on one line.
2466 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2467
2468 // Always break on an explicit newline.
2469 std::size_t first_newline = this_line.find_first_of("\n");
2470
2471 // Don't break on space/tab unless the text is too long to fit on one line.
2472 std::size_t last_space = llvm::StringRef::npos;
2473 if (this_line.size() != help_text.size())
2474 last_space = this_line.find_last_of(" \t");
2475
2476 // Break at whichever condition triggered first.
2477 this_line = this_line.substr(0, std::min(first_newline, last_space));
2478 strm.PutCString(this_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002479 strm.EOL();
2480
Zachary Turner0ac5f982016-11-08 04:12:42 +00002481 // Remove whitespace / newlines after breaking.
2482 help_text = help_text.drop_front(this_line.size()).ltrim();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002483 }
Zachary Turner0ac5f982016-11-08 04:12:42 +00002484 strm.IndentLess(prefix.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002485}
2486
2487void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002488 llvm::StringRef word_text,
2489 llvm::StringRef separator,
2490 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002491 size_t max_word_len) {
2492 StreamString prefix_stream;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002493 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2494 (int)separator.size(), separator.data());
Zachary Turnerc1564272016-11-16 21:15:24 +00002495 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2496}
2497
Zachary Turner0ac5f982016-11-08 04:12:42 +00002498void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2499 llvm::StringRef separator,
2500 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002501 uint32_t max_word_len) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00002502 int indent_size = max_word_len + separator.size() + 2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002503
2504 strm.IndentMore(indent_size);
2505
2506 StreamString text_strm;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002507 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2508 text_strm << separator << " " << help_text;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002509
2510 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2511
Zachary Turnerc1564272016-11-16 21:15:24 +00002512 llvm::StringRef text = text_strm.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002513
2514 uint32_t chars_left = max_columns;
2515
Davide Italianocf8a8292017-04-14 22:36:08 +00002516 auto nextWordLength = [](llvm::StringRef S) {
2517 size_t pos = S.find_first_of(' ');
2518 return pos == llvm::StringRef::npos ? S.size() : pos;
2519 };
2520
Zachary Turnerc1564272016-11-16 21:15:24 +00002521 while (!text.empty()) {
2522 if (text.front() == '\n' ||
Jim Inghama81bd7f2017-07-27 00:18:18 +00002523 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002524 strm.EOL();
2525 strm.Indent();
Zachary Turnerc1564272016-11-16 21:15:24 +00002526 chars_left = max_columns - indent_size;
2527 if (text.front() == '\n')
2528 text = text.drop_front();
2529 else
2530 text = text.ltrim(' ');
Kate Stoneb9c1b512016-09-06 20:57:50 +00002531 } else {
Zachary Turnerc1564272016-11-16 21:15:24 +00002532 strm.PutChar(text.front());
2533 --chars_left;
2534 text = text.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002535 }
2536 }
2537
2538 strm.EOL();
2539 strm.IndentLess(indent_size);
2540}
2541
2542void CommandInterpreter::FindCommandsForApropos(
Zachary Turner067d1db2016-11-16 21:45:04 +00002543 llvm::StringRef search_word, StringList &commands_found,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002544 StringList &commands_help, CommandObject::CommandMap &command_map) {
2545 CommandObject::CommandMap::const_iterator pos;
2546
2547 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
Zachary Turner067d1db2016-11-16 21:45:04 +00002548 llvm::StringRef command_name = pos->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002549 CommandObject *cmd_obj = pos->second.get();
2550
2551 const bool search_short_help = true;
2552 const bool search_long_help = false;
2553 const bool search_syntax = false;
2554 const bool search_options = false;
Zachary Turner067d1db2016-11-16 21:45:04 +00002555 if (command_name.contains_lower(search_word) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002556 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2557 search_long_help, search_syntax,
2558 search_options)) {
2559 commands_found.AppendString(cmd_obj->GetCommandName());
2560 commands_help.AppendString(cmd_obj->GetHelp());
2561 }
2562
2563 if (cmd_obj->IsMultiwordObject()) {
2564 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2565 FindCommandsForApropos(search_word, commands_found, commands_help,
2566 cmd_multiword->GetSubcommandDictionary());
2567 }
2568 }
2569}
2570
Zachary Turner067d1db2016-11-16 21:45:04 +00002571void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002572 StringList &commands_found,
2573 StringList &commands_help,
2574 bool search_builtin_commands,
2575 bool search_user_commands,
2576 bool search_alias_commands) {
2577 CommandObject::CommandMap::const_iterator pos;
2578
2579 if (search_builtin_commands)
2580 FindCommandsForApropos(search_word, commands_found, commands_help,
2581 m_command_dict);
2582
2583 if (search_user_commands)
2584 FindCommandsForApropos(search_word, commands_found, commands_help,
2585 m_user_dict);
2586
2587 if (search_alias_commands)
2588 FindCommandsForApropos(search_word, commands_found, commands_help,
2589 m_alias_dict);
2590}
2591
2592void CommandInterpreter::UpdateExecutionContext(
2593 ExecutionContext *override_context) {
2594 if (override_context != nullptr) {
2595 m_exe_ctx_ref = *override_context;
2596 } else {
2597 const bool adopt_selected = true;
2598 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2599 adopt_selected);
2600 }
2601}
2602
2603size_t CommandInterpreter::GetProcessOutput() {
2604 // The process has stuff waiting for stderr; get it and write it out to the
2605 // appropriate place.
2606 char stdio_buffer[1024];
2607 size_t len;
2608 size_t total_bytes = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002609 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002610 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2611 if (target_sp) {
2612 ProcessSP process_sp(target_sp->GetProcessSP());
2613 if (process_sp) {
2614 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2615 error)) > 0) {
2616 size_t bytes_written = len;
2617 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2618 total_bytes += len;
2619 }
2620 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2621 error)) > 0) {
2622 size_t bytes_written = len;
2623 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2624 total_bytes += len;
2625 }
2626 }
2627 }
2628 return total_bytes;
2629}
2630
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002631void CommandInterpreter::StartHandlingCommand() {
2632 auto idle_state = CommandHandlingState::eIdle;
2633 if (m_command_state.compare_exchange_strong(
2634 idle_state, CommandHandlingState::eInProgress))
2635 lldbassert(m_iohandler_nesting_level == 0);
2636 else
2637 lldbassert(m_iohandler_nesting_level > 0);
2638 ++m_iohandler_nesting_level;
2639}
2640
2641void CommandInterpreter::FinishHandlingCommand() {
2642 lldbassert(m_iohandler_nesting_level > 0);
2643 if (--m_iohandler_nesting_level == 0) {
2644 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2645 lldbassert(prev_state != CommandHandlingState::eIdle);
2646 }
2647}
2648
2649bool CommandInterpreter::InterruptCommand() {
2650 auto in_progress = CommandHandlingState::eInProgress;
2651 return m_command_state.compare_exchange_strong(
2652 in_progress, CommandHandlingState::eInterrupted);
2653}
2654
2655bool CommandInterpreter::WasInterrupted() const {
2656 bool was_interrupted =
2657 (m_command_state == CommandHandlingState::eInterrupted);
2658 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2659 return was_interrupted;
2660}
2661
2662void CommandInterpreter::PrintCommandOutput(Stream &stream,
2663 llvm::StringRef str) {
2664 // Split the output into lines and poll for interrupt requests
2665 const char *data = str.data();
2666 size_t size = str.size();
2667 while (size > 0 && !WasInterrupted()) {
2668 size_t chunk_size = 0;
2669 for (; chunk_size < size; ++chunk_size) {
2670 lldbassert(data[chunk_size] != '\0');
2671 if (data[chunk_size] == '\n') {
2672 ++chunk_size;
2673 break;
2674 }
2675 }
2676 chunk_size = stream.Write(data, chunk_size);
2677 lldbassert(size >= chunk_size);
2678 data += chunk_size;
2679 size -= chunk_size;
2680 }
2681 if (size > 0) {
2682 stream.Printf("\n... Interrupted.\n");
2683 }
2684}
2685
Kate Stoneb9c1b512016-09-06 20:57:50 +00002686void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2687 std::string &line) {
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002688 // If we were interrupted, bail out...
2689 if (WasInterrupted())
2690 return;
2691
Kate Stoneb9c1b512016-09-06 20:57:50 +00002692 const bool is_interactive = io_handler.GetIsInteractive();
2693 if (is_interactive == false) {
2694 // When we are not interactive, don't execute blank lines. This will happen
2695 // sourcing a commands file. We don't want blank lines to repeat the
Adrian Prantl05097242018-04-30 16:49:04 +00002696 // previous command and cause any errors to occur (like redefining an
2697 // alias, get an error and stop parsing the commands file).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002698 if (line.empty())
2699 return;
2700
2701 // When using a non-interactive file handle (like when sourcing commands
Adrian Prantl05097242018-04-30 16:49:04 +00002702 // from a file) we need to echo the command out so we don't just see the
2703 // command output and no command...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002704 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2705 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2706 line.c_str());
2707 }
2708
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002709 StartHandlingCommand();
2710
Kate Stoneb9c1b512016-09-06 20:57:50 +00002711 lldb_private::CommandReturnObject result;
2712 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2713
2714 // Now emit the command output text from the command we just executed
2715 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2716 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2717 GetProcessOutput();
2718
2719 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002720 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002721 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002722 }
2723
2724 // Now emit the command error text from the command we just executed
2725 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002726 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002727 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002728 }
2729 }
2730
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002731 FinishHandlingCommand();
2732
Kate Stoneb9c1b512016-09-06 20:57:50 +00002733 switch (result.GetStatus()) {
2734 case eReturnStatusInvalid:
2735 case eReturnStatusSuccessFinishNoResult:
2736 case eReturnStatusSuccessFinishResult:
2737 case eReturnStatusStarted:
2738 break;
2739
2740 case eReturnStatusSuccessContinuingNoResult:
2741 case eReturnStatusSuccessContinuingResult:
2742 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2743 io_handler.SetIsDone(true);
2744 break;
2745
2746 case eReturnStatusFailed:
2747 m_num_errors++;
2748 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2749 io_handler.SetIsDone(true);
2750 break;
2751
2752 case eReturnStatusQuit:
2753 m_quit_requested = true;
2754 io_handler.SetIsDone(true);
2755 break;
2756 }
2757
2758 // Finally, if we're going to stop on crash, check that here:
2759 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2760 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2761 bool should_stop = false;
2762 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2763 if (target_sp) {
2764 ProcessSP process_sp(target_sp->GetProcessSP());
2765 if (process_sp) {
2766 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2767 StopReason reason = thread_sp->GetStopReason();
2768 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2769 reason == eStopReasonInstrumentation) &&
2770 !result.GetAbnormalStopWasExpected()) {
2771 should_stop = true;
2772 break;
2773 }
2774 }
2775 }
2776 }
2777 if (should_stop) {
2778 io_handler.SetIsDone(true);
2779 m_stopped_for_crash = true;
2780 }
2781 }
2782}
2783
2784bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2785 ExecutionContext exe_ctx(GetExecutionContext());
2786 Process *process = exe_ctx.GetProcessPtr();
2787
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002788 if (InterruptCommand())
2789 return true;
2790
Kate Stoneb9c1b512016-09-06 20:57:50 +00002791 if (process) {
2792 StateType state = process->GetState();
2793 if (StateIsRunningState(state)) {
2794 process->Halt();
2795 return true; // Don't do any updating when we are running
2796 }
2797 }
2798
2799 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2800 if (script_interpreter) {
2801 if (script_interpreter->Interrupt())
2802 return true;
2803 }
2804 return false;
2805}
2806
2807void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2808 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2809 void *baton) {
2810 Debugger &debugger = GetDebugger();
2811 IOHandlerSP io_handler_sp(
2812 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2813 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002814 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2815 llvm::StringRef(), // Continuation prompt
2816 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002817 debugger.GetUseColor(),
2818 0, // Don't show line numbers
2819 delegate)); // IOHandlerDelegate
2820
2821 if (io_handler_sp) {
2822 io_handler_sp->SetUserData(baton);
2823 if (asynchronously)
2824 debugger.PushIOHandler(io_handler_sp);
2825 else
2826 debugger.RunIOHandler(io_handler_sp);
2827 }
2828}
2829
2830void CommandInterpreter::GetPythonCommandsFromIOHandler(
2831 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2832 void *baton) {
2833 Debugger &debugger = GetDebugger();
2834 IOHandlerSP io_handler_sp(
2835 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2836 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002837 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2838 llvm::StringRef(), // Continuation prompt
2839 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002840 debugger.GetUseColor(),
2841 0, // Don't show line numbers
2842 delegate)); // IOHandlerDelegate
2843
2844 if (io_handler_sp) {
2845 io_handler_sp->SetUserData(baton);
2846 if (asynchronously)
2847 debugger.PushIOHandler(io_handler_sp);
2848 else
2849 debugger.RunIOHandler(io_handler_sp);
2850 }
2851}
2852
2853bool CommandInterpreter::IsActive() {
2854 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2855}
2856
2857lldb::IOHandlerSP
2858CommandInterpreter::GetIOHandler(bool force_create,
2859 CommandInterpreterRunOptions *options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002860 // Always re-create the IOHandlerEditline in case the input changed. The old
2861 // instance might have had a non-interactive input and now it does or vice
2862 // versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002863 if (force_create || !m_command_io_handler_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002864 // Always re-create the IOHandlerEditline in case the input changed. The
2865 // old instance might have had a non-interactive input and now it does or
2866 // vice versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002867 uint32_t flags = 0;
2868
2869 if (options) {
2870 if (options->m_stop_on_continue == eLazyBoolYes)
2871 flags |= eHandleCommandFlagStopOnContinue;
2872 if (options->m_stop_on_error == eLazyBoolYes)
2873 flags |= eHandleCommandFlagStopOnError;
2874 if (options->m_stop_on_crash == eLazyBoolYes)
2875 flags |= eHandleCommandFlagStopOnCrash;
2876 if (options->m_echo_commands != eLazyBoolNo)
2877 flags |= eHandleCommandFlagEchoCommand;
2878 if (options->m_print_results != eLazyBoolNo)
2879 flags |= eHandleCommandFlagPrintResult;
2880 } else {
2881 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2882 }
2883
2884 m_command_io_handler_sp.reset(new IOHandlerEditline(
2885 m_debugger, IOHandler::Type::CommandInterpreter,
2886 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2887 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002888 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002889 false, // Don't enable multiple line input, just single line commands
2890 m_debugger.GetUseColor(),
2891 0, // Don't show line numbers
2892 *this));
2893 }
2894 return m_command_io_handler_sp;
2895}
2896
2897void CommandInterpreter::RunCommandInterpreter(
2898 bool auto_handle_events, bool spawn_thread,
2899 CommandInterpreterRunOptions &options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002900 // Always re-create the command interpreter when we run it in case any file
2901 // handles have changed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002902 bool force_create = true;
2903 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2904 m_stopped_for_crash = false;
2905
2906 if (auto_handle_events)
2907 m_debugger.StartEventHandlerThread();
2908
2909 if (spawn_thread) {
2910 m_debugger.StartIOHandlerThread();
2911 } else {
2912 m_debugger.ExecuteIOHandlers();
2913
2914 if (auto_handle_events)
2915 m_debugger.StopEventHandlerThread();
2916 }
2917}
2918
2919CommandObject *
2920CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2921 CommandReturnObject &result) {
2922 std::string scratch_command(command_line); // working copy so we don't modify
2923 // command_line unless we succeed
2924 CommandObject *cmd_obj = nullptr;
2925 StreamString revised_command_line;
2926 bool wants_raw_input = false;
2927 size_t actual_cmd_name_len = 0;
2928 std::string next_word;
2929 StringList matches;
2930 bool done = false;
2931 while (!done) {
2932 char quote_char = '\0';
2933 std::string suffix;
2934 ExtractCommand(scratch_command, next_word, suffix, quote_char);
2935 if (cmd_obj == nullptr) {
2936 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002937 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00002938 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002939 bool is_real_command =
2940 (is_alias == false) ||
2941 (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
2942 if (!is_real_command) {
2943 matches.Clear();
2944 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002945 cmd_obj =
2946 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002947 revised_command_line.Printf("%s", alias_result.c_str());
2948 if (cmd_obj) {
2949 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00002950 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002951 }
2952 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002953 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00002954 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
2955 actual_cmd_name_len += cmd_name.size();
2956 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002957 wants_raw_input = cmd_obj->WantsRawCommandString();
2958 } else {
2959 revised_command_line.Printf("%s", next_word.c_str());
2960 }
2961 }
2962 } else {
2963 if (cmd_obj->IsMultiwordObject()) {
2964 CommandObject *sub_cmd_obj =
2965 cmd_obj->GetSubcommandObject(next_word.c_str());
2966 if (sub_cmd_obj) {
Adrian Prantl05097242018-04-30 16:49:04 +00002967 // The subcommand's name includes the parent command's name, so
2968 // restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00002969 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
2970 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002971 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00002972 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002973 cmd_obj = sub_cmd_obj;
2974 wants_raw_input = cmd_obj->WantsRawCommandString();
2975 } else {
2976 if (quote_char)
2977 revised_command_line.Printf(" %c%s%s%c", quote_char,
2978 next_word.c_str(), suffix.c_str(),
2979 quote_char);
2980 else
2981 revised_command_line.Printf(" %s%s", next_word.c_str(),
2982 suffix.c_str());
2983 done = true;
2984 }
2985 } else {
2986 if (quote_char)
2987 revised_command_line.Printf(" %c%s%s%c", quote_char,
2988 next_word.c_str(), suffix.c_str(),
2989 quote_char);
2990 else
2991 revised_command_line.Printf(" %s%s", next_word.c_str(),
2992 suffix.c_str());
2993 done = true;
2994 }
2995 }
2996
2997 if (cmd_obj == nullptr) {
2998 const size_t num_matches = matches.GetSize();
2999 if (matches.GetSize() > 1) {
3000 StreamString error_msg;
3001 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3002 next_word.c_str());
3003
3004 for (uint32_t i = 0; i < num_matches; ++i) {
3005 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3006 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003007 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003008 } else {
3009 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003010 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003011 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3012 next_word.c_str());
3013 }
3014 result.SetStatus(eReturnStatusFailed);
3015 return nullptr;
3016 }
3017
3018 if (cmd_obj->IsMultiwordObject()) {
3019 if (!suffix.empty()) {
3020 result.AppendErrorWithFormat(
3021 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3022 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003023 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003024 next_word.empty() ? "" : next_word.c_str(),
3025 next_word.empty() ? " -- " : " ", suffix.c_str());
3026 result.SetStatus(eReturnStatusFailed);
3027 return nullptr;
3028 }
3029 } else {
3030 // If we found a normal command, we are done
3031 done = true;
3032 if (!suffix.empty()) {
3033 switch (suffix[0]) {
3034 case '/':
3035 // GDB format suffixes
3036 {
3037 Options *command_options = cmd_obj->GetOptions();
3038 if (command_options &&
3039 command_options->SupportsLongOption("gdb-format")) {
3040 std::string gdb_format_option("--gdb-format=");
3041 gdb_format_option += (suffix.c_str() + 1);
3042
Zachary Turnerc1564272016-11-16 21:15:24 +00003043 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003044 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3045 if (arg_terminator_idx != std::string::npos) {
3046 // Insert the gdb format option before the "--" that terminates
3047 // options
3048 gdb_format_option.append(1, ' ');
3049 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003050 revised_command_line.Clear();
3051 revised_command_line.PutCString(cmd);
3052 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003053 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3054
3055 if (wants_raw_input &&
3056 FindArgumentTerminator(cmd) == std::string::npos)
3057 revised_command_line.PutCString(" --");
3058 } else {
3059 result.AppendErrorWithFormat(
3060 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003061 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003062 result.SetStatus(eReturnStatusFailed);
3063 return nullptr;
3064 }
3065 }
3066 break;
3067
3068 default:
3069 result.AppendErrorWithFormat(
3070 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3071 result.SetStatus(eReturnStatusFailed);
3072 return nullptr;
3073 }
3074 }
3075 }
3076 if (scratch_command.empty())
3077 done = true;
3078 }
3079
3080 if (!scratch_command.empty())
3081 revised_command_line.Printf(" %s", scratch_command.c_str());
3082
3083 if (cmd_obj != NULL)
Zachary Turnerc1564272016-11-16 21:15:24 +00003084 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003085
3086 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003087}