blob: c57debab6f33328ef22f6bc4de565bae2b551794 [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, {},
Tatyana Krasnukhae40db052018-09-27 07:11:58 +000092 "If true, blank lines will be printed between between REPL submissions."}};
Kate Stoneb9c1b512016-09-06 20:57:50 +000093
94enum {
95 ePropertyExpandRegexAliases = 0,
96 ePropertyPromptOnQuit = 1,
97 ePropertyStopCmdSourceOnError = 2,
98 eSpaceReplPrompts = 3
Greg Clayton754a9362012-08-23 00:22:02 +000099};
100
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101ConstString &CommandInterpreter::GetStaticBroadcasterClass() {
102 static ConstString class_name("lldb.commandInterpreter");
103 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000104}
105
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106CommandInterpreter::CommandInterpreter(Debugger &debugger,
107 ScriptLanguage script_language,
108 bool synchronous_execution)
109 : Broadcaster(debugger.GetBroadcasterManager(),
110 CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
111 Properties(OptionValuePropertiesSP(
112 new OptionValueProperties(ConstString("interpreter")))),
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000113 IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114 m_debugger(debugger), m_synchronous_execution(synchronous_execution),
115 m_skip_lldbinit_files(false), m_skip_app_init_files(false),
116 m_script_interpreter_sp(), m_command_io_handler_sp(), m_comment_char('#'),
117 m_batch_command_mode(false), m_truncation_warning(eNoTruncation),
118 m_command_source_depth(0), m_num_errors(0), m_quit_requested(false),
119 m_stopped_for_crash(false) {
120 debugger.SetScriptLanguage(script_language);
121 SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit");
122 SetEventName(eBroadcastBitResetPrompt, "reset-prompt");
123 SetEventName(eBroadcastBitQuitCommandReceived, "quit");
124 CheckInWithManager();
125 m_collection_sp->Initialize(g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000126}
127
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128bool CommandInterpreter::GetExpandRegexAliases() const {
129 const uint32_t idx = ePropertyExpandRegexAliases;
130 return m_collection_sp->GetPropertyAtIndexAsBoolean(
131 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000132}
133
Kate Stoneb9c1b512016-09-06 20:57:50 +0000134bool CommandInterpreter::GetPromptOnQuit() const {
135 const uint32_t idx = ePropertyPromptOnQuit;
136 return m_collection_sp->GetPropertyAtIndexAsBoolean(
137 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000138}
Greg Clayton754a9362012-08-23 00:22:02 +0000139
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140void CommandInterpreter::SetPromptOnQuit(bool b) {
141 const uint32_t idx = ePropertyPromptOnQuit;
142 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ilia Kacf28be2015-03-23 22:45:13 +0000143}
144
Raphael Isemannc094d232018-07-11 17:18:01 +0000145void CommandInterpreter::AllowExitCodeOnQuit(bool allow) {
146 m_allow_exit_code = allow;
147 if (!allow)
148 m_quit_exit_code.reset();
149}
150
151bool CommandInterpreter::SetQuitExitCode(int exit_code) {
152 if (!m_allow_exit_code)
153 return false;
154 m_quit_exit_code = exit_code;
155 return true;
156}
157
158int CommandInterpreter::GetQuitExitCode(bool &exited) const {
159 exited = m_quit_exit_code.hasValue();
160 if (exited)
161 return *m_quit_exit_code;
162 return 0;
163}
164
Kate Stoneb9c1b512016-09-06 20:57:50 +0000165void CommandInterpreter::ResolveCommand(const char *command_line,
166 CommandReturnObject &result) {
167 std::string command = command_line;
168 if (ResolveCommandImpl(command, result) != nullptr) {
169 result.AppendMessageWithFormat("%s", command.c_str());
170 result.SetStatus(eReturnStatusSuccessFinishResult);
171 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000172}
173
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174bool CommandInterpreter::GetStopCmdSourceOnError() const {
175 const uint32_t idx = ePropertyStopCmdSourceOnError;
176 return m_collection_sp->GetPropertyAtIndexAsBoolean(
177 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000178}
179
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180bool CommandInterpreter::GetSpaceReplPrompts() const {
181 const uint32_t idx = eSpaceReplPrompts;
182 return m_collection_sp->GetPropertyAtIndexAsBoolean(
183 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callanan66810412015-10-19 23:11:07 +0000184}
185
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186void CommandInterpreter::Initialize() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000187 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
188 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000189
Kate Stoneb9c1b512016-09-06 20:57:50 +0000190 CommandReturnObject result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000191
Kate Stoneb9c1b512016-09-06 20:57:50 +0000192 LoadCommandDictionary();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000193
Kate Stoneb9c1b512016-09-06 20:57:50 +0000194 // An alias arguments vector to reuse - reset it before use...
195 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
196
197 // Set up some initial aliases.
198 CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
199 if (cmd_obj_sp) {
200 AddAlias("q", cmd_obj_sp);
201 AddAlias("exit", cmd_obj_sp);
202 }
203
204 cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
205 if (cmd_obj_sp)
206 AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
207
208 cmd_obj_sp = GetCommandSPExact("process detach", false);
209 if (cmd_obj_sp) {
210 AddAlias("detach", cmd_obj_sp);
211 }
212
213 cmd_obj_sp = GetCommandSPExact("process continue", false);
214 if (cmd_obj_sp) {
215 AddAlias("c", cmd_obj_sp);
216 AddAlias("continue", cmd_obj_sp);
217 }
218
219 cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
220 if (cmd_obj_sp)
221 AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
222
223 cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
224 if (cmd_obj_sp)
225 AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
226
227 cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
228 if (cmd_obj_sp) {
229 AddAlias("stepi", cmd_obj_sp);
230 AddAlias("si", cmd_obj_sp);
231 }
232
233 cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
234 if (cmd_obj_sp) {
235 AddAlias("nexti", cmd_obj_sp);
236 AddAlias("ni", cmd_obj_sp);
237 }
238
239 cmd_obj_sp = GetCommandSPExact("thread step-in", false);
240 if (cmd_obj_sp) {
241 AddAlias("s", cmd_obj_sp);
242 AddAlias("step", cmd_obj_sp);
243 CommandAlias *sif_alias = AddAlias(
244 "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
245 if (sif_alias) {
246 sif_alias->SetHelp("Step through the current block, stopping if you step "
247 "directly into a function whose name matches the "
248 "TargetFunctionName.");
249 sif_alias->SetSyntax("sif <TargetFunctionName>");
Caroline Ticeca90c472011-05-06 21:37:15 +0000250 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000252
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 cmd_obj_sp = GetCommandSPExact("thread step-over", false);
254 if (cmd_obj_sp) {
255 AddAlias("n", cmd_obj_sp);
256 AddAlias("next", cmd_obj_sp);
257 }
258
259 cmd_obj_sp = GetCommandSPExact("thread step-out", false);
260 if (cmd_obj_sp) {
261 AddAlias("finish", cmd_obj_sp);
262 }
263
264 cmd_obj_sp = GetCommandSPExact("frame select", false);
265 if (cmd_obj_sp) {
266 AddAlias("f", cmd_obj_sp);
267 }
268
269 cmd_obj_sp = GetCommandSPExact("thread select", false);
270 if (cmd_obj_sp) {
271 AddAlias("t", cmd_obj_sp);
272 }
273
274 cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
275 if (cmd_obj_sp) {
276 AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
277 AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
278 }
279
280 cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
281 if (cmd_obj_sp) {
282 AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
283 AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
284 }
285
286 cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
287 if (cmd_obj_sp)
288 AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
289
290 cmd_obj_sp = GetCommandSPExact("memory read", false);
291 if (cmd_obj_sp)
292 AddAlias("x", cmd_obj_sp);
293
294 cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
295 if (cmd_obj_sp)
296 AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
297
298 cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
299 if (cmd_obj_sp)
300 AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
301
302 cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
303 if (cmd_obj_sp)
304 AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
305
306 cmd_obj_sp = GetCommandSPExact("disassemble", false);
307 if (cmd_obj_sp)
308 AddAlias("dis", cmd_obj_sp);
309
310 cmd_obj_sp = GetCommandSPExact("disassemble", false);
311 if (cmd_obj_sp)
312 AddAlias("di", cmd_obj_sp);
313
314 cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
315 if (cmd_obj_sp)
316 AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
317
318 cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
319 if (cmd_obj_sp)
320 AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
321
322 cmd_obj_sp = GetCommandSPExact("target create", false);
323 if (cmd_obj_sp)
324 AddAlias("file", cmd_obj_sp);
325
326 cmd_obj_sp = GetCommandSPExact("target modules", false);
327 if (cmd_obj_sp)
328 AddAlias("image", cmd_obj_sp);
329
330 alias_arguments_vector_sp.reset(new OptionArgVector);
331
332 cmd_obj_sp = GetCommandSPExact("expression", false);
333 if (cmd_obj_sp) {
334 AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
335 AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
336 AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
337 if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
338 po->SetHelp("Evaluate an expression on the current thread. Displays any "
339 "returned value with formatting "
340 "controlled by the type's author.");
341 po->SetHelpLong("");
Johnny Chen6d675242012-08-24 18:15:45 +0000342 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343 AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
344 AddAlias("poarray", cmd_obj_sp,
345 "--object-description --element-count %1 --")
346 ->SetHelpLong("");
347 }
Johnny Chen6d675242012-08-24 18:15:45 +0000348
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 cmd_obj_sp = GetCommandSPExact("process kill", false);
350 if (cmd_obj_sp) {
351 AddAlias("kill", cmd_obj_sp);
352 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000353
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 cmd_obj_sp = GetCommandSPExact("process launch", false);
355 if (cmd_obj_sp) {
Chaoren Lin6fc5c7f2016-02-26 03:36:27 +0000356 alias_arguments_vector_sp.reset(new OptionArgVector);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000357#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
358 AddAlias("r", cmd_obj_sp, "--");
359 AddAlias("run", cmd_obj_sp, "--");
Jason Molenda85da3122012-07-06 02:46:23 +0000360#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361#if defined(__APPLE__)
362 std::string shell_option;
363 shell_option.append("--shell-expand-args");
364 shell_option.append(" true");
365 shell_option.append(" --");
366 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
367 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
368#else
369 StreamString defaultshell;
370 defaultshell.Printf("--shell=%s --",
371 HostInfo::GetDefaultShell().GetPath().c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +0000372 AddAlias("r", cmd_obj_sp, defaultshell.GetString());
373 AddAlias("run", cmd_obj_sp, defaultshell.GetString());
Jason Molenda85da3122012-07-06 02:46:23 +0000374#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000375#endif
376 }
377
378 cmd_obj_sp = GetCommandSPExact("target symbols add", false);
379 if (cmd_obj_sp) {
380 AddAlias("add-dsym", cmd_obj_sp);
381 }
382
383 cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
384 if (cmd_obj_sp) {
385 AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
386 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000387}
388
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389void CommandInterpreter::Clear() {
390 m_command_io_handler_sp.reset();
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000391
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 if (m_script_interpreter_sp)
393 m_script_interpreter_sp->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000394}
395
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
397 // This function has not yet been implemented.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000398
Kate Stoneb9c1b512016-09-06 20:57:50 +0000399 // Look for any embedded script command
400 // If found,
401 // get interpreter object from the command dictionary,
402 // call execute_one_command on it,
403 // get the results as a string,
404 // substitute that string for current stuff.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000405
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 return arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000407}
408
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409void CommandInterpreter::LoadCommandDictionary() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000410 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
411 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000412
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000414
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
416 m_command_dict["breakpoint"] =
417 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
418 m_command_dict["bugreport"] =
419 CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
420 m_command_dict["command"] =
421 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
422 m_command_dict["disassemble"] =
423 CommandObjectSP(new CommandObjectDisassemble(*this));
424 m_command_dict["expression"] =
425 CommandObjectSP(new CommandObjectExpression(*this));
426 m_command_dict["frame"] =
427 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
428 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
429 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
430 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
431 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
432 m_command_dict["platform"] =
433 CommandObjectSP(new CommandObjectPlatform(*this));
434 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
435 m_command_dict["process"] =
436 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
437 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
438 m_command_dict["register"] =
439 CommandObjectSP(new CommandObjectRegister(*this));
440 m_command_dict["script"] =
441 CommandObjectSP(new CommandObjectScript(*this, script_language));
442 m_command_dict["settings"] =
443 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
444 m_command_dict["source"] =
445 CommandObjectSP(new CommandObjectMultiwordSource(*this));
Davide Italiano24fff242018-04-13 18:02:39 +0000446 m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000447 m_command_dict["target"] =
448 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
449 m_command_dict["thread"] =
450 CommandObjectSP(new CommandObjectMultiwordThread(*this));
451 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
452 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
453 m_command_dict["watchpoint"] =
454 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
455 m_command_dict["language"] =
456 CommandObjectSP(new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000457
Kate Stoneb9c1b512016-09-06 20:57:50 +0000458 const char *break_regexes[][2] = {
459 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
460 "breakpoint set --file '%1' --line %2"},
461 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
462 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
463 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
464 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
465 "breakpoint set --name '%1'"},
466 {"^(-.*)$", "breakpoint set %1"},
467 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
468 "breakpoint set --name '%2' --shlib '%1'"},
469 {"^\\&(.*[^[:space:]])[[:space:]]*$",
470 "breakpoint set --name '%1' --skip-prologue=0"},
471 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
472 "breakpoint set --name '%1'"}};
Kate Stone7428a182016-07-14 22:03:10 +0000473
Kate Stoneb9c1b512016-09-06 20:57:50 +0000474 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000475
Kate Stoneb9c1b512016-09-06 20:57:50 +0000476 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap(
477 new CommandObjectRegexCommand(
478 *this, "_regexp-break",
Raphael Isemann129fe892018-07-30 21:41:13 +0000479 "Set a breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000480 "\n"
481 "_regexp-break <filename>:<linenum>\n"
482 " main.c:12 // Break at line 12 of "
483 "main.c\n\n"
484 "_regexp-break <linenum>\n"
485 " 12 // Break at line 12 of current "
486 "file\n\n"
487 "_regexp-break 0x<address>\n"
488 " 0x1234000 // Break at address "
489 "0x1234000\n\n"
490 "_regexp-break <name>\n"
491 " main // Break in 'main' after the "
492 "prologue\n\n"
493 "_regexp-break &<name>\n"
494 " &main // Break at first instruction "
495 "in 'main'\n\n"
496 "_regexp-break <module>`<name>\n"
497 " libc.so`malloc // Break in 'malloc' from "
498 "'libc.so'\n\n"
499 "_regexp-break /<source-regex>/\n"
500 " /break here/ // Break on source lines in "
501 "current file\n"
502 " // containing text 'break "
503 "here'.\n",
504 2, CommandCompletions::eSymbolCompletion |
505 CommandCompletions::eSourceFileCompletion,
506 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000507
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508 if (break_regex_cmd_ap.get()) {
509 bool success = true;
510 for (size_t i = 0; i < num_regexes; i++) {
511 success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0],
512 break_regexes[i][1]);
513 if (!success)
514 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000515 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000516 success =
517 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Jim Inghamffba2292011-03-22 02:29:32 +0000518
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 if (success) {
520 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
521 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
Jim Inghamca36cd12012-10-05 19:16:31 +0000522 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000523 }
Jim Inghamca36cd12012-10-05 19:16:31 +0000524
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap(
526 new CommandObjectRegexCommand(
527 *this, "_regexp-tbreak",
Raphael Isemann129fe892018-07-30 21:41:13 +0000528 "Set a one-shot breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000529 "\n"
530 "_regexp-break <filename>:<linenum>\n"
531 " main.c:12 // Break at line 12 of "
532 "main.c\n\n"
533 "_regexp-break <linenum>\n"
534 " 12 // Break at line 12 of current "
535 "file\n\n"
536 "_regexp-break 0x<address>\n"
537 " 0x1234000 // Break at address "
538 "0x1234000\n\n"
539 "_regexp-break <name>\n"
540 " main // Break in 'main' after the "
541 "prologue\n\n"
542 "_regexp-break &<name>\n"
543 " &main // Break at first instruction "
544 "in 'main'\n\n"
545 "_regexp-break <module>`<name>\n"
546 " libc.so`malloc // Break in 'malloc' from "
547 "'libc.so'\n\n"
548 "_regexp-break /<source-regex>/\n"
549 " /break here/ // Break on source lines in "
550 "current file\n"
551 " // containing text 'break "
552 "here'.\n",
553 2, CommandCompletions::eSymbolCompletion |
554 CommandCompletions::eSourceFileCompletion,
555 false));
556
557 if (tbreak_regex_cmd_ap.get()) {
558 bool success = true;
559 for (size_t i = 0; i < num_regexes; i++) {
560 // If you add a resultant command string longer than 1024 characters be
561 // sure to increase the size of this buffer.
562 char buffer[1024];
563 int num_printed =
Frederic Riss49c9d8b2018-06-18 04:34:33 +0000564 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1");
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000565 lldbassert(num_printed < 1024);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566 UNUSED_IF_ASSERT_DISABLED(num_printed);
567 success =
568 tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer);
569 if (!success)
570 break;
Johnny Chen6d675242012-08-24 18:15:45 +0000571 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000572 success =
573 tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Kate Stone7428a182016-07-14 22:03:10 +0000574
Kate Stoneb9c1b512016-09-06 20:57:50 +0000575 if (success) {
576 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
577 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
578 tbreak_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000579 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000580 }
Kate Stone7428a182016-07-14 22:03:10 +0000581
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap(
583 new CommandObjectRegexCommand(
584 *this, "_regexp-attach", "Attach to process by ID or name.",
585 "_regexp-attach <pid> | <process-name>", 2, 0, false));
586 if (attach_regex_cmd_ap.get()) {
587 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
588 "process attach --pid %1") &&
589 attach_regex_cmd_ap->AddRegexCommand(
590 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
591 // specified get passed to
592 // 'process attach'
593 attach_regex_cmd_ap->AddRegexCommand("^(.+)$",
594 "process attach --name '%1'") &&
595 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) {
596 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
597 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
598 attach_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000599 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000601
Kate Stoneb9c1b512016-09-06 20:57:50 +0000602 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap(
603 new CommandObjectRegexCommand(*this, "_regexp-down",
604 "Select a newer stack frame. Defaults to "
605 "moving one frame, a numeric argument can "
606 "specify an arbitrary number.",
607 "_regexp-down [<count>]", 2, 0, false));
608 if (down_regex_cmd_ap.get()) {
609 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
610 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
611 "frame select -r -%1")) {
612 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
613 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000614 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000616
Kate Stoneb9c1b512016-09-06 20:57:50 +0000617 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap(
618 new CommandObjectRegexCommand(
619 *this, "_regexp-up",
620 "Select an older stack frame. Defaults to moving one "
621 "frame, a numeric argument can specify an arbitrary number.",
622 "_regexp-up [<count>]", 2, 0, false));
623 if (up_regex_cmd_ap.get()) {
624 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
625 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
626 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
627 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000628 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000630
Kate Stoneb9c1b512016-09-06 20:57:50 +0000631 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap(
632 new CommandObjectRegexCommand(
633 *this, "_regexp-display",
634 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
635 "_regexp-display expression", 2, 0, false));
636 if (display_regex_cmd_ap.get()) {
637 if (display_regex_cmd_ap->AddRegexCommand(
638 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
639 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
640 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
641 display_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000642 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000643 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000644
Kate Stoneb9c1b512016-09-06 20:57:50 +0000645 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap(
646 new CommandObjectRegexCommand(
647 *this, "_regexp-undisplay", "Stop displaying expression at every "
648 "stop (specified by stop-hook index.)",
649 "_regexp-undisplay stop-hook-number", 2, 0, false));
650 if (undisplay_regex_cmd_ap.get()) {
651 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
652 "target stop-hook delete %1")) {
653 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
654 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
655 undisplay_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000656 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000658
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap(
660 new CommandObjectRegexCommand(
661 *this, "gdb-remote", "Connect to a process via remote GDB server. "
662 "If no host is specifed, localhost is assumed.",
663 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
664 if (connect_gdb_remote_cmd_ap.get()) {
665 if (connect_gdb_remote_cmd_ap->AddRegexCommand(
Chris Bieneman51978f52017-04-27 16:13:58 +0000666 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
667 "process connect --plugin gdb-remote connect://%1:%2") &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668 connect_gdb_remote_cmd_ap->AddRegexCommand(
669 "^([[:digit:]]+)$",
670 "process connect --plugin gdb-remote connect://localhost:%1")) {
671 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
672 m_command_dict[command_sp->GetCommandName()] = command_sp;
Jason Molenda4cddfed2012-10-05 05:29:32 +0000673 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000674 }
Jason Molenda4cddfed2012-10-05 05:29:32 +0000675
Kate Stoneb9c1b512016-09-06 20:57:50 +0000676 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap(
677 new CommandObjectRegexCommand(
678 *this, "kdp-remote", "Connect to a process via remote KDP server. "
679 "If no UDP port is specified, port 41139 is "
680 "assumed.",
681 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
682 if (connect_kdp_remote_cmd_ap.get()) {
683 if (connect_kdp_remote_cmd_ap->AddRegexCommand(
684 "^([^:]+:[[:digit:]]+)$",
685 "process connect --plugin kdp-remote udp://%1") &&
686 connect_kdp_remote_cmd_ap->AddRegexCommand(
687 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
688 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
689 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Clayton6bade322013-02-01 23:33:03 +0000690 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691 }
Greg Clayton6bade322013-02-01 23:33:03 +0000692
Kate Stoneb9c1b512016-09-06 20:57:50 +0000693 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap(
694 new CommandObjectRegexCommand(
695 *this, "_regexp-bt",
696 "Show the current thread's call stack. Any numeric argument "
697 "displays at most that many "
698 "frames. The argument 'all' displays all threads.",
699 "bt [<digit> | all]", 2, 0, false));
700 if (bt_regex_cmd_ap.get()) {
701 // accept but don't document "bt -c <number>" -- before bt was a regex
Adrian Prantl05097242018-04-30 16:49:04 +0000702 // command if you wanted to backtrace three frames you would do "bt -c 3"
703 // but the intention is to have this emulate the gdb "bt" command and so
704 // now "bt 3" is the preferred form, in line with gdb.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$",
706 "thread backtrace -c %1") &&
707 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$",
708 "thread backtrace -c %1") &&
709 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
710 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) {
711 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
712 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Claytonef5651d2013-02-12 18:52:24 +0000713 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000714 }
Greg Claytonef5651d2013-02-12 18:52:24 +0000715
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap(
717 new CommandObjectRegexCommand(
718 *this, "_regexp-list",
719 "List relevant source code using one of several shorthand formats.",
720 "\n"
721 "_regexp-list <file>:<line> // List around specific file/line\n"
722 "_regexp-list <line> // List current file around specified "
723 "line\n"
724 "_regexp-list <function-name> // List specified function\n"
725 "_regexp-list 0x<address> // List around specified address\n"
726 "_regexp-list -[<count>] // List previous <count> lines\n"
727 "_regexp-list // List subsequent lines",
728 2, CommandCompletions::eSourceFileCompletion, false));
729 if (list_regex_cmd_ap.get()) {
730 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
731 "source list --line %1") &&
732 list_regex_cmd_ap->AddRegexCommand(
733 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
734 "]*$",
735 "source list --file '%1' --line %2") &&
736 list_regex_cmd_ap->AddRegexCommand(
737 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
738 "source list --address %1") &&
739 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$",
740 "source list --reverse") &&
741 list_regex_cmd_ap->AddRegexCommand(
742 "^-([[:digit:]]+)[[:space:]]*$",
743 "source list --reverse --count %1") &&
744 list_regex_cmd_ap->AddRegexCommand("^(.+)$",
745 "source list --name \"%1\"") &&
746 list_regex_cmd_ap->AddRegexCommand("^$", "source list")) {
747 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
748 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
Richard Mittonf86248d2013-09-12 02:20:34 +0000749 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750 }
Richard Mittonf86248d2013-09-12 02:20:34 +0000751
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap(
753 new CommandObjectRegexCommand(
754 *this, "_regexp-env",
755 "Shorthand for viewing and setting environment variables.",
756 "\n"
757 "_regexp-env // Show enrivonment\n"
758 "_regexp-env <name>=<value> // Set an environment variable",
759 2, 0, false));
760 if (env_regex_cmd_ap.get()) {
761 if (env_regex_cmd_ap->AddRegexCommand("^$",
762 "settings show target.env-vars") &&
763 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
764 "settings set target.env-vars %1")) {
765 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
766 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
767 }
768 }
769
770 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap(
771 new CommandObjectRegexCommand(
772 *this, "_regexp-jump", "Set the program counter to a new address.",
773 "\n"
774 "_regexp-jump <line>\n"
775 "_regexp-jump +<line-offset> | -<line-offset>\n"
776 "_regexp-jump <file>:<line>\n"
777 "_regexp-jump *<addr>\n",
778 2, 0, false));
779 if (jump_regex_cmd_ap.get()) {
780 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$",
781 "thread jump --addr %1") &&
782 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
783 "thread jump --line %1") &&
784 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$",
785 "thread jump --file %1 --line %2") &&
786 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$",
787 "thread jump --by %1")) {
788 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
789 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
790 }
791 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000792}
793
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794int CommandInterpreter::GetCommandNamesMatchingPartialString(
Raphael Isemann7f888292018-09-13 21:26:00 +0000795 const char *cmd_str, bool include_aliases, StringList &matches,
796 StringList &descriptions) {
797 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches,
798 &descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000799
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 if (include_aliases) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000801 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches,
802 &descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000803 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000804
Kate Stoneb9c1b512016-09-06 20:57:50 +0000805 return matches.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000806}
807
Raphael Isemann7f888292018-09-13 21:26:00 +0000808CommandObjectSP
809CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases,
810 bool exact, StringList *matches,
811 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000812 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000813
Zachary Turnera4496982016-10-05 21:14:38 +0000814 std::string cmd = cmd_str;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000815
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816 if (HasCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000817 auto pos = m_command_dict.find(cmd);
Greg Claytonb5472782015-01-09 19:08:20 +0000818 if (pos != m_command_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000819 command_sp = pos->second;
820 }
821
822 if (include_aliases && HasAliases()) {
823 auto alias_pos = m_alias_dict.find(cmd);
824 if (alias_pos != m_alias_dict.end())
825 command_sp = alias_pos->second;
826 }
827
828 if (HasUserCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000829 auto pos = m_user_dict.find(cmd);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000830 if (pos != m_user_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000831 command_sp = pos->second;
832 }
833
834 if (!exact && !command_sp) {
835 // We will only get into here if we didn't find any exact matches.
836
837 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
838
839 StringList local_matches;
840 if (matches == nullptr)
841 matches = &local_matches;
842
843 unsigned int num_cmd_matches = 0;
844 unsigned int num_alias_matches = 0;
845 unsigned int num_user_matches = 0;
846
847 // Look through the command dictionaries one by one, and if we get only one
Adrian Prantl05097242018-04-30 16:49:04 +0000848 // match from any of them in toto, then return that, otherwise return an
849 // empty CommandObjectSP and the list of matches.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850
851 if (HasCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000852 num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str,
853 *matches, descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000854 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000855
856 if (num_cmd_matches == 1) {
857 cmd.assign(matches->GetStringAtIndex(0));
Zachary Turnera4496982016-10-05 21:14:38 +0000858 auto pos = m_command_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000859 if (pos != m_command_dict.end())
860 real_match_sp = pos->second;
861 }
862
863 if (include_aliases && HasAliases()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000864 num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str,
865 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866 }
867
868 if (num_alias_matches == 1) {
869 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
870 auto alias_pos = m_alias_dict.find(cmd);
871 if (alias_pos != m_alias_dict.end())
872 alias_match_sp = alias_pos->second;
873 }
874
875 if (HasUserCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000876 num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str,
877 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000878 }
879
880 if (num_user_matches == 1) {
881 cmd.assign(
882 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
883
Zachary Turnera4496982016-10-05 21:14:38 +0000884 auto pos = m_user_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885 if (pos != m_user_dict.end())
886 user_match_sp = pos->second;
887 }
888
889 // If we got exactly one match, return that, otherwise return the match
890 // list.
891
892 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
893 if (num_cmd_matches)
894 return real_match_sp;
895 else if (num_alias_matches)
896 return alias_match_sp;
897 else
898 return user_match_sp;
899 }
900 } else if (matches && command_sp) {
Zachary Turnera4496982016-10-05 21:14:38 +0000901 matches->AppendString(cmd_str);
Raphael Isemann7f888292018-09-13 21:26:00 +0000902 if (descriptions)
903 descriptions->AppendString(command_sp->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904 }
905
906 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000907}
908
Zachary Turnera4496982016-10-05 21:14:38 +0000909bool CommandInterpreter::AddCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910 const lldb::CommandObjectSP &cmd_sp,
911 bool can_replace) {
912 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000913 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
914 "tried to add a CommandObject from a different interpreter");
Kate Stonea487aa42015-01-15 00:52:41 +0000915
Zachary Turnera4496982016-10-05 21:14:38 +0000916 if (name.empty())
917 return false;
918
919 std::string name_sstr(name);
920 auto name_iter = m_command_dict.find(name_sstr);
921 if (name_iter != m_command_dict.end()) {
922 if (!can_replace || !name_iter->second->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000923 return false;
Zachary Turnera4496982016-10-05 21:14:38 +0000924 name_iter->second = cmd_sp;
925 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000926 m_command_dict[name_sstr] = cmd_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000927 }
Zachary Turnera4496982016-10-05 21:14:38 +0000928 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000929}
930
Zachary Turnera483f572016-10-05 21:14:49 +0000931bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000932 const lldb::CommandObjectSP &cmd_sp,
933 bool can_replace) {
934 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000935 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
936 "tried to add a CommandObject from a different interpreter");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000937
Kate Stoneb9c1b512016-09-06 20:57:50 +0000938 if (!name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000939 // do not allow replacement of internal commands
Zachary Turnera483f572016-10-05 21:14:49 +0000940 if (CommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941 if (can_replace == false)
942 return false;
943 if (m_command_dict[name]->IsRemovable() == false)
Greg Clayton5a314712011-10-14 07:41:33 +0000944 return false;
945 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000946
Zachary Turnera483f572016-10-05 21:14:49 +0000947 if (UserCommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948 if (can_replace == false)
949 return false;
950 if (m_user_dict[name]->IsRemovable() == false)
951 return false;
Caroline Tice844d2302010-12-09 22:52:49 +0000952 }
953
Kate Stoneb9c1b512016-09-06 20:57:50 +0000954 m_user_dict[name] = cmd_sp;
955 return true;
956 }
957 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000958}
959
Zachary Turnera4496982016-10-05 21:14:38 +0000960CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
961 bool include_aliases) const {
962 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963 // it's a multi-word command.
964 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000965
Zachary Turnera4496982016-10-05 21:14:38 +0000966 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000967 return ret_val;
968
969 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +0000970 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 else {
972 // We have a multi-word command (seemingly), so we need to do more work.
973 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +0000974 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000975 include_aliases, true, nullptr);
976 if (cmd_obj_sp.get() != nullptr) {
Adrian Prantl05097242018-04-30 16:49:04 +0000977 // Loop through the rest of the words in the command (everything passed
978 // in was supposed to be part of a command name), and find the
979 // appropriate sub-command SP for each command word....
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980 size_t end = cmd_words.GetArgumentCount();
981 for (size_t j = 1; j < end; ++j) {
982 if (cmd_obj_sp->IsMultiwordObject()) {
983 cmd_obj_sp =
984 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
985 if (cmd_obj_sp.get() == nullptr)
986 // The sub-command name was invalid. Fail and return the empty
987 // 'ret_val'.
988 return ret_val;
989 } else
990 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +0000991 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000992 return ret_val;
993 }
994 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +0000995 // command objects for them. Assign the last object retrieved to
996 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000997 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000998 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999 }
1000 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001001}
1002
Raphael Isemann7f888292018-09-13 21:26:00 +00001003CommandObject *
1004CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
1005 StringList *matches,
1006 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007 CommandObject *command_obj =
Raphael Isemann7f888292018-09-13 21:26:00 +00001008 GetCommandSP(cmd_str, false, true, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001009
Kate Stoneb9c1b512016-09-06 20:57:50 +00001010 // If we didn't find an exact match to the command string in the commands,
Adrian Prantl05097242018-04-30 16:49:04 +00001011 // look in the aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012
1013 if (command_obj)
1014 return command_obj;
1015
Raphael Isemann7f888292018-09-13 21:26:00 +00001016 command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001017
1018 if (command_obj)
1019 return command_obj;
1020
1021 // If there wasn't an exact match then look for an inexact one in just the
1022 // commands
Zachary Turnera4496982016-10-05 21:14:38 +00001023 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001024
1025 // Finally, if there wasn't an inexact match among the commands, look for an
Adrian Prantl05097242018-04-30 16:49:04 +00001026 // inexact match in both the commands and aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001027
1028 if (command_obj) {
1029 if (matches)
1030 matches->AppendString(command_obj->GetCommandName());
Raphael Isemann7f888292018-09-13 21:26:00 +00001031 if (descriptions)
1032 descriptions->AppendString(command_obj->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033 return command_obj;
1034 }
1035
Raphael Isemann7f888292018-09-13 21:26:00 +00001036 return GetCommandSP(cmd_str, true, false, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001037}
1038
Zachary Turnera483f572016-10-05 21:14:49 +00001039bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001040 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001041}
1042
Zachary Turnera483f572016-10-05 21:14:49 +00001043bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1044 std::string &full_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1046 if (exact_match) {
1047 full_name.assign(cmd);
1048 return exact_match;
1049 } else {
1050 StringList matches;
1051 size_t num_alias_matches;
1052 num_alias_matches =
1053 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1054 if (num_alias_matches == 1) {
1055 // Make sure this isn't shadowing a command in the regular command space:
1056 StringList regular_matches;
1057 const bool include_aliases = false;
1058 const bool exact = false;
1059 CommandObjectSP cmd_obj_sp(
1060 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1061 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1062 return false;
1063 else {
1064 full_name.assign(matches.GetStringAtIndex(0));
1065 return true;
1066 }
1067 } else
1068 return false;
1069 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070}
1071
Zachary Turnera483f572016-10-05 21:14:49 +00001072bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001074}
1075
Zachary Turnera483f572016-10-05 21:14:49 +00001076bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001078}
1079
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080CommandAlias *
Zachary Turnera483f572016-10-05 21:14:49 +00001081CommandInterpreter::AddAlias(llvm::StringRef alias_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001082 lldb::CommandObjectSP &command_obj_sp,
Zachary Turnera483f572016-10-05 21:14:49 +00001083 llvm::StringRef args_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001084 if (command_obj_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001085 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1086 "tried to add a CommandObject from a different interpreter");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001087
1088 std::unique_ptr<CommandAlias> command_alias_up(
1089 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1090
1091 if (command_alias_up && command_alias_up->IsValid()) {
1092 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1093 return command_alias_up.release();
1094 }
1095
1096 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001097}
1098
Zachary Turnera483f572016-10-05 21:14:49 +00001099bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100 auto pos = m_alias_dict.find(alias_name);
1101 if (pos != m_alias_dict.end()) {
1102 m_alias_dict.erase(pos);
1103 return true;
1104 }
1105 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001106}
1107
Zachary Turnera483f572016-10-05 21:14:49 +00001108bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109 auto pos = m_command_dict.find(cmd);
1110 if (pos != m_command_dict.end()) {
1111 if (pos->second->IsRemovable()) {
1112 // Only regular expression objects or python commands are removable
1113 m_command_dict.erase(pos);
1114 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001115 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001116 }
1117 return false;
1118}
Zachary Turnera483f572016-10-05 21:14:49 +00001119bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001120 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1121 if (pos != m_user_dict.end()) {
1122 m_user_dict.erase(pos);
1123 return true;
1124 }
1125 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001126}
1127
Kate Stoneb9c1b512016-09-06 20:57:50 +00001128void CommandInterpreter::GetHelp(CommandReturnObject &result,
1129 uint32_t cmd_types) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001130 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1131 if (!help_prologue.empty()) {
1132 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1133 help_prologue);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001134 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001135
Kate Stoneb9c1b512016-09-06 20:57:50 +00001136 CommandObject::CommandMap::const_iterator pos;
1137 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001138
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1140 result.AppendMessage("Debugger commands:");
1141 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001142
Kate Stoneb9c1b512016-09-06 20:57:50 +00001143 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1144 if (!(cmd_types & eCommandTypesHidden) &&
1145 (pos->first.compare(0, 1, "_") == 0))
1146 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001147
Zachary Turner0ac5f982016-11-08 04:12:42 +00001148 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1149 pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001150 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001151 result.AppendMessage("");
1152 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001153
Kate Stoneb9c1b512016-09-06 20:57:50 +00001154 if (!m_alias_dict.empty() &&
1155 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1156 result.AppendMessageWithFormat(
1157 "Current command abbreviations "
1158 "(type '%shelp command alias' for more info):\n",
1159 GetCommandPrefix());
1160 result.AppendMessage("");
1161 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001162
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1164 ++alias_pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001165 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
Kate Stoneb9c1b512016-09-06 20:57:50 +00001166 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001167 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168 result.AppendMessage("");
1169 }
Greg Clayton14a35512011-09-11 00:01:44 +00001170
Kate Stoneb9c1b512016-09-06 20:57:50 +00001171 if (!m_user_dict.empty() &&
1172 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1173 result.AppendMessage("Current user-defined commands:");
1174 result.AppendMessage("");
1175 max_len = FindLongestCommandWord(m_user_dict);
1176 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001177 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1178 pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001179 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001180 result.AppendMessage("");
1181 }
Greg Clayton14a35512011-09-11 00:01:44 +00001182
Kate Stoneb9c1b512016-09-06 20:57:50 +00001183 result.AppendMessageWithFormat(
1184 "For more information on any command, type '%shelp <command-name>'.\n",
1185 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001186}
1187
Zachary Turnera01bccd2016-10-05 21:14:56 +00001188CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1189 llvm::StringRef &command_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190 // This function finds the final, lowest-level, alias-resolved command object
Adrian Prantl05097242018-04-30 16:49:04 +00001191 // whose 'Execute' function will eventually be invoked by the given command
1192 // line.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001193
1194 CommandObject *cmd_obj = nullptr;
1195 size_t start = command_string.find_first_not_of(k_white_space);
1196 size_t end = 0;
1197 bool done = false;
1198 while (!done) {
1199 if (start != std::string::npos) {
1200 // Get the next word from command_string.
1201 end = command_string.find_first_of(k_white_space, start);
1202 if (end == std::string::npos)
1203 end = command_string.size();
1204 std::string cmd_word = command_string.substr(start, end - start);
1205
1206 if (cmd_obj == nullptr)
1207 // Since cmd_obj is NULL we are on our first time through this loop.
Zachary Turnera01bccd2016-10-05 21:14:56 +00001208 // Check to see if cmd_word is a valid command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001209 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 else if (cmd_obj->IsMultiwordObject()) {
1211 // Our current object is a multi-word object; see if the cmd_word is a
1212 // valid sub-command for our object.
1213 CommandObject *sub_cmd_obj =
1214 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1215 if (sub_cmd_obj)
1216 cmd_obj = sub_cmd_obj;
1217 else // cmd_word was not a valid sub-command word, so we are done
1218 done = true;
1219 } else
1220 // We have a cmd_obj and it is not a multi-word object, so we are done.
1221 done = true;
1222
1223 // If we didn't find a valid command object, or our command object is not
Zachary Turnera01bccd2016-10-05 21:14:56 +00001224 // a multi-word object, or we are at the end of the command_string, then
1225 // we are done. Otherwise, find the start of the next word.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001226
1227 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1228 end >= command_string.size())
1229 done = true;
1230 else
1231 start = command_string.find_first_not_of(k_white_space, end);
1232 } else
1233 // Unable to find any more words.
1234 done = true;
1235 }
1236
Zachary Turnera01bccd2016-10-05 21:14:56 +00001237 command_string = command_string.substr(end);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001238 return cmd_obj;
1239}
1240
1241static const char *k_valid_command_chars =
1242 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1243static void StripLeadingSpaces(std::string &s) {
1244 if (!s.empty()) {
1245 size_t pos = s.find_first_not_of(k_white_space);
1246 if (pos == std::string::npos)
1247 s.clear();
1248 else if (pos == 0)
1249 return;
1250 s.erase(0, pos);
1251 }
1252}
1253
1254static size_t FindArgumentTerminator(const std::string &s) {
1255 const size_t s_len = s.size();
1256 size_t offset = 0;
1257 while (offset < s_len) {
1258 size_t pos = s.find("--", offset);
1259 if (pos == std::string::npos)
1260 break;
1261 if (pos > 0) {
1262 if (isspace(s[pos - 1])) {
Adrian Prantl05097242018-04-30 16:49:04 +00001263 // Check if the string ends "\s--" (where \s is a space character) or
1264 // if we have "\s--\s".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1266 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001267 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001268 }
1269 }
1270 offset = pos + 2;
1271 }
1272 return std::string::npos;
1273}
1274
1275static bool ExtractCommand(std::string &command_string, std::string &command,
1276 std::string &suffix, char &quote_char) {
1277 command.clear();
1278 suffix.clear();
1279 StripLeadingSpaces(command_string);
1280
1281 bool result = false;
1282 quote_char = '\0';
1283
1284 if (!command_string.empty()) {
1285 const char first_char = command_string[0];
1286 if (first_char == '\'' || first_char == '"') {
1287 quote_char = first_char;
1288 const size_t end_quote_pos = command_string.find(quote_char, 1);
1289 if (end_quote_pos == std::string::npos) {
1290 command.swap(command_string);
1291 command_string.erase();
1292 } else {
1293 command.assign(command_string, 1, end_quote_pos - 1);
1294 if (end_quote_pos + 1 < command_string.size())
1295 command_string.erase(0, command_string.find_first_not_of(
1296 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001297 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298 command_string.erase();
1299 }
1300 } else {
1301 const size_t first_space_pos =
1302 command_string.find_first_of(k_white_space);
1303 if (first_space_pos == std::string::npos) {
1304 command.swap(command_string);
1305 command_string.erase();
1306 } else {
1307 command.assign(command_string, 0, first_space_pos);
1308 command_string.erase(0, command_string.find_first_not_of(
1309 k_white_space, first_space_pos));
1310 }
1311 }
1312 result = true;
1313 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001314
Kate Stoneb9c1b512016-09-06 20:57:50 +00001315 if (!command.empty()) {
1316 // actual commands can't start with '-' or '_'
1317 if (command[0] != '-' && command[0] != '_') {
1318 size_t pos = command.find_first_not_of(k_valid_command_chars);
1319 if (pos > 0 && pos != std::string::npos) {
1320 suffix.assign(command.begin() + pos, command.end());
1321 command.erase(pos);
1322 }
1323 }
1324 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001325
Kate Stoneb9c1b512016-09-06 20:57:50 +00001326 return result;
1327}
1328
1329CommandObject *CommandInterpreter::BuildAliasResult(
Zachary Turnera483f572016-10-05 21:14:49 +00001330 llvm::StringRef alias_name, std::string &raw_input_string,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001331 std::string &alias_result, CommandReturnObject &result) {
1332 CommandObject *alias_cmd_obj = nullptr;
1333 Args cmd_args(raw_input_string);
1334 alias_cmd_obj = GetCommandObject(alias_name);
1335 StreamString result_str;
1336
Zachary Turner5c28c662016-10-03 23:20:36 +00001337 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1338 alias_result.clear();
1339 return alias_cmd_obj;
1340 }
1341 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1342 ((CommandAlias *)alias_cmd_obj)->Desugar();
1343 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1344 alias_cmd_obj = desugared.first.get();
1345 std::string alias_name_str = alias_name;
1346 if ((cmd_args.GetArgumentCount() == 0) ||
1347 (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0))
1348 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001349
Zachary Turnera4496982016-10-05 21:14:38 +00001350 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001351
Zachary Turner5c28c662016-10-03 23:20:36 +00001352 if (!option_arg_vector_sp.get()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001353 alias_result = result_str.GetString();
Zachary Turner5c28c662016-10-03 23:20:36 +00001354 return alias_cmd_obj;
1355 }
1356 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001357
Zachary Turner5c28c662016-10-03 23:20:36 +00001358 int value_type;
1359 std::string option;
1360 std::string value;
1361 for (const auto &entry : *option_arg_vector) {
1362 std::tie(option, value_type, value) = entry;
1363 if (option == "<argument>") {
1364 result_str.Printf(" %s", value.c_str());
1365 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001366 }
1367
Zachary Turner5c28c662016-10-03 23:20:36 +00001368 result_str.Printf(" %s", option.c_str());
1369 if (value_type == OptionParser::eNoArgument)
1370 continue;
1371
1372 if (value_type != OptionParser::eOptionalArgument)
1373 result_str.Printf(" ");
1374 int index = GetOptionArgumentPosition(value.c_str());
1375 if (index == 0)
1376 result_str.Printf("%s", value.c_str());
1377 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1378
1379 result.AppendErrorWithFormat("Not enough arguments provided; you "
1380 "need at least %d arguments to use "
1381 "this alias.\n",
1382 index);
1383 result.SetStatus(eReturnStatusFailed);
1384 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001385 } else {
1386 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1387 if (strpos != std::string::npos)
1388 raw_input_string = raw_input_string.erase(
1389 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1390 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001391 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001392 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001393
Zachary Turnerc1564272016-11-16 21:15:24 +00001394 alias_result = result_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395 return alias_cmd_obj;
1396}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001397
Zachary Turner97206d52017-05-12 04:51:55 +00001398Status CommandInterpreter::PreprocessCommand(std::string &command) {
Adrian Prantl05097242018-04-30 16:49:04 +00001399 // The command preprocessor needs to do things to the command line before any
1400 // parsing of arguments or anything else is done. The only current stuff that
1401 // gets preprocessed is anything enclosed in backtick ('`') characters is
1402 // evaluated as an expression and the result of the expression must be a
1403 // scalar that can be substituted into the command. An example would be:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001404 // (lldb) memory read `$rsp + 20`
Zachary Turner97206d52017-05-12 04:51:55 +00001405 Status error; // Status for any expressions that might not evaluate
Kate Stoneb9c1b512016-09-06 20:57:50 +00001406 size_t start_backtick;
1407 size_t pos = 0;
1408 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1409 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
Adrian Prantl05097242018-04-30 16:49:04 +00001410 // The backtick was preceded by a '\' character, remove the slash and
1411 // don't treat the backtick as the start of an expression
Kate Stoneb9c1b512016-09-06 20:57:50 +00001412 command.erase(start_backtick - 1, 1);
1413 // No need to add one to start_backtick since we just deleted a char
1414 pos = start_backtick;
1415 } else {
1416 const size_t expr_content_start = start_backtick + 1;
1417 const size_t end_backtick = command.find('`', expr_content_start);
1418 if (end_backtick == std::string::npos)
1419 return error;
1420 else if (end_backtick == expr_content_start) {
1421 // Empty expression (two backticks in a row)
1422 command.erase(start_backtick, 2);
1423 } else {
1424 std::string expr_str(command, expr_content_start,
1425 end_backtick - expr_content_start);
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001426
Kate Stoneb9c1b512016-09-06 20:57:50 +00001427 ExecutionContext exe_ctx(GetExecutionContext());
1428 Target *target = exe_ctx.GetTargetPtr();
1429 // Get a dummy target to allow for calculator mode while processing
Adrian Prantl05097242018-04-30 16:49:04 +00001430 // backticks. This also helps break the infinite loop caused when
1431 // target is null.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001432 if (!target)
1433 target = m_debugger.GetDummyTarget();
1434 if (target) {
1435 ValueObjectSP expr_result_valobj_sp;
1436
1437 EvaluateExpressionOptions options;
1438 options.SetCoerceToId(false);
1439 options.SetUnwindOnError(true);
1440 options.SetIgnoreBreakpoints(true);
1441 options.SetKeepInMemory(false);
1442 options.SetTryAllThreads(true);
Pavel Labath43d35412016-12-06 11:24:51 +00001443 options.SetTimeout(llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001444
1445 ExpressionResults expr_result = target->EvaluateExpression(
1446 expr_str.c_str(), exe_ctx.GetFramePtr(), expr_result_valobj_sp,
1447 options);
1448
1449 if (expr_result == eExpressionCompleted) {
1450 Scalar scalar;
1451 if (expr_result_valobj_sp)
1452 expr_result_valobj_sp =
1453 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1454 expr_result_valobj_sp->GetDynamicValueType(), true);
1455 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1456 command.erase(start_backtick, end_backtick - start_backtick + 1);
1457 StreamString value_strm;
1458 const bool show_type = false;
1459 scalar.GetValue(&value_strm, show_type);
1460 size_t value_string_size = value_strm.GetSize();
1461 if (value_string_size) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001462 command.insert(start_backtick, value_strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001463 pos = start_backtick + value_string_size;
1464 continue;
1465 } else {
1466 error.SetErrorStringWithFormat("expression value didn't result "
1467 "in a scalar value for the "
1468 "expression '%s'",
1469 expr_str.c_str());
1470 }
1471 } else {
1472 error.SetErrorStringWithFormat("expression value didn't result "
1473 "in a scalar value for the "
1474 "expression '%s'",
1475 expr_str.c_str());
1476 }
1477 } else {
1478 if (expr_result_valobj_sp)
1479 error = expr_result_valobj_sp->GetError();
1480 if (error.Success()) {
1481
1482 switch (expr_result) {
1483 case eExpressionSetupError:
1484 error.SetErrorStringWithFormat(
1485 "expression setup error for the expression '%s'",
1486 expr_str.c_str());
1487 break;
1488 case eExpressionParseError:
1489 error.SetErrorStringWithFormat(
1490 "expression parse error for the expression '%s'",
1491 expr_str.c_str());
1492 break;
1493 case eExpressionResultUnavailable:
1494 error.SetErrorStringWithFormat(
1495 "expression error fetching result for the expression '%s'",
1496 expr_str.c_str());
1497 break;
1498 case eExpressionCompleted:
1499 break;
1500 case eExpressionDiscarded:
1501 error.SetErrorStringWithFormat(
1502 "expression discarded for the expression '%s'",
1503 expr_str.c_str());
1504 break;
1505 case eExpressionInterrupted:
1506 error.SetErrorStringWithFormat(
1507 "expression interrupted for the expression '%s'",
1508 expr_str.c_str());
1509 break;
1510 case eExpressionHitBreakpoint:
1511 error.SetErrorStringWithFormat(
1512 "expression hit breakpoint for the expression '%s'",
1513 expr_str.c_str());
1514 break;
1515 case eExpressionTimedOut:
1516 error.SetErrorStringWithFormat(
1517 "expression timed out for the expression '%s'",
1518 expr_str.c_str());
1519 break;
1520 case eExpressionStoppedForDebug:
1521 error.SetErrorStringWithFormat("expression stop at entry point "
1522 "for debugging for the "
1523 "expression '%s'",
1524 expr_str.c_str());
1525 break;
1526 }
1527 }
1528 }
1529 }
1530 }
1531 if (error.Fail())
1532 break;
1533 }
1534 }
1535 return error;
1536}
1537
1538bool CommandInterpreter::HandleCommand(const char *command_line,
1539 LazyBool lazy_add_to_history,
1540 CommandReturnObject &result,
1541 ExecutionContext *override_context,
1542 bool repeat_on_empty_command,
1543 bool no_context_switching)
1544
1545{
1546
1547 std::string command_string(command_line);
1548 std::string original_command_string(command_line);
1549
1550 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
Jim Ingham8f7db522016-12-15 00:30:30 +00001551 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
Sean Callanan237c3ed2016-12-14 21:31:31 +00001552 command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001553
1554 if (log)
1555 log->Printf("Processing command: %s", command_line);
1556
Pavel Labathf9d16472017-05-15 13:02:37 +00001557 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1558 Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001559
1560 if (!no_context_switching)
1561 UpdateExecutionContext(override_context);
1562
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001563 if (WasInterrupted()) {
1564 result.AppendError("interrupted");
1565 result.SetStatus(eReturnStatusFailed);
1566 return false;
1567 }
1568
Kate Stoneb9c1b512016-09-06 20:57:50 +00001569 bool add_to_history;
1570 if (lazy_add_to_history == eLazyBoolCalculate)
1571 add_to_history = (m_command_source_depth == 0);
1572 else
1573 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1574
1575 bool empty_command = false;
1576 bool comment_command = false;
1577 if (command_string.empty())
1578 empty_command = true;
1579 else {
1580 const char *k_space_characters = "\t\n\v\f\r ";
1581
1582 size_t non_space = command_string.find_first_not_of(k_space_characters);
Adrian Prantl05097242018-04-30 16:49:04 +00001583 // Check for empty line or comment line (lines whose first non-space
1584 // character is the comment character for this interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001585 if (non_space == std::string::npos)
1586 empty_command = true;
1587 else if (command_string[non_space] == m_comment_char)
1588 comment_command = true;
1589 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001590 llvm::StringRef search_str(command_string);
1591 search_str = search_str.drop_front(non_space);
1592 if (auto hist_str = m_command_history.FindString(search_str)) {
1593 add_to_history = false;
1594 command_string = *hist_str;
1595 original_command_string = *hist_str;
1596 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001597 result.AppendErrorWithFormat("Could not find entry: %s in history",
1598 command_string.c_str());
1599 result.SetStatus(eReturnStatusFailed);
1600 return false;
1601 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001602 }
1603 }
1604
1605 if (empty_command) {
1606 if (repeat_on_empty_command) {
1607 if (m_command_history.IsEmpty()) {
1608 result.AppendError("empty command");
1609 result.SetStatus(eReturnStatusFailed);
1610 return false;
1611 } else {
1612 command_line = m_repeat_command.c_str();
1613 command_string = command_line;
1614 original_command_string = command_line;
1615 if (m_repeat_command.empty()) {
1616 result.AppendErrorWithFormat("No auto repeat.\n");
1617 result.SetStatus(eReturnStatusFailed);
1618 return false;
1619 }
1620 }
1621 add_to_history = false;
1622 } else {
1623 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1624 return true;
1625 }
1626 } else if (comment_command) {
1627 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1628 return true;
1629 }
1630
Zachary Turner97206d52017-05-12 04:51:55 +00001631 Status error(PreprocessCommand(command_string));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001632
1633 if (error.Fail()) {
1634 result.AppendError(error.AsCString());
1635 result.SetStatus(eReturnStatusFailed);
1636 return false;
1637 }
1638
1639 // Phase 1.
1640
1641 // Before we do ANY kind of argument processing, we need to figure out what
1642 // the real/final command object is for the specified command. This gets
1643 // complicated by the fact that the user could have specified an alias, and,
1644 // in translating the alias, there may also be command options and/or even
1645 // data (including raw text strings) that need to be found and inserted into
1646 // the command line as part of the translation. So this first step is plain
1647 // look-up and replacement, resulting in:
1648 // 1. the command object whose Execute method will actually be called
1649 // 2. a revised command string, with all substitutions and replacements
1650 // taken care of
1651 // From 1 above, we can determine whether the Execute function wants raw
1652 // input or not.
1653
1654 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1655
1656 // Although the user may have abbreviated the command, the command_string now
Adrian Prantl05097242018-04-30 16:49:04 +00001657 // has the command expanded to the full name. For example, if the input was
1658 // "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001659 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001660 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1661 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001662 log->Printf("HandleCommand, (revised) command_string: '%s'",
1663 command_string.c_str());
1664 const bool wants_raw_input =
1665 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1666 log->Printf("HandleCommand, wants_raw_input:'%s'",
1667 wants_raw_input ? "True" : "False");
1668 }
1669
1670 // Phase 2.
1671 // Take care of things like setting up the history command & calling the
Adrian Prantl05097242018-04-30 16:49:04 +00001672 // appropriate Execute method on the CommandObject, with the appropriate
1673 // arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001674
1675 if (cmd_obj != nullptr) {
1676 if (add_to_history) {
1677 Args command_args(command_string);
1678 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1679 if (repeat_command != nullptr)
1680 m_repeat_command.assign(repeat_command);
1681 else
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001682 m_repeat_command.assign(original_command_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001683
1684 m_command_history.AppendString(original_command_string);
1685 }
1686
1687 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001688 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001689 if (actual_cmd_name_len < command_string.length())
1690 remainder = command_string.substr(actual_cmd_name_len);
1691
1692 // Remove any initial spaces
1693 size_t pos = remainder.find_first_not_of(k_white_space);
1694 if (pos != 0 && pos != std::string::npos)
1695 remainder.erase(0, pos);
1696
1697 if (log)
1698 log->Printf(
1699 "HandleCommand, command line after removing command name(s): '%s'",
1700 remainder.c_str());
1701
1702 cmd_obj->Execute(remainder.c_str(), result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001703 }
1704
1705 if (log)
1706 log->Printf("HandleCommand, command %s",
1707 (result.Succeeded() ? "succeeded" : "did not succeed"));
1708
1709 return result.Succeeded();
1710}
1711
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001712int CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001713 int num_command_matches = 0;
1714 bool look_for_subcommand = false;
1715
1716 // For any of the command completions a unique match will be a complete word.
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001717 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001718
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001719 if (request.GetCursorIndex() == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001720 // We got nothing on the command line, so return the list of commands
1721 bool include_aliases = true;
Raphael Isemann7f888292018-09-13 21:26:00 +00001722 StringList new_matches, descriptions;
1723 num_command_matches = GetCommandNamesMatchingPartialString(
1724 "", include_aliases, new_matches, descriptions);
1725 request.AddCompletions(new_matches, descriptions);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001726 } else if (request.GetCursorIndex() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001727 // The cursor is in the first argument, so just do a lookup in the
1728 // dictionary.
Raphael Isemann7f888292018-09-13 21:26:00 +00001729 StringList new_matches, new_descriptions;
1730 CommandObject *cmd_obj =
1731 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0),
1732 &new_matches, &new_descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001733
1734 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001735 new_matches.GetStringAtIndex(0) != nullptr &&
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001736 strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001737 new_matches.GetStringAtIndex(0)) == 0) {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001738 if (request.GetParsedLine().GetArgumentCount() == 1) {
1739 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001740 } else {
1741 look_for_subcommand = true;
1742 num_command_matches = 0;
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001743 new_matches.DeleteStringAtIndex(0);
Raphael Isemann7f888292018-09-13 21:26:00 +00001744 new_descriptions.DeleteStringAtIndex(0);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001745 request.GetParsedLine().AppendArgument(llvm::StringRef());
1746 request.SetCursorIndex(request.GetCursorIndex() + 1);
1747 request.SetCursorCharPosition(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001748 }
1749 }
Raphael Isemann7f888292018-09-13 21:26:00 +00001750 request.AddCompletions(new_matches, new_descriptions);
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001751 num_command_matches = request.GetNumberOfMatches();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001752 }
1753
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001754 if (request.GetCursorIndex() > 0 || look_for_subcommand) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001755 // We are completing further on into a commands arguments, so find the
Adrian Prantl05097242018-04-30 16:49:04 +00001756 // command and tell it to complete the command. First see if there is a
1757 // matching initial command:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001758 CommandObject *command_object =
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001759 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001760 if (command_object == nullptr) {
1761 return 0;
1762 } else {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001763 request.GetParsedLine().Shift();
1764 request.SetCursorIndex(request.GetCursorIndex() - 1);
1765 num_command_matches = command_object->HandleCompletion(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001766 }
1767 }
1768
1769 return num_command_matches;
1770}
1771
1772int CommandInterpreter::HandleCompletion(
1773 const char *current_line, const char *cursor, const char *last_char,
Raphael Isemann7f888292018-09-13 21:26:00 +00001774 int match_start_point, int max_return_elements, StringList &matches,
1775 StringList &descriptions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001776
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001777 llvm::StringRef command_line(current_line, last_char - current_line);
Raphael Isemann7f888292018-09-13 21:26:00 +00001778 CompletionResult result;
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001779 CompletionRequest request(command_line, cursor - current_line,
Raphael Isemann7f888292018-09-13 21:26:00 +00001780 match_start_point, max_return_elements, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001781 // Don't complete comments, and if the line we are completing is just the
Adrian Prantl05097242018-04-30 16:49:04 +00001782 // history repeat character, substitute the appropriate history line.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001783 const char *first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001784 if (first_arg) {
1785 if (first_arg[0] == m_comment_char)
1786 return 0;
1787 else if (first_arg[0] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001788 if (auto hist_str = m_command_history.FindString(first_arg)) {
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001789 matches.InsertStringAtIndex(0, *hist_str);
Raphael Isemann7f888292018-09-13 21:26:00 +00001790 descriptions.InsertStringAtIndex(0, "Previous command history event");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001791 return -2;
1792 } else
1793 return 0;
1794 }
1795 }
1796
Kate Stoneb9c1b512016-09-06 20:57:50 +00001797 // Only max_return_elements == -1 is supported at present:
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001798 lldbassert(max_return_elements == -1);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001799
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001800 int num_command_matches = HandleCompletionMatches(request);
Raphael Isemann7f888292018-09-13 21:26:00 +00001801 result.GetMatches(matches);
1802 result.GetDescriptions(descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001803
1804 if (num_command_matches <= 0)
1805 return num_command_matches;
1806
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001807 if (request.GetParsedLine().GetArgumentCount() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001808 // If we got an empty string, insert nothing.
1809 matches.InsertStringAtIndex(0, "");
Raphael Isemann7f888292018-09-13 21:26:00 +00001810 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001811 } else {
1812 // Now figure out if there is a common substring, and if so put that in
Adrian Prantl05097242018-04-30 16:49:04 +00001813 // element 0, otherwise put an empty string in element 0.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001814 std::string command_partial_str = request.GetCursorArgumentPrefix().str();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001815
1816 std::string common_prefix;
1817 matches.LongestCommonPrefix(common_prefix);
1818 const size_t partial_name_len = command_partial_str.size();
1819 common_prefix.erase(0, partial_name_len);
1820
Adrian Prantl05097242018-04-30 16:49:04 +00001821 // If we matched a unique single command, add a space... Only do this if
1822 // the completer told us this was a complete word, however...
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001823 if (num_command_matches == 1 && request.GetWordComplete()) {
1824 char quote_char = request.GetParsedLine()[request.GetCursorIndex()].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001825 common_prefix =
1826 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1827 if (quote_char != '\0')
1828 common_prefix.push_back(quote_char);
1829 common_prefix.push_back(' ');
1830 }
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001831 matches.InsertStringAtIndex(0, common_prefix.c_str());
Raphael Isemann7f888292018-09-13 21:26:00 +00001832 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001833 }
1834 return num_command_matches;
1835}
1836
1837CommandInterpreter::~CommandInterpreter() {}
1838
Zachary Turner514d8cd2016-09-23 18:06:53 +00001839void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001840 EventSP prompt_change_event_sp(
1841 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1842 ;
1843 BroadcastEvent(prompt_change_event_sp);
1844 if (m_command_io_handler_sp)
1845 m_command_io_handler_sp->SetPrompt(new_prompt);
1846}
1847
Zachary Turner7a120c82016-11-13 03:05:58 +00001848bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001849 // Check AutoConfirm first:
1850 if (m_debugger.GetAutoConfirm())
1851 return default_answer;
1852
1853 IOHandlerConfirm *confirm =
1854 new IOHandlerConfirm(m_debugger, message, default_answer);
1855 IOHandlerSP io_handler_sp(confirm);
1856 m_debugger.RunIOHandler(io_handler_sp);
1857 return confirm->GetResponse();
1858}
1859
Zachary Turnera483f572016-10-05 21:14:49 +00001860const CommandAlias *
1861CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001862 OptionArgVectorSP ret_val;
1863
Zachary Turnera483f572016-10-05 21:14:49 +00001864 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001865 if (pos != m_alias_dict.end())
1866 return (CommandAlias *)pos->second.get();
1867
1868 return nullptr;
1869}
1870
Zachary Turnera4496982016-10-05 21:14:38 +00001871bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001872
Zachary Turnera4496982016-10-05 21:14:38 +00001873bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001874
Zachary Turnera4496982016-10-05 21:14:38 +00001875bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001876
Zachary Turnera4496982016-10-05 21:14:38 +00001877bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001878
1879void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1880 const char *alias_name,
1881 Args &cmd_args,
1882 std::string &raw_input_string,
1883 CommandReturnObject &result) {
1884 OptionArgVectorSP option_arg_vector_sp =
1885 GetAlias(alias_name)->GetOptionArguments();
1886
1887 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1888
1889 // Make sure that the alias name is the 0th element in cmd_args
1890 std::string alias_name_str = alias_name;
1891 if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)
Zachary Turner5c725f32016-09-19 21:56:59 +00001892 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001893
1894 Args new_args(alias_cmd_obj->GetCommandName());
1895 if (new_args.GetArgumentCount() == 2)
1896 new_args.Shift();
1897
1898 if (option_arg_vector_sp.get()) {
1899 if (wants_raw_input) {
1900 // We have a command that both has command options and takes raw input.
Adrian Prantl05097242018-04-30 16:49:04 +00001901 // Make *sure* it has a " -- " in the right place in the
1902 // raw_input_string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001903 size_t pos = raw_input_string.find(" -- ");
1904 if (pos == std::string::npos) {
1905 // None found; assume it goes at the beginning of the raw input string
1906 raw_input_string.insert(0, " -- ");
1907 }
1908 }
1909
1910 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1911 const size_t old_size = cmd_args.GetArgumentCount();
1912 std::vector<bool> used(old_size + 1, false);
1913
1914 used[0] = true;
1915
Zachary Turner5c28c662016-10-03 23:20:36 +00001916 int value_type;
1917 std::string option;
1918 std::string value;
1919 for (const auto &option_entry : *option_arg_vector) {
1920 std::tie(option, value_type, value) = option_entry;
1921 if (option == "<argument>") {
1922 if (!wants_raw_input || (value != "--")) {
1923 // Since we inserted this above, make sure we don't insert it twice
1924 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001925 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001926 continue;
1927 }
1928
1929 if (value_type != OptionParser::eOptionalArgument)
1930 new_args.AppendArgument(option);
1931
1932 if (value == "<no-argument>")
1933 continue;
1934
1935 int index = GetOptionArgumentPosition(value.c_str());
1936 if (index == 0) {
1937 // value was NOT a positional argument; must be a real value
1938 if (value_type != OptionParser::eOptionalArgument)
1939 new_args.AppendArgument(value);
1940 else {
1941 char buffer[255];
1942 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1943 value.c_str());
1944 new_args.AppendArgument(llvm::StringRef(buffer));
1945 }
1946
1947 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1948 result.AppendErrorWithFormat("Not enough arguments provided; you "
1949 "need at least %d arguments to use "
1950 "this alias.\n",
1951 index);
1952 result.SetStatus(eReturnStatusFailed);
1953 return;
1954 } else {
1955 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1956 size_t strpos =
1957 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1958 if (strpos != std::string::npos) {
1959 raw_input_string = raw_input_string.erase(
1960 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1961 }
1962
1963 if (value_type != OptionParser::eOptionalArgument)
1964 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
1965 else {
1966 char buffer[255];
1967 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1968 cmd_args.GetArgumentAtIndex(index));
1969 new_args.AppendArgument(buffer);
1970 }
1971 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001972 }
1973 }
1974
Zachary Turner97d2c402016-10-05 23:40:23 +00001975 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00001976 if (!used[entry.index()] && !wants_raw_input)
1977 new_args.AppendArgument(entry.value().ref);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001978 }
1979
1980 cmd_args.Clear();
1981 cmd_args.SetArguments(new_args.GetArgumentCount(),
1982 new_args.GetConstArgumentVector());
1983 } else {
1984 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1985 // This alias was not created with any options; nothing further needs to be
Adrian Prantl05097242018-04-30 16:49:04 +00001986 // done, unless it is a command that wants raw input, in which case we need
1987 // to clear the rest of the data from cmd_args, since its in the raw input
1988 // string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001989 if (wants_raw_input) {
1990 cmd_args.Clear();
1991 cmd_args.SetArguments(new_args.GetArgumentCount(),
1992 new_args.GetConstArgumentVector());
1993 }
1994 return;
1995 }
1996
1997 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1998 return;
1999}
2000
2001int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2002 int position = 0; // Any string that isn't an argument position, i.e. '%'
2003 // followed by an integer, gets a position
2004 // of zero.
2005
2006 const char *cptr = in_string;
2007
2008 // Does it start with '%'
2009 if (cptr[0] == '%') {
2010 ++cptr;
2011
2012 // Is the rest of it entirely digits?
2013 if (isdigit(cptr[0])) {
2014 const char *start = cptr;
2015 while (isdigit(cptr[0]))
2016 ++cptr;
2017
Adrian Prantl05097242018-04-30 16:49:04 +00002018 // We've gotten to the end of the digits; are we at the end of the
2019 // string?
Kate Stoneb9c1b512016-09-06 20:57:50 +00002020 if (cptr[0] == '\0')
2021 position = atoi(start);
2022 }
2023 }
2024
2025 return position;
2026}
2027
2028void CommandInterpreter::SourceInitFile(bool in_cwd,
2029 CommandReturnObject &result) {
2030 FileSpec init_file;
2031 if (in_cwd) {
2032 ExecutionContext exe_ctx(GetExecutionContext());
2033 Target *target = exe_ctx.GetTargetPtr();
2034 if (target) {
2035 // In the current working directory we don't load any program specific
2036 // .lldbinit files, we only look for a ".lldbinit" file.
2037 if (m_skip_lldbinit_files)
2038 return;
2039
2040 LoadCWDlldbinitFile should_load =
2041 target->TargetProperties::GetLoadCWDlldbinitFile();
2042 if (should_load == eLoadCWDlldbinitWarn) {
2043 FileSpec dot_lldb(".lldbinit", true);
2044 llvm::SmallString<64> home_dir_path;
2045 llvm::sys::path::home_directory(home_dir_path);
2046 FileSpec homedir_dot_lldb(home_dir_path.c_str(), false);
2047 homedir_dot_lldb.AppendPathComponent(".lldbinit");
2048 homedir_dot_lldb.ResolvePath();
2049 if (dot_lldb.Exists() &&
2050 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2051 result.AppendErrorWithFormat(
2052 "There is a .lldbinit file in the current directory which is not "
2053 "being read.\n"
2054 "To silence this warning without sourcing in the local "
2055 ".lldbinit,\n"
2056 "add the following to the lldbinit file in your home directory:\n"
2057 " settings set target.load-cwd-lldbinit false\n"
2058 "To allow lldb to source .lldbinit files in the current working "
2059 "directory,\n"
2060 "set the value of this variable to true. Only do so if you "
2061 "understand and\n"
2062 "accept the security risk.");
2063 result.SetStatus(eReturnStatusFailed);
2064 return;
2065 }
2066 } else if (should_load == eLoadCWDlldbinitTrue) {
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002067 init_file.SetFile("./.lldbinit", true, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002068 }
2069 }
2070 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002071 // If we aren't looking in the current working directory we are looking in
2072 // the home directory. We will first see if there is an application
2073 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a "-"
2074 // and the name of the program. If this file doesn't exist, we fall back to
2075 // just the "~/.lldbinit" file. We also obey any requests to not load the
2076 // init files.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002077 llvm::SmallString<64> home_dir_path;
2078 llvm::sys::path::home_directory(home_dir_path);
2079 FileSpec profilePath(home_dir_path.c_str(), false);
2080 profilePath.AppendPathComponent(".lldbinit");
2081 std::string init_file_path = profilePath.GetPath();
2082
2083 if (m_skip_app_init_files == false) {
2084 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2085 const char *program_name = program_file_spec.GetFilename().AsCString();
2086
2087 if (program_name) {
2088 char program_init_file_name[PATH_MAX];
2089 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2090 "%s-%s", init_file_path.c_str(), program_name);
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002091 init_file.SetFile(program_init_file_name, true,
2092 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002093 if (!init_file.Exists())
2094 init_file.Clear();
2095 }
2096 }
2097
2098 if (!init_file && !m_skip_lldbinit_files)
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002099 init_file.SetFile(init_file_path, false, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002100 }
2101
2102 // If the file exists, tell HandleCommand to 'source' it; this will do the
Adrian Prantl05097242018-04-30 16:49:04 +00002103 // actual broadcasting of the commands back to any appropriate listener (see
Kate Stoneb9c1b512016-09-06 20:57:50 +00002104 // CommandObjectSource::Execute for more details).
2105
2106 if (init_file.Exists()) {
2107 const bool saved_batch = SetBatchCommandMode(true);
2108 CommandInterpreterRunOptions options;
2109 options.SetSilent(true);
2110 options.SetStopOnError(false);
2111 options.SetStopOnContinue(true);
2112
2113 HandleCommandsFromFile(init_file,
2114 nullptr, // Execution context
2115 options, result);
2116 SetBatchCommandMode(saved_batch);
2117 } else {
2118 // nothing to be done if the file doesn't exist
2119 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2120 }
2121}
2122
2123const char *CommandInterpreter::GetCommandPrefix() {
2124 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2125 return prefix == NULL ? "" : prefix;
2126}
2127
2128PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2129 PlatformSP platform_sp;
2130 if (prefer_target_platform) {
2131 ExecutionContext exe_ctx(GetExecutionContext());
2132 Target *target = exe_ctx.GetTargetPtr();
2133 if (target)
2134 platform_sp = target->GetPlatform();
2135 }
2136
2137 if (!platform_sp)
2138 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2139 return platform_sp;
2140}
2141
2142void CommandInterpreter::HandleCommands(const StringList &commands,
2143 ExecutionContext *override_context,
2144 CommandInterpreterRunOptions &options,
2145 CommandReturnObject &result) {
2146 size_t num_lines = commands.GetSize();
2147
2148 // If we are going to continue past a "continue" then we need to run the
Adrian Prantl05097242018-04-30 16:49:04 +00002149 // commands synchronously. Make sure you reset this value anywhere you return
2150 // from the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002151
2152 bool old_async_execution = m_debugger.GetAsyncExecution();
2153
2154 // If we've been given an execution context, set it at the start, but don't
Adrian Prantl05097242018-04-30 16:49:04 +00002155 // keep resetting it or we will cause series of commands that change the
2156 // context, then do an operation that relies on that context to fail.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002157
2158 if (override_context != nullptr)
2159 UpdateExecutionContext(override_context);
2160
2161 if (!options.GetStopOnContinue()) {
2162 m_debugger.SetAsyncExecution(false);
2163 }
2164
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002165 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002166 const char *cmd = commands.GetStringAtIndex(idx);
2167 if (cmd[0] == '\0')
2168 continue;
2169
2170 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002171 // TODO: Add Stream support.
2172 result.AppendMessageWithFormat("%s %s\n",
2173 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002174 }
2175
2176 CommandReturnObject tmp_result;
2177 // If override_context is not NULL, pass no_context_switching = true for
2178 // HandleCommand() since we updated our context already.
2179
2180 // We might call into a regex or alias command, in which case the
Adrian Prantl05097242018-04-30 16:49:04 +00002181 // add_to_history will get lost. This m_command_source_depth dingus is the
2182 // way we turn off adding to the history in that case, so set it up here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002183 if (!options.GetAddToHistory())
2184 m_command_source_depth++;
2185 bool success =
2186 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2187 nullptr, /* override_context */
2188 true, /* repeat_on_empty_command */
2189 override_context != nullptr /* no_context_switching */);
2190 if (!options.GetAddToHistory())
2191 m_command_source_depth--;
2192
2193 if (options.GetPrintResults()) {
2194 if (tmp_result.Succeeded())
Zachary Turner03c9f362016-11-14 23:23:31 +00002195 result.AppendMessage(tmp_result.GetOutputData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002196 }
2197
2198 if (!success || !tmp_result.Succeeded()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002199 llvm::StringRef error_msg = tmp_result.GetErrorData();
2200 if (error_msg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002201 error_msg = "<unknown error>.\n";
2202 if (options.GetStopOnError()) {
2203 result.AppendErrorWithFormat(
2204 "Aborting reading of commands after command #%" PRIu64
2205 ": '%s' failed with %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00002206 (uint64_t)idx, cmd, error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002207 result.SetStatus(eReturnStatusFailed);
2208 m_debugger.SetAsyncExecution(old_async_execution);
2209 return;
2210 } else if (options.GetPrintResults()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002211 result.AppendMessageWithFormat(
2212 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2213 error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002214 }
2215 }
2216
2217 if (result.GetImmediateOutputStream())
2218 result.GetImmediateOutputStream()->Flush();
2219
2220 if (result.GetImmediateErrorStream())
2221 result.GetImmediateErrorStream()->Flush();
2222
Adrian Prantl05097242018-04-30 16:49:04 +00002223 // N.B. Can't depend on DidChangeProcessState, because the state coming
2224 // into the command execution could be running (for instance in Breakpoint
2225 // Commands. So we check the return value to see if it is has running in
2226 // it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002227 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2228 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2229 if (options.GetStopOnContinue()) {
2230 // If we caused the target to proceed, and we're going to stop in that
Adrian Prantl05097242018-04-30 16:49:04 +00002231 // case, set the status in our real result before returning. This is
2232 // an error if the continue was not the last command in the set of
2233 // commands to be run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002234 if (idx != num_lines - 1)
2235 result.AppendErrorWithFormat(
2236 "Aborting reading of commands after command #%" PRIu64
2237 ": '%s' continued the target.\n",
2238 (uint64_t)idx + 1, cmd);
2239 else
2240 result.AppendMessageWithFormat("Command #%" PRIu64
2241 " '%s' continued the target.\n",
2242 (uint64_t)idx + 1, cmd);
2243
2244 result.SetStatus(tmp_result.GetStatus());
2245 m_debugger.SetAsyncExecution(old_async_execution);
2246
2247 return;
2248 }
2249 }
2250
2251 // Also check for "stop on crash here:
2252 bool should_stop = false;
2253 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2254 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2255 if (target_sp) {
2256 ProcessSP process_sp(target_sp->GetProcessSP());
2257 if (process_sp) {
2258 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2259 StopReason reason = thread_sp->GetStopReason();
2260 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2261 reason == eStopReasonInstrumentation) {
2262 should_stop = true;
2263 break;
2264 }
2265 }
2266 }
2267 }
2268 if (should_stop) {
2269 if (idx != num_lines - 1)
2270 result.AppendErrorWithFormat(
2271 "Aborting reading of commands after command #%" PRIu64
2272 ": '%s' stopped with a signal or exception.\n",
2273 (uint64_t)idx + 1, cmd);
2274 else
2275 result.AppendMessageWithFormat(
2276 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2277 (uint64_t)idx + 1, cmd);
2278
2279 result.SetStatus(tmp_result.GetStatus());
2280 m_debugger.SetAsyncExecution(old_async_execution);
2281
2282 return;
2283 }
2284 }
2285 }
2286
2287 result.SetStatus(eReturnStatusSuccessFinishResult);
2288 m_debugger.SetAsyncExecution(old_async_execution);
2289
2290 return;
2291}
2292
2293// Make flags that we can pass into the IOHandler so our delegates can do the
2294// right thing
2295enum {
2296 eHandleCommandFlagStopOnContinue = (1u << 0),
2297 eHandleCommandFlagStopOnError = (1u << 1),
2298 eHandleCommandFlagEchoCommand = (1u << 2),
2299 eHandleCommandFlagPrintResult = (1u << 3),
2300 eHandleCommandFlagStopOnCrash = (1u << 4)
2301};
2302
2303void CommandInterpreter::HandleCommandsFromFile(
2304 FileSpec &cmd_file, ExecutionContext *context,
2305 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2306 if (cmd_file.Exists()) {
2307 StreamFileSP input_file_sp(new StreamFile());
2308
2309 std::string cmd_file_path = cmd_file.GetPath();
Zachary Turner97206d52017-05-12 04:51:55 +00002310 Status error = input_file_sp->GetFile().Open(cmd_file_path.c_str(),
2311 File::eOpenOptionRead);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002312
2313 if (error.Success()) {
2314 Debugger &debugger = GetDebugger();
2315
2316 uint32_t flags = 0;
2317
2318 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2319 if (m_command_source_flags.empty()) {
2320 // Stop on continue by default
2321 flags |= eHandleCommandFlagStopOnContinue;
2322 } else if (m_command_source_flags.back() &
2323 eHandleCommandFlagStopOnContinue) {
2324 flags |= eHandleCommandFlagStopOnContinue;
2325 }
2326 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2327 flags |= eHandleCommandFlagStopOnContinue;
2328 }
2329
2330 if (options.m_stop_on_error == eLazyBoolCalculate) {
2331 if (m_command_source_flags.empty()) {
2332 if (GetStopCmdSourceOnError())
2333 flags |= eHandleCommandFlagStopOnError;
2334 } else if (m_command_source_flags.back() &
2335 eHandleCommandFlagStopOnError) {
2336 flags |= eHandleCommandFlagStopOnError;
2337 }
2338 } else if (options.m_stop_on_error == eLazyBoolYes) {
2339 flags |= eHandleCommandFlagStopOnError;
2340 }
2341
2342 if (options.GetStopOnCrash()) {
2343 if (m_command_source_flags.empty()) {
2344 // Echo command by default
2345 flags |= eHandleCommandFlagStopOnCrash;
2346 } else if (m_command_source_flags.back() &
2347 eHandleCommandFlagStopOnCrash) {
2348 flags |= eHandleCommandFlagStopOnCrash;
2349 }
2350 }
2351
2352 if (options.m_echo_commands == eLazyBoolCalculate) {
2353 if (m_command_source_flags.empty()) {
2354 // Echo command by default
2355 flags |= eHandleCommandFlagEchoCommand;
2356 } else if (m_command_source_flags.back() &
2357 eHandleCommandFlagEchoCommand) {
2358 flags |= eHandleCommandFlagEchoCommand;
2359 }
2360 } else if (options.m_echo_commands == eLazyBoolYes) {
2361 flags |= eHandleCommandFlagEchoCommand;
2362 }
2363
2364 if (options.m_print_results == eLazyBoolCalculate) {
2365 if (m_command_source_flags.empty()) {
2366 // Print output by default
2367 flags |= eHandleCommandFlagPrintResult;
2368 } else if (m_command_source_flags.back() &
2369 eHandleCommandFlagPrintResult) {
2370 flags |= eHandleCommandFlagPrintResult;
2371 }
2372 } else if (options.m_print_results == eLazyBoolYes) {
2373 flags |= eHandleCommandFlagPrintResult;
2374 }
2375
2376 if (flags & eHandleCommandFlagPrintResult) {
2377 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2378 cmd_file_path.c_str());
2379 }
2380
Adrian Prantl05097242018-04-30 16:49:04 +00002381 // Used for inheriting the right settings when "command source" might
2382 // have nested "command source" commands
Kate Stoneb9c1b512016-09-06 20:57:50 +00002383 lldb::StreamFileSP empty_stream_sp;
2384 m_command_source_flags.push_back(flags);
2385 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2386 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2387 empty_stream_sp, // Pass in an empty stream so we inherit the top
2388 // input reader output stream
2389 empty_stream_sp, // Pass in an empty stream so we inherit the top
2390 // input reader error stream
2391 flags,
2392 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2393 // or written
Zachary Turner514d8cd2016-09-23 18:06:53 +00002394 debugger.GetPrompt(), llvm::StringRef(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00002395 false, // Not multi-line
2396 debugger.GetUseColor(), 0, *this));
2397 const bool old_async_execution = debugger.GetAsyncExecution();
2398
2399 // Set synchronous execution if we are not stopping on continue
2400 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2401 debugger.SetAsyncExecution(false);
2402
2403 m_command_source_depth++;
2404
2405 debugger.RunIOHandler(io_handler_sp);
2406 if (!m_command_source_flags.empty())
2407 m_command_source_flags.pop_back();
2408 m_command_source_depth--;
2409 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2410 debugger.SetAsyncExecution(old_async_execution);
2411 } else {
2412 result.AppendErrorWithFormat(
2413 "error: an error occurred read file '%s': %s\n",
2414 cmd_file_path.c_str(), error.AsCString());
2415 result.SetStatus(eReturnStatusFailed);
2416 }
2417
2418 } else {
2419 result.AppendErrorWithFormat(
2420 "Error reading commands from file %s - file not found.\n",
2421 cmd_file.GetFilename().AsCString("<Unknown>"));
2422 result.SetStatus(eReturnStatusFailed);
2423 return;
2424 }
2425}
2426
2427ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
Jim Ingham30bac792017-07-13 19:45:54 +00002428 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
Greg Clayton79040462016-12-09 01:21:14 +00002429 if (!m_script_interpreter_sp) {
2430 if (!can_create)
2431 return nullptr;
2432 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2433 m_script_interpreter_sp =
2434 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2435 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002436 return m_script_interpreter_sp.get();
2437}
2438
2439bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2440
2441void CommandInterpreter::SetSynchronous(bool value) {
2442 m_synchronous_execution = value;
2443}
2444
2445void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002446 llvm::StringRef prefix,
2447 llvm::StringRef help_text) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002448 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002449
Zachary Turner0ac5f982016-11-08 04:12:42 +00002450 size_t line_width_max = max_columns - prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002451 if (line_width_max < 16)
Zachary Turner0ac5f982016-11-08 04:12:42 +00002452 line_width_max = help_text.size() + prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002453
Zachary Turner0ac5f982016-11-08 04:12:42 +00002454 strm.IndentMore(prefix.size());
2455 bool prefixed_yet = false;
2456 while (!help_text.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002457 // Prefix the first line, indent subsequent lines to line up
Zachary Turner0ac5f982016-11-08 04:12:42 +00002458 if (!prefixed_yet) {
2459 strm << prefix;
2460 prefixed_yet = true;
2461 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002462 strm.Indent();
Zachary Turner0ac5f982016-11-08 04:12:42 +00002463
2464 // Never print more than the maximum on one line.
2465 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2466
2467 // Always break on an explicit newline.
2468 std::size_t first_newline = this_line.find_first_of("\n");
2469
2470 // Don't break on space/tab unless the text is too long to fit on one line.
2471 std::size_t last_space = llvm::StringRef::npos;
2472 if (this_line.size() != help_text.size())
2473 last_space = this_line.find_last_of(" \t");
2474
2475 // Break at whichever condition triggered first.
2476 this_line = this_line.substr(0, std::min(first_newline, last_space));
2477 strm.PutCString(this_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002478 strm.EOL();
2479
Zachary Turner0ac5f982016-11-08 04:12:42 +00002480 // Remove whitespace / newlines after breaking.
2481 help_text = help_text.drop_front(this_line.size()).ltrim();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002482 }
Zachary Turner0ac5f982016-11-08 04:12:42 +00002483 strm.IndentLess(prefix.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002484}
2485
2486void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002487 llvm::StringRef word_text,
2488 llvm::StringRef separator,
2489 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002490 size_t max_word_len) {
2491 StreamString prefix_stream;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002492 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2493 (int)separator.size(), separator.data());
Zachary Turnerc1564272016-11-16 21:15:24 +00002494 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2495}
2496
Zachary Turner0ac5f982016-11-08 04:12:42 +00002497void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2498 llvm::StringRef separator,
2499 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002500 uint32_t max_word_len) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00002501 int indent_size = max_word_len + separator.size() + 2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002502
2503 strm.IndentMore(indent_size);
2504
2505 StreamString text_strm;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002506 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2507 text_strm << separator << " " << help_text;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002508
2509 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2510
Zachary Turnerc1564272016-11-16 21:15:24 +00002511 llvm::StringRef text = text_strm.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002512
2513 uint32_t chars_left = max_columns;
2514
Davide Italianocf8a8292017-04-14 22:36:08 +00002515 auto nextWordLength = [](llvm::StringRef S) {
2516 size_t pos = S.find_first_of(' ');
2517 return pos == llvm::StringRef::npos ? S.size() : pos;
2518 };
2519
Zachary Turnerc1564272016-11-16 21:15:24 +00002520 while (!text.empty()) {
2521 if (text.front() == '\n' ||
Jim Inghama81bd7f2017-07-27 00:18:18 +00002522 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002523 strm.EOL();
2524 strm.Indent();
Zachary Turnerc1564272016-11-16 21:15:24 +00002525 chars_left = max_columns - indent_size;
2526 if (text.front() == '\n')
2527 text = text.drop_front();
2528 else
2529 text = text.ltrim(' ');
Kate Stoneb9c1b512016-09-06 20:57:50 +00002530 } else {
Zachary Turnerc1564272016-11-16 21:15:24 +00002531 strm.PutChar(text.front());
2532 --chars_left;
2533 text = text.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002534 }
2535 }
2536
2537 strm.EOL();
2538 strm.IndentLess(indent_size);
2539}
2540
2541void CommandInterpreter::FindCommandsForApropos(
Zachary Turner067d1db2016-11-16 21:45:04 +00002542 llvm::StringRef search_word, StringList &commands_found,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002543 StringList &commands_help, CommandObject::CommandMap &command_map) {
2544 CommandObject::CommandMap::const_iterator pos;
2545
2546 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
Zachary Turner067d1db2016-11-16 21:45:04 +00002547 llvm::StringRef command_name = pos->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002548 CommandObject *cmd_obj = pos->second.get();
2549
2550 const bool search_short_help = true;
2551 const bool search_long_help = false;
2552 const bool search_syntax = false;
2553 const bool search_options = false;
Zachary Turner067d1db2016-11-16 21:45:04 +00002554 if (command_name.contains_lower(search_word) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002555 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2556 search_long_help, search_syntax,
2557 search_options)) {
2558 commands_found.AppendString(cmd_obj->GetCommandName());
2559 commands_help.AppendString(cmd_obj->GetHelp());
2560 }
2561
2562 if (cmd_obj->IsMultiwordObject()) {
2563 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2564 FindCommandsForApropos(search_word, commands_found, commands_help,
2565 cmd_multiword->GetSubcommandDictionary());
2566 }
2567 }
2568}
2569
Zachary Turner067d1db2016-11-16 21:45:04 +00002570void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002571 StringList &commands_found,
2572 StringList &commands_help,
2573 bool search_builtin_commands,
2574 bool search_user_commands,
2575 bool search_alias_commands) {
2576 CommandObject::CommandMap::const_iterator pos;
2577
2578 if (search_builtin_commands)
2579 FindCommandsForApropos(search_word, commands_found, commands_help,
2580 m_command_dict);
2581
2582 if (search_user_commands)
2583 FindCommandsForApropos(search_word, commands_found, commands_help,
2584 m_user_dict);
2585
2586 if (search_alias_commands)
2587 FindCommandsForApropos(search_word, commands_found, commands_help,
2588 m_alias_dict);
2589}
2590
2591void CommandInterpreter::UpdateExecutionContext(
2592 ExecutionContext *override_context) {
2593 if (override_context != nullptr) {
2594 m_exe_ctx_ref = *override_context;
2595 } else {
2596 const bool adopt_selected = true;
2597 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2598 adopt_selected);
2599 }
2600}
2601
2602size_t CommandInterpreter::GetProcessOutput() {
2603 // The process has stuff waiting for stderr; get it and write it out to the
2604 // appropriate place.
2605 char stdio_buffer[1024];
2606 size_t len;
2607 size_t total_bytes = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002608 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002609 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2610 if (target_sp) {
2611 ProcessSP process_sp(target_sp->GetProcessSP());
2612 if (process_sp) {
2613 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2614 error)) > 0) {
2615 size_t bytes_written = len;
2616 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2617 total_bytes += len;
2618 }
2619 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2620 error)) > 0) {
2621 size_t bytes_written = len;
2622 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2623 total_bytes += len;
2624 }
2625 }
2626 }
2627 return total_bytes;
2628}
2629
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002630void CommandInterpreter::StartHandlingCommand() {
2631 auto idle_state = CommandHandlingState::eIdle;
2632 if (m_command_state.compare_exchange_strong(
2633 idle_state, CommandHandlingState::eInProgress))
2634 lldbassert(m_iohandler_nesting_level == 0);
2635 else
2636 lldbassert(m_iohandler_nesting_level > 0);
2637 ++m_iohandler_nesting_level;
2638}
2639
2640void CommandInterpreter::FinishHandlingCommand() {
2641 lldbassert(m_iohandler_nesting_level > 0);
2642 if (--m_iohandler_nesting_level == 0) {
2643 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2644 lldbassert(prev_state != CommandHandlingState::eIdle);
2645 }
2646}
2647
2648bool CommandInterpreter::InterruptCommand() {
2649 auto in_progress = CommandHandlingState::eInProgress;
2650 return m_command_state.compare_exchange_strong(
2651 in_progress, CommandHandlingState::eInterrupted);
2652}
2653
2654bool CommandInterpreter::WasInterrupted() const {
2655 bool was_interrupted =
2656 (m_command_state == CommandHandlingState::eInterrupted);
2657 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2658 return was_interrupted;
2659}
2660
2661void CommandInterpreter::PrintCommandOutput(Stream &stream,
2662 llvm::StringRef str) {
2663 // Split the output into lines and poll for interrupt requests
2664 const char *data = str.data();
2665 size_t size = str.size();
2666 while (size > 0 && !WasInterrupted()) {
2667 size_t chunk_size = 0;
2668 for (; chunk_size < size; ++chunk_size) {
2669 lldbassert(data[chunk_size] != '\0');
2670 if (data[chunk_size] == '\n') {
2671 ++chunk_size;
2672 break;
2673 }
2674 }
2675 chunk_size = stream.Write(data, chunk_size);
2676 lldbassert(size >= chunk_size);
2677 data += chunk_size;
2678 size -= chunk_size;
2679 }
2680 if (size > 0) {
2681 stream.Printf("\n... Interrupted.\n");
2682 }
2683}
2684
Kate Stoneb9c1b512016-09-06 20:57:50 +00002685void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2686 std::string &line) {
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002687 // If we were interrupted, bail out...
2688 if (WasInterrupted())
2689 return;
2690
Kate Stoneb9c1b512016-09-06 20:57:50 +00002691 const bool is_interactive = io_handler.GetIsInteractive();
2692 if (is_interactive == false) {
2693 // When we are not interactive, don't execute blank lines. This will happen
2694 // sourcing a commands file. We don't want blank lines to repeat the
Adrian Prantl05097242018-04-30 16:49:04 +00002695 // previous command and cause any errors to occur (like redefining an
2696 // alias, get an error and stop parsing the commands file).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002697 if (line.empty())
2698 return;
2699
2700 // When using a non-interactive file handle (like when sourcing commands
Adrian Prantl05097242018-04-30 16:49:04 +00002701 // from a file) we need to echo the command out so we don't just see the
2702 // command output and no command...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002703 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2704 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2705 line.c_str());
2706 }
2707
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002708 StartHandlingCommand();
2709
Kate Stoneb9c1b512016-09-06 20:57:50 +00002710 lldb_private::CommandReturnObject result;
2711 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2712
2713 // Now emit the command output text from the command we just executed
2714 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2715 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2716 GetProcessOutput();
2717
2718 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002719 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002720 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002721 }
2722
2723 // Now emit the command error text from the command we just executed
2724 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002725 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002726 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002727 }
2728 }
2729
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002730 FinishHandlingCommand();
2731
Kate Stoneb9c1b512016-09-06 20:57:50 +00002732 switch (result.GetStatus()) {
2733 case eReturnStatusInvalid:
2734 case eReturnStatusSuccessFinishNoResult:
2735 case eReturnStatusSuccessFinishResult:
2736 case eReturnStatusStarted:
2737 break;
2738
2739 case eReturnStatusSuccessContinuingNoResult:
2740 case eReturnStatusSuccessContinuingResult:
2741 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2742 io_handler.SetIsDone(true);
2743 break;
2744
2745 case eReturnStatusFailed:
2746 m_num_errors++;
2747 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2748 io_handler.SetIsDone(true);
2749 break;
2750
2751 case eReturnStatusQuit:
2752 m_quit_requested = true;
2753 io_handler.SetIsDone(true);
2754 break;
2755 }
2756
2757 // Finally, if we're going to stop on crash, check that here:
2758 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2759 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2760 bool should_stop = false;
2761 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2762 if (target_sp) {
2763 ProcessSP process_sp(target_sp->GetProcessSP());
2764 if (process_sp) {
2765 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2766 StopReason reason = thread_sp->GetStopReason();
2767 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2768 reason == eStopReasonInstrumentation) &&
2769 !result.GetAbnormalStopWasExpected()) {
2770 should_stop = true;
2771 break;
2772 }
2773 }
2774 }
2775 }
2776 if (should_stop) {
2777 io_handler.SetIsDone(true);
2778 m_stopped_for_crash = true;
2779 }
2780 }
2781}
2782
2783bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2784 ExecutionContext exe_ctx(GetExecutionContext());
2785 Process *process = exe_ctx.GetProcessPtr();
2786
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002787 if (InterruptCommand())
2788 return true;
2789
Kate Stoneb9c1b512016-09-06 20:57:50 +00002790 if (process) {
2791 StateType state = process->GetState();
2792 if (StateIsRunningState(state)) {
2793 process->Halt();
2794 return true; // Don't do any updating when we are running
2795 }
2796 }
2797
2798 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2799 if (script_interpreter) {
2800 if (script_interpreter->Interrupt())
2801 return true;
2802 }
2803 return false;
2804}
2805
2806void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2807 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2808 void *baton) {
2809 Debugger &debugger = GetDebugger();
2810 IOHandlerSP io_handler_sp(
2811 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2812 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002813 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2814 llvm::StringRef(), // Continuation prompt
2815 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002816 debugger.GetUseColor(),
2817 0, // Don't show line numbers
2818 delegate)); // IOHandlerDelegate
2819
2820 if (io_handler_sp) {
2821 io_handler_sp->SetUserData(baton);
2822 if (asynchronously)
2823 debugger.PushIOHandler(io_handler_sp);
2824 else
2825 debugger.RunIOHandler(io_handler_sp);
2826 }
2827}
2828
2829void CommandInterpreter::GetPythonCommandsFromIOHandler(
2830 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2831 void *baton) {
2832 Debugger &debugger = GetDebugger();
2833 IOHandlerSP io_handler_sp(
2834 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2835 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002836 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2837 llvm::StringRef(), // Continuation prompt
2838 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002839 debugger.GetUseColor(),
2840 0, // Don't show line numbers
2841 delegate)); // IOHandlerDelegate
2842
2843 if (io_handler_sp) {
2844 io_handler_sp->SetUserData(baton);
2845 if (asynchronously)
2846 debugger.PushIOHandler(io_handler_sp);
2847 else
2848 debugger.RunIOHandler(io_handler_sp);
2849 }
2850}
2851
2852bool CommandInterpreter::IsActive() {
2853 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2854}
2855
2856lldb::IOHandlerSP
2857CommandInterpreter::GetIOHandler(bool force_create,
2858 CommandInterpreterRunOptions *options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002859 // Always re-create the IOHandlerEditline in case the input changed. The old
2860 // instance might have had a non-interactive input and now it does or vice
2861 // versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002862 if (force_create || !m_command_io_handler_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002863 // Always re-create the IOHandlerEditline in case the input changed. The
2864 // old instance might have had a non-interactive input and now it does or
2865 // vice versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002866 uint32_t flags = 0;
2867
2868 if (options) {
2869 if (options->m_stop_on_continue == eLazyBoolYes)
2870 flags |= eHandleCommandFlagStopOnContinue;
2871 if (options->m_stop_on_error == eLazyBoolYes)
2872 flags |= eHandleCommandFlagStopOnError;
2873 if (options->m_stop_on_crash == eLazyBoolYes)
2874 flags |= eHandleCommandFlagStopOnCrash;
2875 if (options->m_echo_commands != eLazyBoolNo)
2876 flags |= eHandleCommandFlagEchoCommand;
2877 if (options->m_print_results != eLazyBoolNo)
2878 flags |= eHandleCommandFlagPrintResult;
2879 } else {
2880 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2881 }
2882
2883 m_command_io_handler_sp.reset(new IOHandlerEditline(
2884 m_debugger, IOHandler::Type::CommandInterpreter,
2885 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2886 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002887 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002888 false, // Don't enable multiple line input, just single line commands
2889 m_debugger.GetUseColor(),
2890 0, // Don't show line numbers
2891 *this));
2892 }
2893 return m_command_io_handler_sp;
2894}
2895
2896void CommandInterpreter::RunCommandInterpreter(
2897 bool auto_handle_events, bool spawn_thread,
2898 CommandInterpreterRunOptions &options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002899 // Always re-create the command interpreter when we run it in case any file
2900 // handles have changed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002901 bool force_create = true;
2902 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2903 m_stopped_for_crash = false;
2904
2905 if (auto_handle_events)
2906 m_debugger.StartEventHandlerThread();
2907
2908 if (spawn_thread) {
2909 m_debugger.StartIOHandlerThread();
2910 } else {
2911 m_debugger.ExecuteIOHandlers();
2912
2913 if (auto_handle_events)
2914 m_debugger.StopEventHandlerThread();
2915 }
2916}
2917
2918CommandObject *
2919CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2920 CommandReturnObject &result) {
2921 std::string scratch_command(command_line); // working copy so we don't modify
2922 // command_line unless we succeed
2923 CommandObject *cmd_obj = nullptr;
2924 StreamString revised_command_line;
2925 bool wants_raw_input = false;
2926 size_t actual_cmd_name_len = 0;
2927 std::string next_word;
2928 StringList matches;
2929 bool done = false;
2930 while (!done) {
2931 char quote_char = '\0';
2932 std::string suffix;
2933 ExtractCommand(scratch_command, next_word, suffix, quote_char);
2934 if (cmd_obj == nullptr) {
2935 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002936 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00002937 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002938 bool is_real_command =
2939 (is_alias == false) ||
2940 (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
2941 if (!is_real_command) {
2942 matches.Clear();
2943 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002944 cmd_obj =
2945 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002946 revised_command_line.Printf("%s", alias_result.c_str());
2947 if (cmd_obj) {
2948 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00002949 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002950 }
2951 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002952 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00002953 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
2954 actual_cmd_name_len += cmd_name.size();
2955 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002956 wants_raw_input = cmd_obj->WantsRawCommandString();
2957 } else {
2958 revised_command_line.Printf("%s", next_word.c_str());
2959 }
2960 }
2961 } else {
2962 if (cmd_obj->IsMultiwordObject()) {
2963 CommandObject *sub_cmd_obj =
2964 cmd_obj->GetSubcommandObject(next_word.c_str());
2965 if (sub_cmd_obj) {
Adrian Prantl05097242018-04-30 16:49:04 +00002966 // The subcommand's name includes the parent command's name, so
2967 // restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00002968 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
2969 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002970 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00002971 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002972 cmd_obj = sub_cmd_obj;
2973 wants_raw_input = cmd_obj->WantsRawCommandString();
2974 } else {
2975 if (quote_char)
2976 revised_command_line.Printf(" %c%s%s%c", quote_char,
2977 next_word.c_str(), suffix.c_str(),
2978 quote_char);
2979 else
2980 revised_command_line.Printf(" %s%s", next_word.c_str(),
2981 suffix.c_str());
2982 done = true;
2983 }
2984 } else {
2985 if (quote_char)
2986 revised_command_line.Printf(" %c%s%s%c", quote_char,
2987 next_word.c_str(), suffix.c_str(),
2988 quote_char);
2989 else
2990 revised_command_line.Printf(" %s%s", next_word.c_str(),
2991 suffix.c_str());
2992 done = true;
2993 }
2994 }
2995
2996 if (cmd_obj == nullptr) {
2997 const size_t num_matches = matches.GetSize();
2998 if (matches.GetSize() > 1) {
2999 StreamString error_msg;
3000 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3001 next_word.c_str());
3002
3003 for (uint32_t i = 0; i < num_matches; ++i) {
3004 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3005 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003006 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003007 } else {
3008 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003009 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003010 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3011 next_word.c_str());
3012 }
3013 result.SetStatus(eReturnStatusFailed);
3014 return nullptr;
3015 }
3016
3017 if (cmd_obj->IsMultiwordObject()) {
3018 if (!suffix.empty()) {
3019 result.AppendErrorWithFormat(
3020 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3021 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003022 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003023 next_word.empty() ? "" : next_word.c_str(),
3024 next_word.empty() ? " -- " : " ", suffix.c_str());
3025 result.SetStatus(eReturnStatusFailed);
3026 return nullptr;
3027 }
3028 } else {
3029 // If we found a normal command, we are done
3030 done = true;
3031 if (!suffix.empty()) {
3032 switch (suffix[0]) {
3033 case '/':
3034 // GDB format suffixes
3035 {
3036 Options *command_options = cmd_obj->GetOptions();
3037 if (command_options &&
3038 command_options->SupportsLongOption("gdb-format")) {
3039 std::string gdb_format_option("--gdb-format=");
3040 gdb_format_option += (suffix.c_str() + 1);
3041
Zachary Turnerc1564272016-11-16 21:15:24 +00003042 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003043 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3044 if (arg_terminator_idx != std::string::npos) {
3045 // Insert the gdb format option before the "--" that terminates
3046 // options
3047 gdb_format_option.append(1, ' ');
3048 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003049 revised_command_line.Clear();
3050 revised_command_line.PutCString(cmd);
3051 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003052 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3053
3054 if (wants_raw_input &&
3055 FindArgumentTerminator(cmd) == std::string::npos)
3056 revised_command_line.PutCString(" --");
3057 } else {
3058 result.AppendErrorWithFormat(
3059 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003060 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003061 result.SetStatus(eReturnStatusFailed);
3062 return nullptr;
3063 }
3064 }
3065 break;
3066
3067 default:
3068 result.AppendErrorWithFormat(
3069 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3070 result.SetStatus(eReturnStatusFailed);
3071 return nullptr;
3072 }
3073 }
3074 }
3075 if (scratch_command.empty())
3076 done = true;
3077 }
3078
3079 if (!scratch_command.empty())
3080 revised_command_line.Printf(" %s", scratch_command.c_str());
3081
3082 if (cmd_obj != NULL)
Zachary Turnerc1564272016-11-16 21:15:24 +00003083 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003084
3085 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003086}