blob: df27eb24b5291f0b973735e908d49f4f44a1f8cf [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 Claytonf0066ad2014-05-02 00:45:31 +000045#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000046#include "lldb/Core/StreamFile.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000047#include "lldb/Utility/Log.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
Kate Stoneb9c1b512016-09-06 20:57:50 +000079static PropertyDefinition g_properties[] = {
80 {"expand-regex-aliases", OptionValue::eTypeBoolean, true, false, nullptr,
81 nullptr, "If true, regular expression alias commands will show the "
82 "expanded command that will be executed. This can be used to "
83 "debug new regular expression alias commands."},
84 {"prompt-on-quit", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
85 "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,
89 nullptr, 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,
92 nullptr,
93 "If true, blank lines will be printed between between REPL submissions."},
94 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
95
96enum {
97 ePropertyExpandRegexAliases = 0,
98 ePropertyPromptOnQuit = 1,
99 ePropertyStopCmdSourceOnError = 2,
100 eSpaceReplPrompts = 3
Greg Clayton754a9362012-08-23 00:22:02 +0000101};
102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103ConstString &CommandInterpreter::GetStaticBroadcasterClass() {
104 static ConstString class_name("lldb.commandInterpreter");
105 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000106}
107
Kate Stoneb9c1b512016-09-06 20:57:50 +0000108CommandInterpreter::CommandInterpreter(Debugger &debugger,
109 ScriptLanguage script_language,
110 bool synchronous_execution)
111 : Broadcaster(debugger.GetBroadcasterManager(),
112 CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
113 Properties(OptionValuePropertiesSP(
114 new OptionValueProperties(ConstString("interpreter")))),
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000115 IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 m_debugger(debugger), m_synchronous_execution(synchronous_execution),
117 m_skip_lldbinit_files(false), m_skip_app_init_files(false),
118 m_script_interpreter_sp(), m_command_io_handler_sp(), m_comment_char('#'),
119 m_batch_command_mode(false), m_truncation_warning(eNoTruncation),
120 m_command_source_depth(0), m_num_errors(0), m_quit_requested(false),
121 m_stopped_for_crash(false) {
122 debugger.SetScriptLanguage(script_language);
123 SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit");
124 SetEventName(eBroadcastBitResetPrompt, "reset-prompt");
125 SetEventName(eBroadcastBitQuitCommandReceived, "quit");
126 CheckInWithManager();
127 m_collection_sp->Initialize(g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000128}
129
Kate Stoneb9c1b512016-09-06 20:57:50 +0000130bool CommandInterpreter::GetExpandRegexAliases() const {
131 const uint32_t idx = ePropertyExpandRegexAliases;
132 return m_collection_sp->GetPropertyAtIndexAsBoolean(
133 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000134}
135
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136bool CommandInterpreter::GetPromptOnQuit() const {
137 const uint32_t idx = ePropertyPromptOnQuit;
138 return m_collection_sp->GetPropertyAtIndexAsBoolean(
139 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000140}
Greg Clayton754a9362012-08-23 00:22:02 +0000141
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142void CommandInterpreter::SetPromptOnQuit(bool b) {
143 const uint32_t idx = ePropertyPromptOnQuit;
144 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ilia Kacf28be2015-03-23 22:45:13 +0000145}
146
Raphael Isemannc094d232018-07-11 17:18:01 +0000147void CommandInterpreter::AllowExitCodeOnQuit(bool allow) {
148 m_allow_exit_code = allow;
149 if (!allow)
150 m_quit_exit_code.reset();
151}
152
153bool CommandInterpreter::SetQuitExitCode(int exit_code) {
154 if (!m_allow_exit_code)
155 return false;
156 m_quit_exit_code = exit_code;
157 return true;
158}
159
160int CommandInterpreter::GetQuitExitCode(bool &exited) const {
161 exited = m_quit_exit_code.hasValue();
162 if (exited)
163 return *m_quit_exit_code;
164 return 0;
165}
166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167void CommandInterpreter::ResolveCommand(const char *command_line,
168 CommandReturnObject &result) {
169 std::string command = command_line;
170 if (ResolveCommandImpl(command, result) != nullptr) {
171 result.AppendMessageWithFormat("%s", command.c_str());
172 result.SetStatus(eReturnStatusSuccessFinishResult);
173 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000174}
175
Kate Stoneb9c1b512016-09-06 20:57:50 +0000176bool CommandInterpreter::GetStopCmdSourceOnError() const {
177 const uint32_t idx = ePropertyStopCmdSourceOnError;
178 return m_collection_sp->GetPropertyAtIndexAsBoolean(
179 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000180}
181
Kate Stoneb9c1b512016-09-06 20:57:50 +0000182bool CommandInterpreter::GetSpaceReplPrompts() const {
183 const uint32_t idx = eSpaceReplPrompts;
184 return m_collection_sp->GetPropertyAtIndexAsBoolean(
185 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callanan66810412015-10-19 23:11:07 +0000186}
187
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188void CommandInterpreter::Initialize() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000189 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
190 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000191
Kate Stoneb9c1b512016-09-06 20:57:50 +0000192 CommandReturnObject result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000193
Kate Stoneb9c1b512016-09-06 20:57:50 +0000194 LoadCommandDictionary();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000195
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196 // An alias arguments vector to reuse - reset it before use...
197 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
198
199 // Set up some initial aliases.
200 CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
201 if (cmd_obj_sp) {
202 AddAlias("q", cmd_obj_sp);
203 AddAlias("exit", cmd_obj_sp);
204 }
205
206 cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
207 if (cmd_obj_sp)
208 AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
209
210 cmd_obj_sp = GetCommandSPExact("process detach", false);
211 if (cmd_obj_sp) {
212 AddAlias("detach", cmd_obj_sp);
213 }
214
215 cmd_obj_sp = GetCommandSPExact("process continue", false);
216 if (cmd_obj_sp) {
217 AddAlias("c", cmd_obj_sp);
218 AddAlias("continue", cmd_obj_sp);
219 }
220
221 cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
222 if (cmd_obj_sp)
223 AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
224
225 cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
226 if (cmd_obj_sp)
227 AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
228
229 cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
230 if (cmd_obj_sp) {
231 AddAlias("stepi", cmd_obj_sp);
232 AddAlias("si", cmd_obj_sp);
233 }
234
235 cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
236 if (cmd_obj_sp) {
237 AddAlias("nexti", cmd_obj_sp);
238 AddAlias("ni", cmd_obj_sp);
239 }
240
241 cmd_obj_sp = GetCommandSPExact("thread step-in", false);
242 if (cmd_obj_sp) {
243 AddAlias("s", cmd_obj_sp);
244 AddAlias("step", cmd_obj_sp);
245 CommandAlias *sif_alias = AddAlias(
246 "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
247 if (sif_alias) {
248 sif_alias->SetHelp("Step through the current block, stopping if you step "
249 "directly into a function whose name matches the "
250 "TargetFunctionName.");
251 sif_alias->SetSyntax("sif <TargetFunctionName>");
Caroline Ticeca90c472011-05-06 21:37:15 +0000252 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000254
Kate Stoneb9c1b512016-09-06 20:57:50 +0000255 cmd_obj_sp = GetCommandSPExact("thread step-over", false);
256 if (cmd_obj_sp) {
257 AddAlias("n", cmd_obj_sp);
258 AddAlias("next", cmd_obj_sp);
259 }
260
261 cmd_obj_sp = GetCommandSPExact("thread step-out", false);
262 if (cmd_obj_sp) {
263 AddAlias("finish", cmd_obj_sp);
264 }
265
266 cmd_obj_sp = GetCommandSPExact("frame select", false);
267 if (cmd_obj_sp) {
268 AddAlias("f", cmd_obj_sp);
269 }
270
271 cmd_obj_sp = GetCommandSPExact("thread select", false);
272 if (cmd_obj_sp) {
273 AddAlias("t", cmd_obj_sp);
274 }
275
276 cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
277 if (cmd_obj_sp) {
278 AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
279 AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
280 }
281
282 cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
283 if (cmd_obj_sp) {
284 AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
285 AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
286 }
287
288 cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
289 if (cmd_obj_sp)
290 AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
291
292 cmd_obj_sp = GetCommandSPExact("memory read", false);
293 if (cmd_obj_sp)
294 AddAlias("x", cmd_obj_sp);
295
296 cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
297 if (cmd_obj_sp)
298 AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
299
300 cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
301 if (cmd_obj_sp)
302 AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
303
304 cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
305 if (cmd_obj_sp)
306 AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
307
308 cmd_obj_sp = GetCommandSPExact("disassemble", false);
309 if (cmd_obj_sp)
310 AddAlias("dis", cmd_obj_sp);
311
312 cmd_obj_sp = GetCommandSPExact("disassemble", false);
313 if (cmd_obj_sp)
314 AddAlias("di", cmd_obj_sp);
315
316 cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
317 if (cmd_obj_sp)
318 AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
319
320 cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
321 if (cmd_obj_sp)
322 AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
323
324 cmd_obj_sp = GetCommandSPExact("target create", false);
325 if (cmd_obj_sp)
326 AddAlias("file", cmd_obj_sp);
327
328 cmd_obj_sp = GetCommandSPExact("target modules", false);
329 if (cmd_obj_sp)
330 AddAlias("image", cmd_obj_sp);
331
332 alias_arguments_vector_sp.reset(new OptionArgVector);
333
334 cmd_obj_sp = GetCommandSPExact("expression", false);
335 if (cmd_obj_sp) {
336 AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
337 AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
338 AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
339 if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
340 po->SetHelp("Evaluate an expression on the current thread. Displays any "
341 "returned value with formatting "
342 "controlled by the type's author.");
343 po->SetHelpLong("");
Johnny Chen6d675242012-08-24 18:15:45 +0000344 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345 AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
346 AddAlias("poarray", cmd_obj_sp,
347 "--object-description --element-count %1 --")
348 ->SetHelpLong("");
349 }
Johnny Chen6d675242012-08-24 18:15:45 +0000350
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 cmd_obj_sp = GetCommandSPExact("process kill", false);
352 if (cmd_obj_sp) {
353 AddAlias("kill", cmd_obj_sp);
354 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000355
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 cmd_obj_sp = GetCommandSPExact("process launch", false);
357 if (cmd_obj_sp) {
Chaoren Lin6fc5c7f2016-02-26 03:36:27 +0000358 alias_arguments_vector_sp.reset(new OptionArgVector);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
360 AddAlias("r", cmd_obj_sp, "--");
361 AddAlias("run", cmd_obj_sp, "--");
Jason Molenda85da3122012-07-06 02:46:23 +0000362#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363#if defined(__APPLE__)
364 std::string shell_option;
365 shell_option.append("--shell-expand-args");
366 shell_option.append(" true");
367 shell_option.append(" --");
368 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
369 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
370#else
371 StreamString defaultshell;
372 defaultshell.Printf("--shell=%s --",
373 HostInfo::GetDefaultShell().GetPath().c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +0000374 AddAlias("r", cmd_obj_sp, defaultshell.GetString());
375 AddAlias("run", cmd_obj_sp, defaultshell.GetString());
Jason Molenda85da3122012-07-06 02:46:23 +0000376#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377#endif
378 }
379
380 cmd_obj_sp = GetCommandSPExact("target symbols add", false);
381 if (cmd_obj_sp) {
382 AddAlias("add-dsym", cmd_obj_sp);
383 }
384
385 cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
386 if (cmd_obj_sp) {
387 AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
388 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000389}
390
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391void CommandInterpreter::Clear() {
392 m_command_io_handler_sp.reset();
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000393
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 if (m_script_interpreter_sp)
395 m_script_interpreter_sp->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000396}
397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
399 // This function has not yet been implemented.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 // Look for any embedded script command
402 // If found,
403 // get interpreter object from the command dictionary,
404 // call execute_one_command on it,
405 // get the results as a string,
406 // substitute that string for current stuff.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000407
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 return arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000409}
410
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411void CommandInterpreter::LoadCommandDictionary() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000412 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
413 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000414
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000416
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
418 m_command_dict["breakpoint"] =
419 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
420 m_command_dict["bugreport"] =
421 CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
422 m_command_dict["command"] =
423 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
424 m_command_dict["disassemble"] =
425 CommandObjectSP(new CommandObjectDisassemble(*this));
426 m_command_dict["expression"] =
427 CommandObjectSP(new CommandObjectExpression(*this));
428 m_command_dict["frame"] =
429 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
430 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
431 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
432 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
433 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
434 m_command_dict["platform"] =
435 CommandObjectSP(new CommandObjectPlatform(*this));
436 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
437 m_command_dict["process"] =
438 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
439 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
440 m_command_dict["register"] =
441 CommandObjectSP(new CommandObjectRegister(*this));
442 m_command_dict["script"] =
443 CommandObjectSP(new CommandObjectScript(*this, script_language));
444 m_command_dict["settings"] =
445 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
446 m_command_dict["source"] =
447 CommandObjectSP(new CommandObjectMultiwordSource(*this));
Davide Italiano24fff242018-04-13 18:02:39 +0000448 m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000449 m_command_dict["target"] =
450 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
451 m_command_dict["thread"] =
452 CommandObjectSP(new CommandObjectMultiwordThread(*this));
453 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
454 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
455 m_command_dict["watchpoint"] =
456 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
457 m_command_dict["language"] =
458 CommandObjectSP(new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000459
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 const char *break_regexes[][2] = {
461 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
462 "breakpoint set --file '%1' --line %2"},
463 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
464 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
465 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
466 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
467 "breakpoint set --name '%1'"},
468 {"^(-.*)$", "breakpoint set %1"},
469 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
470 "breakpoint set --name '%2' --shlib '%1'"},
471 {"^\\&(.*[^[:space:]])[[:space:]]*$",
472 "breakpoint set --name '%1' --skip-prologue=0"},
473 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
474 "breakpoint set --name '%1'"}};
Kate Stone7428a182016-07-14 22:03:10 +0000475
Kate Stoneb9c1b512016-09-06 20:57:50 +0000476 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000477
Kate Stoneb9c1b512016-09-06 20:57:50 +0000478 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap(
479 new CommandObjectRegexCommand(
480 *this, "_regexp-break",
481 "Set a breakpoint using one of several shorthand formats.\n",
482 "\n"
483 "_regexp-break <filename>:<linenum>\n"
484 " main.c:12 // Break at line 12 of "
485 "main.c\n\n"
486 "_regexp-break <linenum>\n"
487 " 12 // Break at line 12 of current "
488 "file\n\n"
489 "_regexp-break 0x<address>\n"
490 " 0x1234000 // Break at address "
491 "0x1234000\n\n"
492 "_regexp-break <name>\n"
493 " main // Break in 'main' after the "
494 "prologue\n\n"
495 "_regexp-break &<name>\n"
496 " &main // Break at first instruction "
497 "in 'main'\n\n"
498 "_regexp-break <module>`<name>\n"
499 " libc.so`malloc // Break in 'malloc' from "
500 "'libc.so'\n\n"
501 "_regexp-break /<source-regex>/\n"
502 " /break here/ // Break on source lines in "
503 "current file\n"
504 " // containing text 'break "
505 "here'.\n",
506 2, CommandCompletions::eSymbolCompletion |
507 CommandCompletions::eSourceFileCompletion,
508 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000509
Kate Stoneb9c1b512016-09-06 20:57:50 +0000510 if (break_regex_cmd_ap.get()) {
511 bool success = true;
512 for (size_t i = 0; i < num_regexes; i++) {
513 success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0],
514 break_regexes[i][1]);
515 if (!success)
516 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000517 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000518 success =
519 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Jim Inghamffba2292011-03-22 02:29:32 +0000520
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 if (success) {
522 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
523 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
Jim Inghamca36cd12012-10-05 19:16:31 +0000524 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 }
Jim Inghamca36cd12012-10-05 19:16:31 +0000526
Kate Stoneb9c1b512016-09-06 20:57:50 +0000527 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap(
528 new CommandObjectRegexCommand(
529 *this, "_regexp-tbreak",
530 "Set a one-shot breakpoint using one of several shorthand formats.\n",
531 "\n"
532 "_regexp-break <filename>:<linenum>\n"
533 " main.c:12 // Break at line 12 of "
534 "main.c\n\n"
535 "_regexp-break <linenum>\n"
536 " 12 // Break at line 12 of current "
537 "file\n\n"
538 "_regexp-break 0x<address>\n"
539 " 0x1234000 // Break at address "
540 "0x1234000\n\n"
541 "_regexp-break <name>\n"
542 " main // Break in 'main' after the "
543 "prologue\n\n"
544 "_regexp-break &<name>\n"
545 " &main // Break at first instruction "
546 "in 'main'\n\n"
547 "_regexp-break <module>`<name>\n"
548 " libc.so`malloc // Break in 'malloc' from "
549 "'libc.so'\n\n"
550 "_regexp-break /<source-regex>/\n"
551 " /break here/ // Break on source lines in "
552 "current file\n"
553 " // containing text 'break "
554 "here'.\n",
555 2, CommandCompletions::eSymbolCompletion |
556 CommandCompletions::eSourceFileCompletion,
557 false));
558
559 if (tbreak_regex_cmd_ap.get()) {
560 bool success = true;
561 for (size_t i = 0; i < num_regexes; i++) {
562 // If you add a resultant command string longer than 1024 characters be
563 // sure to increase the size of this buffer.
564 char buffer[1024];
565 int num_printed =
Frederic Riss49c9d8b2018-06-18 04:34:33 +0000566 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1");
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000567 lldbassert(num_printed < 1024);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 UNUSED_IF_ASSERT_DISABLED(num_printed);
569 success =
570 tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer);
571 if (!success)
572 break;
Johnny Chen6d675242012-08-24 18:15:45 +0000573 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574 success =
575 tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Kate Stone7428a182016-07-14 22:03:10 +0000576
Kate Stoneb9c1b512016-09-06 20:57:50 +0000577 if (success) {
578 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
579 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
580 tbreak_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000581 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 }
Kate Stone7428a182016-07-14 22:03:10 +0000583
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap(
585 new CommandObjectRegexCommand(
586 *this, "_regexp-attach", "Attach to process by ID or name.",
587 "_regexp-attach <pid> | <process-name>", 2, 0, false));
588 if (attach_regex_cmd_ap.get()) {
589 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
590 "process attach --pid %1") &&
591 attach_regex_cmd_ap->AddRegexCommand(
592 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
593 // specified get passed to
594 // 'process attach'
595 attach_regex_cmd_ap->AddRegexCommand("^(.+)$",
596 "process attach --name '%1'") &&
597 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) {
598 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
599 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
600 attach_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000601 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000602 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000603
Kate Stoneb9c1b512016-09-06 20:57:50 +0000604 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap(
605 new CommandObjectRegexCommand(*this, "_regexp-down",
606 "Select a newer stack frame. Defaults to "
607 "moving one frame, a numeric argument can "
608 "specify an arbitrary number.",
609 "_regexp-down [<count>]", 2, 0, false));
610 if (down_regex_cmd_ap.get()) {
611 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
612 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
613 "frame select -r -%1")) {
614 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
615 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000616 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000617 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000618
Kate Stoneb9c1b512016-09-06 20:57:50 +0000619 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap(
620 new CommandObjectRegexCommand(
621 *this, "_regexp-up",
622 "Select an older stack frame. Defaults to moving one "
623 "frame, a numeric argument can specify an arbitrary number.",
624 "_regexp-up [<count>]", 2, 0, false));
625 if (up_regex_cmd_ap.get()) {
626 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
627 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
628 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
629 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000630 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000631 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000632
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap(
634 new CommandObjectRegexCommand(
635 *this, "_regexp-display",
636 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
637 "_regexp-display expression", 2, 0, false));
638 if (display_regex_cmd_ap.get()) {
639 if (display_regex_cmd_ap->AddRegexCommand(
640 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
641 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
642 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
643 display_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000644 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000645 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000646
Kate Stoneb9c1b512016-09-06 20:57:50 +0000647 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap(
648 new CommandObjectRegexCommand(
649 *this, "_regexp-undisplay", "Stop displaying expression at every "
650 "stop (specified by stop-hook index.)",
651 "_regexp-undisplay stop-hook-number", 2, 0, false));
652 if (undisplay_regex_cmd_ap.get()) {
653 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
654 "target stop-hook delete %1")) {
655 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
656 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
657 undisplay_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000658 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000660
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap(
662 new CommandObjectRegexCommand(
663 *this, "gdb-remote", "Connect to a process via remote GDB server. "
664 "If no host is specifed, localhost is assumed.",
665 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
666 if (connect_gdb_remote_cmd_ap.get()) {
667 if (connect_gdb_remote_cmd_ap->AddRegexCommand(
Chris Bieneman51978f52017-04-27 16:13:58 +0000668 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
669 "process connect --plugin gdb-remote connect://%1:%2") &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670 connect_gdb_remote_cmd_ap->AddRegexCommand(
671 "^([[:digit:]]+)$",
672 "process connect --plugin gdb-remote connect://localhost:%1")) {
673 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
674 m_command_dict[command_sp->GetCommandName()] = command_sp;
Jason Molenda4cddfed2012-10-05 05:29:32 +0000675 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000676 }
Jason Molenda4cddfed2012-10-05 05:29:32 +0000677
Kate Stoneb9c1b512016-09-06 20:57:50 +0000678 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap(
679 new CommandObjectRegexCommand(
680 *this, "kdp-remote", "Connect to a process via remote KDP server. "
681 "If no UDP port is specified, port 41139 is "
682 "assumed.",
683 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
684 if (connect_kdp_remote_cmd_ap.get()) {
685 if (connect_kdp_remote_cmd_ap->AddRegexCommand(
686 "^([^:]+:[[:digit:]]+)$",
687 "process connect --plugin kdp-remote udp://%1") &&
688 connect_kdp_remote_cmd_ap->AddRegexCommand(
689 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
690 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
691 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Clayton6bade322013-02-01 23:33:03 +0000692 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000693 }
Greg Clayton6bade322013-02-01 23:33:03 +0000694
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap(
696 new CommandObjectRegexCommand(
697 *this, "_regexp-bt",
698 "Show the current thread's call stack. Any numeric argument "
699 "displays at most that many "
700 "frames. The argument 'all' displays all threads.",
701 "bt [<digit> | all]", 2, 0, false));
702 if (bt_regex_cmd_ap.get()) {
703 // accept but don't document "bt -c <number>" -- before bt was a regex
Adrian Prantl05097242018-04-30 16:49:04 +0000704 // command if you wanted to backtrace three frames you would do "bt -c 3"
705 // but the intention is to have this emulate the gdb "bt" command and so
706 // now "bt 3" is the preferred form, in line with gdb.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$",
708 "thread backtrace -c %1") &&
709 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$",
710 "thread backtrace -c %1") &&
711 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
712 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) {
713 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
714 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Claytonef5651d2013-02-12 18:52:24 +0000715 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716 }
Greg Claytonef5651d2013-02-12 18:52:24 +0000717
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap(
719 new CommandObjectRegexCommand(
720 *this, "_regexp-list",
721 "List relevant source code using one of several shorthand formats.",
722 "\n"
723 "_regexp-list <file>:<line> // List around specific file/line\n"
724 "_regexp-list <line> // List current file around specified "
725 "line\n"
726 "_regexp-list <function-name> // List specified function\n"
727 "_regexp-list 0x<address> // List around specified address\n"
728 "_regexp-list -[<count>] // List previous <count> lines\n"
729 "_regexp-list // List subsequent lines",
730 2, CommandCompletions::eSourceFileCompletion, false));
731 if (list_regex_cmd_ap.get()) {
732 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
733 "source list --line %1") &&
734 list_regex_cmd_ap->AddRegexCommand(
735 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
736 "]*$",
737 "source list --file '%1' --line %2") &&
738 list_regex_cmd_ap->AddRegexCommand(
739 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
740 "source list --address %1") &&
741 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$",
742 "source list --reverse") &&
743 list_regex_cmd_ap->AddRegexCommand(
744 "^-([[:digit:]]+)[[:space:]]*$",
745 "source list --reverse --count %1") &&
746 list_regex_cmd_ap->AddRegexCommand("^(.+)$",
747 "source list --name \"%1\"") &&
748 list_regex_cmd_ap->AddRegexCommand("^$", "source list")) {
749 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
750 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
Richard Mittonf86248d2013-09-12 02:20:34 +0000751 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 }
Richard Mittonf86248d2013-09-12 02:20:34 +0000753
Kate Stoneb9c1b512016-09-06 20:57:50 +0000754 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap(
755 new CommandObjectRegexCommand(
756 *this, "_regexp-env",
757 "Shorthand for viewing and setting environment variables.",
758 "\n"
759 "_regexp-env // Show enrivonment\n"
760 "_regexp-env <name>=<value> // Set an environment variable",
761 2, 0, false));
762 if (env_regex_cmd_ap.get()) {
763 if (env_regex_cmd_ap->AddRegexCommand("^$",
764 "settings show target.env-vars") &&
765 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
766 "settings set target.env-vars %1")) {
767 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
768 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
769 }
770 }
771
772 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap(
773 new CommandObjectRegexCommand(
774 *this, "_regexp-jump", "Set the program counter to a new address.",
775 "\n"
776 "_regexp-jump <line>\n"
777 "_regexp-jump +<line-offset> | -<line-offset>\n"
778 "_regexp-jump <file>:<line>\n"
779 "_regexp-jump *<addr>\n",
780 2, 0, false));
781 if (jump_regex_cmd_ap.get()) {
782 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$",
783 "thread jump --addr %1") &&
784 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
785 "thread jump --line %1") &&
786 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$",
787 "thread jump --file %1 --line %2") &&
788 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$",
789 "thread jump --by %1")) {
790 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
791 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
792 }
793 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000794}
795
Kate Stoneb9c1b512016-09-06 20:57:50 +0000796int CommandInterpreter::GetCommandNamesMatchingPartialString(
797 const char *cmd_str, bool include_aliases, StringList &matches) {
798 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000799
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 if (include_aliases) {
801 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches);
802 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000803
Kate Stoneb9c1b512016-09-06 20:57:50 +0000804 return matches.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000805}
806
Zachary Turnera4496982016-10-05 21:14:38 +0000807CommandObjectSP CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000808 bool include_aliases,
809 bool exact,
Zachary Turnera4496982016-10-05 21:14:38 +0000810 StringList *matches) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000811 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000812
Zachary Turnera4496982016-10-05 21:14:38 +0000813 std::string cmd = cmd_str;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000814
Kate Stoneb9c1b512016-09-06 20:57:50 +0000815 if (HasCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000816 auto pos = m_command_dict.find(cmd);
Greg Claytonb5472782015-01-09 19:08:20 +0000817 if (pos != m_command_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 command_sp = pos->second;
819 }
820
821 if (include_aliases && HasAliases()) {
822 auto alias_pos = m_alias_dict.find(cmd);
823 if (alias_pos != m_alias_dict.end())
824 command_sp = alias_pos->second;
825 }
826
827 if (HasUserCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000828 auto pos = m_user_dict.find(cmd);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000829 if (pos != m_user_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830 command_sp = pos->second;
831 }
832
833 if (!exact && !command_sp) {
834 // We will only get into here if we didn't find any exact matches.
835
836 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
837
838 StringList local_matches;
839 if (matches == nullptr)
840 matches = &local_matches;
841
842 unsigned int num_cmd_matches = 0;
843 unsigned int num_alias_matches = 0;
844 unsigned int num_user_matches = 0;
845
846 // Look through the command dictionaries one by one, and if we get only one
Adrian Prantl05097242018-04-30 16:49:04 +0000847 // match from any of them in toto, then return that, otherwise return an
848 // empty CommandObjectSP and the list of matches.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000849
850 if (HasCommands()) {
851 num_cmd_matches =
Zachary Turnera4496982016-10-05 21:14:38 +0000852 AddNamesMatchingPartialString(m_command_dict, cmd_str, *matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000853 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000854
855 if (num_cmd_matches == 1) {
856 cmd.assign(matches->GetStringAtIndex(0));
Zachary Turnera4496982016-10-05 21:14:38 +0000857 auto pos = m_command_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000858 if (pos != m_command_dict.end())
859 real_match_sp = pos->second;
860 }
861
862 if (include_aliases && HasAliases()) {
863 num_alias_matches =
Zachary Turnera4496982016-10-05 21:14:38 +0000864 AddNamesMatchingPartialString(m_alias_dict, cmd_str, *matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865 }
866
867 if (num_alias_matches == 1) {
868 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
869 auto alias_pos = m_alias_dict.find(cmd);
870 if (alias_pos != m_alias_dict.end())
871 alias_match_sp = alias_pos->second;
872 }
873
874 if (HasUserCommands()) {
875 num_user_matches =
Zachary Turnera4496982016-10-05 21:14:38 +0000876 AddNamesMatchingPartialString(m_user_dict, cmd_str, *matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877 }
878
879 if (num_user_matches == 1) {
880 cmd.assign(
881 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
882
Zachary Turnera4496982016-10-05 21:14:38 +0000883 auto pos = m_user_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884 if (pos != m_user_dict.end())
885 user_match_sp = pos->second;
886 }
887
888 // If we got exactly one match, return that, otherwise return the match
889 // list.
890
891 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
892 if (num_cmd_matches)
893 return real_match_sp;
894 else if (num_alias_matches)
895 return alias_match_sp;
896 else
897 return user_match_sp;
898 }
899 } else if (matches && command_sp) {
Zachary Turnera4496982016-10-05 21:14:38 +0000900 matches->AppendString(cmd_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901 }
902
903 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000904}
905
Zachary Turnera4496982016-10-05 21:14:38 +0000906bool CommandInterpreter::AddCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000907 const lldb::CommandObjectSP &cmd_sp,
908 bool can_replace) {
909 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000910 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
911 "tried to add a CommandObject from a different interpreter");
Kate Stonea487aa42015-01-15 00:52:41 +0000912
Zachary Turnera4496982016-10-05 21:14:38 +0000913 if (name.empty())
914 return false;
915
916 std::string name_sstr(name);
917 auto name_iter = m_command_dict.find(name_sstr);
918 if (name_iter != m_command_dict.end()) {
919 if (!can_replace || !name_iter->second->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920 return false;
Zachary Turnera4496982016-10-05 21:14:38 +0000921 name_iter->second = cmd_sp;
922 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000923 m_command_dict[name_sstr] = cmd_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 }
Zachary Turnera4496982016-10-05 21:14:38 +0000925 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000926}
927
Zachary Turnera483f572016-10-05 21:14:49 +0000928bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000929 const lldb::CommandObjectSP &cmd_sp,
930 bool can_replace) {
931 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000932 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
933 "tried to add a CommandObject from a different interpreter");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000934
Kate Stoneb9c1b512016-09-06 20:57:50 +0000935 if (!name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000936 // do not allow replacement of internal commands
Zachary Turnera483f572016-10-05 21:14:49 +0000937 if (CommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000938 if (can_replace == false)
939 return false;
940 if (m_command_dict[name]->IsRemovable() == false)
Greg Clayton5a314712011-10-14 07:41:33 +0000941 return false;
942 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000943
Zachary Turnera483f572016-10-05 21:14:49 +0000944 if (UserCommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000945 if (can_replace == false)
946 return false;
947 if (m_user_dict[name]->IsRemovable() == false)
948 return false;
Caroline Tice844d2302010-12-09 22:52:49 +0000949 }
950
Kate Stoneb9c1b512016-09-06 20:57:50 +0000951 m_user_dict[name] = cmd_sp;
952 return true;
953 }
954 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000955}
956
Zachary Turnera4496982016-10-05 21:14:38 +0000957CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
958 bool include_aliases) const {
959 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +0000960 // it's a multi-word command.
961 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000962
Zachary Turnera4496982016-10-05 21:14:38 +0000963 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964 return ret_val;
965
966 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +0000967 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968 else {
969 // We have a multi-word command (seemingly), so we need to do more work.
970 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +0000971 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000972 include_aliases, true, nullptr);
973 if (cmd_obj_sp.get() != nullptr) {
Adrian Prantl05097242018-04-30 16:49:04 +0000974 // Loop through the rest of the words in the command (everything passed
975 // in was supposed to be part of a command name), and find the
976 // appropriate sub-command SP for each command word....
Kate Stoneb9c1b512016-09-06 20:57:50 +0000977 size_t end = cmd_words.GetArgumentCount();
978 for (size_t j = 1; j < end; ++j) {
979 if (cmd_obj_sp->IsMultiwordObject()) {
980 cmd_obj_sp =
981 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
982 if (cmd_obj_sp.get() == nullptr)
983 // The sub-command name was invalid. Fail and return the empty
984 // 'ret_val'.
985 return ret_val;
986 } else
987 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +0000988 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000989 return ret_val;
990 }
991 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +0000992 // command objects for them. Assign the last object retrieved to
993 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000994 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000995 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996 }
997 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000998}
999
Zachary Turnera4496982016-10-05 21:14:38 +00001000CommandObject *CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
1001 StringList *matches) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002 CommandObject *command_obj =
Zachary Turnera4496982016-10-05 21:14:38 +00001003 GetCommandSP(cmd_str, false, true, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001004
Kate Stoneb9c1b512016-09-06 20:57:50 +00001005 // If we didn't find an exact match to the command string in the commands,
Adrian Prantl05097242018-04-30 16:49:04 +00001006 // look in the aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007
1008 if (command_obj)
1009 return command_obj;
1010
Zachary Turnera4496982016-10-05 21:14:38 +00001011 command_obj = GetCommandSP(cmd_str, true, true, matches).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012
1013 if (command_obj)
1014 return command_obj;
1015
1016 // If there wasn't an exact match then look for an inexact one in just the
1017 // commands
Zachary Turnera4496982016-10-05 21:14:38 +00001018 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001019
1020 // Finally, if there wasn't an inexact match among the commands, look for an
Adrian Prantl05097242018-04-30 16:49:04 +00001021 // inexact match in both the commands and aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001022
1023 if (command_obj) {
1024 if (matches)
1025 matches->AppendString(command_obj->GetCommandName());
1026 return command_obj;
1027 }
1028
Zachary Turnera4496982016-10-05 21:14:38 +00001029 return GetCommandSP(cmd_str, true, false, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001030}
1031
Zachary Turnera483f572016-10-05 21:14:49 +00001032bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001034}
1035
Zachary Turnera483f572016-10-05 21:14:49 +00001036bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1037 std::string &full_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001038 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1039 if (exact_match) {
1040 full_name.assign(cmd);
1041 return exact_match;
1042 } else {
1043 StringList matches;
1044 size_t num_alias_matches;
1045 num_alias_matches =
1046 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1047 if (num_alias_matches == 1) {
1048 // Make sure this isn't shadowing a command in the regular command space:
1049 StringList regular_matches;
1050 const bool include_aliases = false;
1051 const bool exact = false;
1052 CommandObjectSP cmd_obj_sp(
1053 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1054 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1055 return false;
1056 else {
1057 full_name.assign(matches.GetStringAtIndex(0));
1058 return true;
1059 }
1060 } else
1061 return false;
1062 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001063}
1064
Zachary Turnera483f572016-10-05 21:14:49 +00001065bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001066 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001067}
1068
Zachary Turnera483f572016-10-05 21:14:49 +00001069bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001070 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071}
1072
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073CommandAlias *
Zachary Turnera483f572016-10-05 21:14:49 +00001074CommandInterpreter::AddAlias(llvm::StringRef alias_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075 lldb::CommandObjectSP &command_obj_sp,
Zachary Turnera483f572016-10-05 21:14:49 +00001076 llvm::StringRef args_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077 if (command_obj_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001078 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1079 "tried to add a CommandObject from a different interpreter");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080
1081 std::unique_ptr<CommandAlias> command_alias_up(
1082 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1083
1084 if (command_alias_up && command_alias_up->IsValid()) {
1085 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1086 return command_alias_up.release();
1087 }
1088
1089 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001090}
1091
Zachary Turnera483f572016-10-05 21:14:49 +00001092bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 auto pos = m_alias_dict.find(alias_name);
1094 if (pos != m_alias_dict.end()) {
1095 m_alias_dict.erase(pos);
1096 return true;
1097 }
1098 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001099}
1100
Zachary Turnera483f572016-10-05 21:14:49 +00001101bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001102 auto pos = m_command_dict.find(cmd);
1103 if (pos != m_command_dict.end()) {
1104 if (pos->second->IsRemovable()) {
1105 // Only regular expression objects or python commands are removable
1106 m_command_dict.erase(pos);
1107 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001108 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109 }
1110 return false;
1111}
Zachary Turnera483f572016-10-05 21:14:49 +00001112bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001113 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1114 if (pos != m_user_dict.end()) {
1115 m_user_dict.erase(pos);
1116 return true;
1117 }
1118 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001119}
1120
Kate Stoneb9c1b512016-09-06 20:57:50 +00001121void CommandInterpreter::GetHelp(CommandReturnObject &result,
1122 uint32_t cmd_types) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001123 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1124 if (!help_prologue.empty()) {
1125 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1126 help_prologue);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001128
Kate Stoneb9c1b512016-09-06 20:57:50 +00001129 CommandObject::CommandMap::const_iterator pos;
1130 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001131
Kate Stoneb9c1b512016-09-06 20:57:50 +00001132 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1133 result.AppendMessage("Debugger commands:");
1134 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001135
Kate Stoneb9c1b512016-09-06 20:57:50 +00001136 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1137 if (!(cmd_types & eCommandTypesHidden) &&
1138 (pos->first.compare(0, 1, "_") == 0))
1139 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001140
Zachary Turner0ac5f982016-11-08 04:12:42 +00001141 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1142 pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001143 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001144 result.AppendMessage("");
1145 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001146
Kate Stoneb9c1b512016-09-06 20:57:50 +00001147 if (!m_alias_dict.empty() &&
1148 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1149 result.AppendMessageWithFormat(
1150 "Current command abbreviations "
1151 "(type '%shelp command alias' for more info):\n",
1152 GetCommandPrefix());
1153 result.AppendMessage("");
1154 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001155
Kate Stoneb9c1b512016-09-06 20:57:50 +00001156 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1157 ++alias_pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001158 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
Kate Stoneb9c1b512016-09-06 20:57:50 +00001159 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001160 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001161 result.AppendMessage("");
1162 }
Greg Clayton14a35512011-09-11 00:01:44 +00001163
Kate Stoneb9c1b512016-09-06 20:57:50 +00001164 if (!m_user_dict.empty() &&
1165 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1166 result.AppendMessage("Current user-defined commands:");
1167 result.AppendMessage("");
1168 max_len = FindLongestCommandWord(m_user_dict);
1169 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001170 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1171 pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001172 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173 result.AppendMessage("");
1174 }
Greg Clayton14a35512011-09-11 00:01:44 +00001175
Kate Stoneb9c1b512016-09-06 20:57:50 +00001176 result.AppendMessageWithFormat(
1177 "For more information on any command, type '%shelp <command-name>'.\n",
1178 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001179}
1180
Zachary Turnera01bccd2016-10-05 21:14:56 +00001181CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1182 llvm::StringRef &command_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001183 // This function finds the final, lowest-level, alias-resolved command object
Adrian Prantl05097242018-04-30 16:49:04 +00001184 // whose 'Execute' function will eventually be invoked by the given command
1185 // line.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001186
1187 CommandObject *cmd_obj = nullptr;
1188 size_t start = command_string.find_first_not_of(k_white_space);
1189 size_t end = 0;
1190 bool done = false;
1191 while (!done) {
1192 if (start != std::string::npos) {
1193 // Get the next word from command_string.
1194 end = command_string.find_first_of(k_white_space, start);
1195 if (end == std::string::npos)
1196 end = command_string.size();
1197 std::string cmd_word = command_string.substr(start, end - start);
1198
1199 if (cmd_obj == nullptr)
1200 // Since cmd_obj is NULL we are on our first time through this loop.
Zachary Turnera01bccd2016-10-05 21:14:56 +00001201 // Check to see if cmd_word is a valid command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001202 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001203 else if (cmd_obj->IsMultiwordObject()) {
1204 // Our current object is a multi-word object; see if the cmd_word is a
1205 // valid sub-command for our object.
1206 CommandObject *sub_cmd_obj =
1207 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1208 if (sub_cmd_obj)
1209 cmd_obj = sub_cmd_obj;
1210 else // cmd_word was not a valid sub-command word, so we are done
1211 done = true;
1212 } else
1213 // We have a cmd_obj and it is not a multi-word object, so we are done.
1214 done = true;
1215
1216 // If we didn't find a valid command object, or our command object is not
Zachary Turnera01bccd2016-10-05 21:14:56 +00001217 // a multi-word object, or we are at the end of the command_string, then
1218 // we are done. Otherwise, find the start of the next word.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001219
1220 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1221 end >= command_string.size())
1222 done = true;
1223 else
1224 start = command_string.find_first_not_of(k_white_space, end);
1225 } else
1226 // Unable to find any more words.
1227 done = true;
1228 }
1229
Zachary Turnera01bccd2016-10-05 21:14:56 +00001230 command_string = command_string.substr(end);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001231 return cmd_obj;
1232}
1233
1234static const char *k_valid_command_chars =
1235 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1236static void StripLeadingSpaces(std::string &s) {
1237 if (!s.empty()) {
1238 size_t pos = s.find_first_not_of(k_white_space);
1239 if (pos == std::string::npos)
1240 s.clear();
1241 else if (pos == 0)
1242 return;
1243 s.erase(0, pos);
1244 }
1245}
1246
1247static size_t FindArgumentTerminator(const std::string &s) {
1248 const size_t s_len = s.size();
1249 size_t offset = 0;
1250 while (offset < s_len) {
1251 size_t pos = s.find("--", offset);
1252 if (pos == std::string::npos)
1253 break;
1254 if (pos > 0) {
1255 if (isspace(s[pos - 1])) {
Adrian Prantl05097242018-04-30 16:49:04 +00001256 // Check if the string ends "\s--" (where \s is a space character) or
1257 // if we have "\s--\s".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1259 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001260 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261 }
1262 }
1263 offset = pos + 2;
1264 }
1265 return std::string::npos;
1266}
1267
1268static bool ExtractCommand(std::string &command_string, std::string &command,
1269 std::string &suffix, char &quote_char) {
1270 command.clear();
1271 suffix.clear();
1272 StripLeadingSpaces(command_string);
1273
1274 bool result = false;
1275 quote_char = '\0';
1276
1277 if (!command_string.empty()) {
1278 const char first_char = command_string[0];
1279 if (first_char == '\'' || first_char == '"') {
1280 quote_char = first_char;
1281 const size_t end_quote_pos = command_string.find(quote_char, 1);
1282 if (end_quote_pos == std::string::npos) {
1283 command.swap(command_string);
1284 command_string.erase();
1285 } else {
1286 command.assign(command_string, 1, end_quote_pos - 1);
1287 if (end_quote_pos + 1 < command_string.size())
1288 command_string.erase(0, command_string.find_first_not_of(
1289 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001290 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001291 command_string.erase();
1292 }
1293 } else {
1294 const size_t first_space_pos =
1295 command_string.find_first_of(k_white_space);
1296 if (first_space_pos == std::string::npos) {
1297 command.swap(command_string);
1298 command_string.erase();
1299 } else {
1300 command.assign(command_string, 0, first_space_pos);
1301 command_string.erase(0, command_string.find_first_not_of(
1302 k_white_space, first_space_pos));
1303 }
1304 }
1305 result = true;
1306 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001307
Kate Stoneb9c1b512016-09-06 20:57:50 +00001308 if (!command.empty()) {
1309 // actual commands can't start with '-' or '_'
1310 if (command[0] != '-' && command[0] != '_') {
1311 size_t pos = command.find_first_not_of(k_valid_command_chars);
1312 if (pos > 0 && pos != std::string::npos) {
1313 suffix.assign(command.begin() + pos, command.end());
1314 command.erase(pos);
1315 }
1316 }
1317 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001318
Kate Stoneb9c1b512016-09-06 20:57:50 +00001319 return result;
1320}
1321
1322CommandObject *CommandInterpreter::BuildAliasResult(
Zachary Turnera483f572016-10-05 21:14:49 +00001323 llvm::StringRef alias_name, std::string &raw_input_string,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001324 std::string &alias_result, CommandReturnObject &result) {
1325 CommandObject *alias_cmd_obj = nullptr;
1326 Args cmd_args(raw_input_string);
1327 alias_cmd_obj = GetCommandObject(alias_name);
1328 StreamString result_str;
1329
Zachary Turner5c28c662016-10-03 23:20:36 +00001330 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1331 alias_result.clear();
1332 return alias_cmd_obj;
1333 }
1334 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1335 ((CommandAlias *)alias_cmd_obj)->Desugar();
1336 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1337 alias_cmd_obj = desugared.first.get();
1338 std::string alias_name_str = alias_name;
1339 if ((cmd_args.GetArgumentCount() == 0) ||
1340 (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0))
1341 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001342
Zachary Turnera4496982016-10-05 21:14:38 +00001343 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344
Zachary Turner5c28c662016-10-03 23:20:36 +00001345 if (!option_arg_vector_sp.get()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001346 alias_result = result_str.GetString();
Zachary Turner5c28c662016-10-03 23:20:36 +00001347 return alias_cmd_obj;
1348 }
1349 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001350
Zachary Turner5c28c662016-10-03 23:20:36 +00001351 int value_type;
1352 std::string option;
1353 std::string value;
1354 for (const auto &entry : *option_arg_vector) {
1355 std::tie(option, value_type, value) = entry;
1356 if (option == "<argument>") {
1357 result_str.Printf(" %s", value.c_str());
1358 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001359 }
1360
Zachary Turner5c28c662016-10-03 23:20:36 +00001361 result_str.Printf(" %s", option.c_str());
1362 if (value_type == OptionParser::eNoArgument)
1363 continue;
1364
1365 if (value_type != OptionParser::eOptionalArgument)
1366 result_str.Printf(" ");
1367 int index = GetOptionArgumentPosition(value.c_str());
1368 if (index == 0)
1369 result_str.Printf("%s", value.c_str());
1370 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1371
1372 result.AppendErrorWithFormat("Not enough arguments provided; you "
1373 "need at least %d arguments to use "
1374 "this alias.\n",
1375 index);
1376 result.SetStatus(eReturnStatusFailed);
1377 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001378 } else {
1379 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1380 if (strpos != std::string::npos)
1381 raw_input_string = raw_input_string.erase(
1382 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1383 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001384 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001385 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001386
Zachary Turnerc1564272016-11-16 21:15:24 +00001387 alias_result = result_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001388 return alias_cmd_obj;
1389}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001390
Zachary Turner97206d52017-05-12 04:51:55 +00001391Status CommandInterpreter::PreprocessCommand(std::string &command) {
Adrian Prantl05097242018-04-30 16:49:04 +00001392 // The command preprocessor needs to do things to the command line before any
1393 // parsing of arguments or anything else is done. The only current stuff that
1394 // gets preprocessed is anything enclosed in backtick ('`') characters is
1395 // evaluated as an expression and the result of the expression must be a
1396 // scalar that can be substituted into the command. An example would be:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397 // (lldb) memory read `$rsp + 20`
Zachary Turner97206d52017-05-12 04:51:55 +00001398 Status error; // Status for any expressions that might not evaluate
Kate Stoneb9c1b512016-09-06 20:57:50 +00001399 size_t start_backtick;
1400 size_t pos = 0;
1401 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1402 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
Adrian Prantl05097242018-04-30 16:49:04 +00001403 // The backtick was preceded by a '\' character, remove the slash and
1404 // don't treat the backtick as the start of an expression
Kate Stoneb9c1b512016-09-06 20:57:50 +00001405 command.erase(start_backtick - 1, 1);
1406 // No need to add one to start_backtick since we just deleted a char
1407 pos = start_backtick;
1408 } else {
1409 const size_t expr_content_start = start_backtick + 1;
1410 const size_t end_backtick = command.find('`', expr_content_start);
1411 if (end_backtick == std::string::npos)
1412 return error;
1413 else if (end_backtick == expr_content_start) {
1414 // Empty expression (two backticks in a row)
1415 command.erase(start_backtick, 2);
1416 } else {
1417 std::string expr_str(command, expr_content_start,
1418 end_backtick - expr_content_start);
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001419
Kate Stoneb9c1b512016-09-06 20:57:50 +00001420 ExecutionContext exe_ctx(GetExecutionContext());
1421 Target *target = exe_ctx.GetTargetPtr();
1422 // Get a dummy target to allow for calculator mode while processing
Adrian Prantl05097242018-04-30 16:49:04 +00001423 // backticks. This also helps break the infinite loop caused when
1424 // target is null.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001425 if (!target)
1426 target = m_debugger.GetDummyTarget();
1427 if (target) {
1428 ValueObjectSP expr_result_valobj_sp;
1429
1430 EvaluateExpressionOptions options;
1431 options.SetCoerceToId(false);
1432 options.SetUnwindOnError(true);
1433 options.SetIgnoreBreakpoints(true);
1434 options.SetKeepInMemory(false);
1435 options.SetTryAllThreads(true);
Pavel Labath43d35412016-12-06 11:24:51 +00001436 options.SetTimeout(llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001437
1438 ExpressionResults expr_result = target->EvaluateExpression(
1439 expr_str.c_str(), exe_ctx.GetFramePtr(), expr_result_valobj_sp,
1440 options);
1441
1442 if (expr_result == eExpressionCompleted) {
1443 Scalar scalar;
1444 if (expr_result_valobj_sp)
1445 expr_result_valobj_sp =
1446 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1447 expr_result_valobj_sp->GetDynamicValueType(), true);
1448 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1449 command.erase(start_backtick, end_backtick - start_backtick + 1);
1450 StreamString value_strm;
1451 const bool show_type = false;
1452 scalar.GetValue(&value_strm, show_type);
1453 size_t value_string_size = value_strm.GetSize();
1454 if (value_string_size) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001455 command.insert(start_backtick, value_strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001456 pos = start_backtick + value_string_size;
1457 continue;
1458 } else {
1459 error.SetErrorStringWithFormat("expression value didn't result "
1460 "in a scalar value for the "
1461 "expression '%s'",
1462 expr_str.c_str());
1463 }
1464 } else {
1465 error.SetErrorStringWithFormat("expression value didn't result "
1466 "in a scalar value for the "
1467 "expression '%s'",
1468 expr_str.c_str());
1469 }
1470 } else {
1471 if (expr_result_valobj_sp)
1472 error = expr_result_valobj_sp->GetError();
1473 if (error.Success()) {
1474
1475 switch (expr_result) {
1476 case eExpressionSetupError:
1477 error.SetErrorStringWithFormat(
1478 "expression setup error for the expression '%s'",
1479 expr_str.c_str());
1480 break;
1481 case eExpressionParseError:
1482 error.SetErrorStringWithFormat(
1483 "expression parse error for the expression '%s'",
1484 expr_str.c_str());
1485 break;
1486 case eExpressionResultUnavailable:
1487 error.SetErrorStringWithFormat(
1488 "expression error fetching result for the expression '%s'",
1489 expr_str.c_str());
1490 break;
1491 case eExpressionCompleted:
1492 break;
1493 case eExpressionDiscarded:
1494 error.SetErrorStringWithFormat(
1495 "expression discarded for the expression '%s'",
1496 expr_str.c_str());
1497 break;
1498 case eExpressionInterrupted:
1499 error.SetErrorStringWithFormat(
1500 "expression interrupted for the expression '%s'",
1501 expr_str.c_str());
1502 break;
1503 case eExpressionHitBreakpoint:
1504 error.SetErrorStringWithFormat(
1505 "expression hit breakpoint for the expression '%s'",
1506 expr_str.c_str());
1507 break;
1508 case eExpressionTimedOut:
1509 error.SetErrorStringWithFormat(
1510 "expression timed out for the expression '%s'",
1511 expr_str.c_str());
1512 break;
1513 case eExpressionStoppedForDebug:
1514 error.SetErrorStringWithFormat("expression stop at entry point "
1515 "for debugging for the "
1516 "expression '%s'",
1517 expr_str.c_str());
1518 break;
1519 }
1520 }
1521 }
1522 }
1523 }
1524 if (error.Fail())
1525 break;
1526 }
1527 }
1528 return error;
1529}
1530
1531bool CommandInterpreter::HandleCommand(const char *command_line,
1532 LazyBool lazy_add_to_history,
1533 CommandReturnObject &result,
1534 ExecutionContext *override_context,
1535 bool repeat_on_empty_command,
1536 bool no_context_switching)
1537
1538{
1539
1540 std::string command_string(command_line);
1541 std::string original_command_string(command_line);
1542
1543 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
Jim Ingham8f7db522016-12-15 00:30:30 +00001544 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
Sean Callanan237c3ed2016-12-14 21:31:31 +00001545 command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001546
1547 if (log)
1548 log->Printf("Processing command: %s", command_line);
1549
Pavel Labathf9d16472017-05-15 13:02:37 +00001550 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1551 Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001552
1553 if (!no_context_switching)
1554 UpdateExecutionContext(override_context);
1555
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001556 if (WasInterrupted()) {
1557 result.AppendError("interrupted");
1558 result.SetStatus(eReturnStatusFailed);
1559 return false;
1560 }
1561
Kate Stoneb9c1b512016-09-06 20:57:50 +00001562 bool add_to_history;
1563 if (lazy_add_to_history == eLazyBoolCalculate)
1564 add_to_history = (m_command_source_depth == 0);
1565 else
1566 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1567
1568 bool empty_command = false;
1569 bool comment_command = false;
1570 if (command_string.empty())
1571 empty_command = true;
1572 else {
1573 const char *k_space_characters = "\t\n\v\f\r ";
1574
1575 size_t non_space = command_string.find_first_not_of(k_space_characters);
Adrian Prantl05097242018-04-30 16:49:04 +00001576 // Check for empty line or comment line (lines whose first non-space
1577 // character is the comment character for this interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001578 if (non_space == std::string::npos)
1579 empty_command = true;
1580 else if (command_string[non_space] == m_comment_char)
1581 comment_command = true;
1582 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001583 llvm::StringRef search_str(command_string);
1584 search_str = search_str.drop_front(non_space);
1585 if (auto hist_str = m_command_history.FindString(search_str)) {
1586 add_to_history = false;
1587 command_string = *hist_str;
1588 original_command_string = *hist_str;
1589 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001590 result.AppendErrorWithFormat("Could not find entry: %s in history",
1591 command_string.c_str());
1592 result.SetStatus(eReturnStatusFailed);
1593 return false;
1594 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001595 }
1596 }
1597
1598 if (empty_command) {
1599 if (repeat_on_empty_command) {
1600 if (m_command_history.IsEmpty()) {
1601 result.AppendError("empty command");
1602 result.SetStatus(eReturnStatusFailed);
1603 return false;
1604 } else {
1605 command_line = m_repeat_command.c_str();
1606 command_string = command_line;
1607 original_command_string = command_line;
1608 if (m_repeat_command.empty()) {
1609 result.AppendErrorWithFormat("No auto repeat.\n");
1610 result.SetStatus(eReturnStatusFailed);
1611 return false;
1612 }
1613 }
1614 add_to_history = false;
1615 } else {
1616 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1617 return true;
1618 }
1619 } else if (comment_command) {
1620 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1621 return true;
1622 }
1623
Zachary Turner97206d52017-05-12 04:51:55 +00001624 Status error(PreprocessCommand(command_string));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001625
1626 if (error.Fail()) {
1627 result.AppendError(error.AsCString());
1628 result.SetStatus(eReturnStatusFailed);
1629 return false;
1630 }
1631
1632 // Phase 1.
1633
1634 // Before we do ANY kind of argument processing, we need to figure out what
1635 // the real/final command object is for the specified command. This gets
1636 // complicated by the fact that the user could have specified an alias, and,
1637 // in translating the alias, there may also be command options and/or even
1638 // data (including raw text strings) that need to be found and inserted into
1639 // the command line as part of the translation. So this first step is plain
1640 // look-up and replacement, resulting in:
1641 // 1. the command object whose Execute method will actually be called
1642 // 2. a revised command string, with all substitutions and replacements
1643 // taken care of
1644 // From 1 above, we can determine whether the Execute function wants raw
1645 // input or not.
1646
1647 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1648
1649 // Although the user may have abbreviated the command, the command_string now
Adrian Prantl05097242018-04-30 16:49:04 +00001650 // has the command expanded to the full name. For example, if the input was
1651 // "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001652 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001653 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1654 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001655 log->Printf("HandleCommand, (revised) command_string: '%s'",
1656 command_string.c_str());
1657 const bool wants_raw_input =
1658 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1659 log->Printf("HandleCommand, wants_raw_input:'%s'",
1660 wants_raw_input ? "True" : "False");
1661 }
1662
1663 // Phase 2.
1664 // Take care of things like setting up the history command & calling the
Adrian Prantl05097242018-04-30 16:49:04 +00001665 // appropriate Execute method on the CommandObject, with the appropriate
1666 // arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001667
1668 if (cmd_obj != nullptr) {
1669 if (add_to_history) {
1670 Args command_args(command_string);
1671 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1672 if (repeat_command != nullptr)
1673 m_repeat_command.assign(repeat_command);
1674 else
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001675 m_repeat_command.assign(original_command_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001676
1677 m_command_history.AppendString(original_command_string);
1678 }
1679
1680 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001681 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001682 if (actual_cmd_name_len < command_string.length())
1683 remainder = command_string.substr(actual_cmd_name_len);
1684
1685 // Remove any initial spaces
1686 size_t pos = remainder.find_first_not_of(k_white_space);
1687 if (pos != 0 && pos != std::string::npos)
1688 remainder.erase(0, pos);
1689
1690 if (log)
1691 log->Printf(
1692 "HandleCommand, command line after removing command name(s): '%s'",
1693 remainder.c_str());
1694
1695 cmd_obj->Execute(remainder.c_str(), result);
1696 } else {
1697 // We didn't find the first command object, so complete the first argument.
1698 Args command_args(command_string);
1699 StringList matches;
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001700 unsigned cursor_char_position = strlen(command_args.GetArgumentAtIndex(0));
1701 CompletionRequest request(command_line, cursor_char_position, 0, -1,
1702 matches);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001703 int num_matches = HandleCompletionMatches(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001704
1705 if (num_matches > 0) {
1706 std::string error_msg;
1707 error_msg.assign("ambiguous command '");
1708 error_msg.append(command_args.GetArgumentAtIndex(0));
1709 error_msg.append("'.");
1710
1711 error_msg.append(" Possible completions:");
1712 for (int i = 0; i < num_matches; i++) {
1713 error_msg.append("\n\t");
1714 error_msg.append(matches.GetStringAtIndex(i));
1715 }
1716 error_msg.append("\n");
1717 result.AppendRawError(error_msg.c_str());
1718 } else
1719 result.AppendErrorWithFormat("Unrecognized command '%s'.\n",
1720 command_args.GetArgumentAtIndex(0));
1721
1722 result.SetStatus(eReturnStatusFailed);
1723 }
1724
1725 if (log)
1726 log->Printf("HandleCommand, command %s",
1727 (result.Succeeded() ? "succeeded" : "did not succeed"));
1728
1729 return result.Succeeded();
1730}
1731
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001732int CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
1733 auto &matches = request.GetMatches();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001734 int num_command_matches = 0;
1735 bool look_for_subcommand = false;
1736
1737 // For any of the command completions a unique match will be a complete word.
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001738 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001739
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001740 if (request.GetCursorIndex() == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001741 // We got nothing on the command line, so return the list of commands
1742 bool include_aliases = true;
1743 num_command_matches =
1744 GetCommandNamesMatchingPartialString("", include_aliases, matches);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001745 } else if (request.GetCursorIndex() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001746 // The cursor is in the first argument, so just do a lookup in the
1747 // dictionary.
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001748 CommandObject *cmd_obj = GetCommandObject(
1749 request.GetParsedLine().GetArgumentAtIndex(0), &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001750 num_command_matches = matches.GetSize();
1751
1752 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
1753 matches.GetStringAtIndex(0) != nullptr &&
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001754 strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001755 matches.GetStringAtIndex(0)) == 0) {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001756 if (request.GetParsedLine().GetArgumentCount() == 1) {
1757 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001758 } else {
1759 look_for_subcommand = true;
1760 num_command_matches = 0;
1761 matches.DeleteStringAtIndex(0);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001762 request.GetParsedLine().AppendArgument(llvm::StringRef());
1763 request.SetCursorIndex(request.GetCursorIndex() + 1);
1764 request.SetCursorCharPosition(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001765 }
1766 }
1767 }
1768
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001769 if (request.GetCursorIndex() > 0 || look_for_subcommand) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001770 // We are completing further on into a commands arguments, so find the
Adrian Prantl05097242018-04-30 16:49:04 +00001771 // command and tell it to complete the command. First see if there is a
1772 // matching initial command:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001773 CommandObject *command_object =
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001774 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001775 if (command_object == nullptr) {
1776 return 0;
1777 } else {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001778 request.GetParsedLine().Shift();
1779 request.SetCursorIndex(request.GetCursorIndex() - 1);
1780 num_command_matches = command_object->HandleCompletion(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001781 }
1782 }
1783
1784 return num_command_matches;
1785}
1786
1787int CommandInterpreter::HandleCompletion(
1788 const char *current_line, const char *cursor, const char *last_char,
1789 int match_start_point, int max_return_elements, StringList &matches) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001790
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001791 llvm::StringRef command_line(current_line, last_char - current_line);
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001792 CompletionRequest request(command_line, cursor - current_line,
1793 match_start_point, max_return_elements, matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001794
1795 // Don't complete comments, and if the line we are completing is just the
Adrian Prantl05097242018-04-30 16:49:04 +00001796 // history repeat character, substitute the appropriate history line.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001797 const char *first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001798 if (first_arg) {
1799 if (first_arg[0] == m_comment_char)
1800 return 0;
1801 else if (first_arg[0] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001802 if (auto hist_str = m_command_history.FindString(first_arg)) {
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001803 request.GetMatches().Clear();
1804 request.GetMatches().InsertStringAtIndex(0, *hist_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001805 return -2;
1806 } else
1807 return 0;
1808 }
1809 }
1810
Kate Stoneb9c1b512016-09-06 20:57:50 +00001811 // Only max_return_elements == -1 is supported at present:
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001812 lldbassert(max_return_elements == -1);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001813
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001814 int num_command_matches = HandleCompletionMatches(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001815
1816 if (num_command_matches <= 0)
1817 return num_command_matches;
1818
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001819 if (request.GetParsedLine().GetArgumentCount() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001820 // If we got an empty string, insert nothing.
1821 matches.InsertStringAtIndex(0, "");
1822 } else {
1823 // Now figure out if there is a common substring, and if so put that in
Adrian Prantl05097242018-04-30 16:49:04 +00001824 // element 0, otherwise put an empty string in element 0.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001825 std::string command_partial_str = request.GetCursorArgumentPrefix().str();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001826
1827 std::string common_prefix;
1828 matches.LongestCommonPrefix(common_prefix);
1829 const size_t partial_name_len = command_partial_str.size();
1830 common_prefix.erase(0, partial_name_len);
1831
Adrian Prantl05097242018-04-30 16:49:04 +00001832 // If we matched a unique single command, add a space... Only do this if
1833 // the completer told us this was a complete word, however...
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001834 if (num_command_matches == 1 && request.GetWordComplete()) {
1835 char quote_char = request.GetParsedLine()[request.GetCursorIndex()].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001836 common_prefix =
1837 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1838 if (quote_char != '\0')
1839 common_prefix.push_back(quote_char);
1840 common_prefix.push_back(' ');
1841 }
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001842 request.GetMatches().InsertStringAtIndex(0, common_prefix.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001843 }
1844 return num_command_matches;
1845}
1846
1847CommandInterpreter::~CommandInterpreter() {}
1848
Zachary Turner514d8cd2016-09-23 18:06:53 +00001849void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001850 EventSP prompt_change_event_sp(
1851 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1852 ;
1853 BroadcastEvent(prompt_change_event_sp);
1854 if (m_command_io_handler_sp)
1855 m_command_io_handler_sp->SetPrompt(new_prompt);
1856}
1857
Zachary Turner7a120c82016-11-13 03:05:58 +00001858bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001859 // Check AutoConfirm first:
1860 if (m_debugger.GetAutoConfirm())
1861 return default_answer;
1862
1863 IOHandlerConfirm *confirm =
1864 new IOHandlerConfirm(m_debugger, message, default_answer);
1865 IOHandlerSP io_handler_sp(confirm);
1866 m_debugger.RunIOHandler(io_handler_sp);
1867 return confirm->GetResponse();
1868}
1869
Zachary Turnera483f572016-10-05 21:14:49 +00001870const CommandAlias *
1871CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001872 OptionArgVectorSP ret_val;
1873
Zachary Turnera483f572016-10-05 21:14:49 +00001874 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001875 if (pos != m_alias_dict.end())
1876 return (CommandAlias *)pos->second.get();
1877
1878 return nullptr;
1879}
1880
Zachary Turnera4496982016-10-05 21:14:38 +00001881bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001882
Zachary Turnera4496982016-10-05 21:14:38 +00001883bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001884
Zachary Turnera4496982016-10-05 21:14:38 +00001885bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001886
Zachary Turnera4496982016-10-05 21:14:38 +00001887bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001888
1889void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1890 const char *alias_name,
1891 Args &cmd_args,
1892 std::string &raw_input_string,
1893 CommandReturnObject &result) {
1894 OptionArgVectorSP option_arg_vector_sp =
1895 GetAlias(alias_name)->GetOptionArguments();
1896
1897 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1898
1899 // Make sure that the alias name is the 0th element in cmd_args
1900 std::string alias_name_str = alias_name;
1901 if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)
Zachary Turner5c725f32016-09-19 21:56:59 +00001902 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001903
1904 Args new_args(alias_cmd_obj->GetCommandName());
1905 if (new_args.GetArgumentCount() == 2)
1906 new_args.Shift();
1907
1908 if (option_arg_vector_sp.get()) {
1909 if (wants_raw_input) {
1910 // We have a command that both has command options and takes raw input.
Adrian Prantl05097242018-04-30 16:49:04 +00001911 // Make *sure* it has a " -- " in the right place in the
1912 // raw_input_string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001913 size_t pos = raw_input_string.find(" -- ");
1914 if (pos == std::string::npos) {
1915 // None found; assume it goes at the beginning of the raw input string
1916 raw_input_string.insert(0, " -- ");
1917 }
1918 }
1919
1920 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1921 const size_t old_size = cmd_args.GetArgumentCount();
1922 std::vector<bool> used(old_size + 1, false);
1923
1924 used[0] = true;
1925
Zachary Turner5c28c662016-10-03 23:20:36 +00001926 int value_type;
1927 std::string option;
1928 std::string value;
1929 for (const auto &option_entry : *option_arg_vector) {
1930 std::tie(option, value_type, value) = option_entry;
1931 if (option == "<argument>") {
1932 if (!wants_raw_input || (value != "--")) {
1933 // Since we inserted this above, make sure we don't insert it twice
1934 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001935 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001936 continue;
1937 }
1938
1939 if (value_type != OptionParser::eOptionalArgument)
1940 new_args.AppendArgument(option);
1941
1942 if (value == "<no-argument>")
1943 continue;
1944
1945 int index = GetOptionArgumentPosition(value.c_str());
1946 if (index == 0) {
1947 // value was NOT a positional argument; must be a real value
1948 if (value_type != OptionParser::eOptionalArgument)
1949 new_args.AppendArgument(value);
1950 else {
1951 char buffer[255];
1952 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1953 value.c_str());
1954 new_args.AppendArgument(llvm::StringRef(buffer));
1955 }
1956
1957 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1958 result.AppendErrorWithFormat("Not enough arguments provided; you "
1959 "need at least %d arguments to use "
1960 "this alias.\n",
1961 index);
1962 result.SetStatus(eReturnStatusFailed);
1963 return;
1964 } else {
1965 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1966 size_t strpos =
1967 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1968 if (strpos != std::string::npos) {
1969 raw_input_string = raw_input_string.erase(
1970 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1971 }
1972
1973 if (value_type != OptionParser::eOptionalArgument)
1974 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
1975 else {
1976 char buffer[255];
1977 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1978 cmd_args.GetArgumentAtIndex(index));
1979 new_args.AppendArgument(buffer);
1980 }
1981 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001982 }
1983 }
1984
Zachary Turner97d2c402016-10-05 23:40:23 +00001985 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00001986 if (!used[entry.index()] && !wants_raw_input)
1987 new_args.AppendArgument(entry.value().ref);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001988 }
1989
1990 cmd_args.Clear();
1991 cmd_args.SetArguments(new_args.GetArgumentCount(),
1992 new_args.GetConstArgumentVector());
1993 } else {
1994 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1995 // This alias was not created with any options; nothing further needs to be
Adrian Prantl05097242018-04-30 16:49:04 +00001996 // done, unless it is a command that wants raw input, in which case we need
1997 // to clear the rest of the data from cmd_args, since its in the raw input
1998 // string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001999 if (wants_raw_input) {
2000 cmd_args.Clear();
2001 cmd_args.SetArguments(new_args.GetArgumentCount(),
2002 new_args.GetConstArgumentVector());
2003 }
2004 return;
2005 }
2006
2007 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2008 return;
2009}
2010
2011int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2012 int position = 0; // Any string that isn't an argument position, i.e. '%'
2013 // followed by an integer, gets a position
2014 // of zero.
2015
2016 const char *cptr = in_string;
2017
2018 // Does it start with '%'
2019 if (cptr[0] == '%') {
2020 ++cptr;
2021
2022 // Is the rest of it entirely digits?
2023 if (isdigit(cptr[0])) {
2024 const char *start = cptr;
2025 while (isdigit(cptr[0]))
2026 ++cptr;
2027
Adrian Prantl05097242018-04-30 16:49:04 +00002028 // We've gotten to the end of the digits; are we at the end of the
2029 // string?
Kate Stoneb9c1b512016-09-06 20:57:50 +00002030 if (cptr[0] == '\0')
2031 position = atoi(start);
2032 }
2033 }
2034
2035 return position;
2036}
2037
2038void CommandInterpreter::SourceInitFile(bool in_cwd,
2039 CommandReturnObject &result) {
2040 FileSpec init_file;
2041 if (in_cwd) {
2042 ExecutionContext exe_ctx(GetExecutionContext());
2043 Target *target = exe_ctx.GetTargetPtr();
2044 if (target) {
2045 // In the current working directory we don't load any program specific
2046 // .lldbinit files, we only look for a ".lldbinit" file.
2047 if (m_skip_lldbinit_files)
2048 return;
2049
2050 LoadCWDlldbinitFile should_load =
2051 target->TargetProperties::GetLoadCWDlldbinitFile();
2052 if (should_load == eLoadCWDlldbinitWarn) {
2053 FileSpec dot_lldb(".lldbinit", true);
2054 llvm::SmallString<64> home_dir_path;
2055 llvm::sys::path::home_directory(home_dir_path);
2056 FileSpec homedir_dot_lldb(home_dir_path.c_str(), false);
2057 homedir_dot_lldb.AppendPathComponent(".lldbinit");
2058 homedir_dot_lldb.ResolvePath();
2059 if (dot_lldb.Exists() &&
2060 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2061 result.AppendErrorWithFormat(
2062 "There is a .lldbinit file in the current directory which is not "
2063 "being read.\n"
2064 "To silence this warning without sourcing in the local "
2065 ".lldbinit,\n"
2066 "add the following to the lldbinit file in your home directory:\n"
2067 " settings set target.load-cwd-lldbinit false\n"
2068 "To allow lldb to source .lldbinit files in the current working "
2069 "directory,\n"
2070 "set the value of this variable to true. Only do so if you "
2071 "understand and\n"
2072 "accept the security risk.");
2073 result.SetStatus(eReturnStatusFailed);
2074 return;
2075 }
2076 } else if (should_load == eLoadCWDlldbinitTrue) {
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002077 init_file.SetFile("./.lldbinit", true, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002078 }
2079 }
2080 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002081 // If we aren't looking in the current working directory we are looking in
2082 // the home directory. We will first see if there is an application
2083 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a "-"
2084 // and the name of the program. If this file doesn't exist, we fall back to
2085 // just the "~/.lldbinit" file. We also obey any requests to not load the
2086 // init files.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002087 llvm::SmallString<64> home_dir_path;
2088 llvm::sys::path::home_directory(home_dir_path);
2089 FileSpec profilePath(home_dir_path.c_str(), false);
2090 profilePath.AppendPathComponent(".lldbinit");
2091 std::string init_file_path = profilePath.GetPath();
2092
2093 if (m_skip_app_init_files == false) {
2094 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2095 const char *program_name = program_file_spec.GetFilename().AsCString();
2096
2097 if (program_name) {
2098 char program_init_file_name[PATH_MAX];
2099 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2100 "%s-%s", init_file_path.c_str(), program_name);
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002101 init_file.SetFile(program_init_file_name, true,
2102 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002103 if (!init_file.Exists())
2104 init_file.Clear();
2105 }
2106 }
2107
2108 if (!init_file && !m_skip_lldbinit_files)
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002109 init_file.SetFile(init_file_path, false, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002110 }
2111
2112 // If the file exists, tell HandleCommand to 'source' it; this will do the
Adrian Prantl05097242018-04-30 16:49:04 +00002113 // actual broadcasting of the commands back to any appropriate listener (see
Kate Stoneb9c1b512016-09-06 20:57:50 +00002114 // CommandObjectSource::Execute for more details).
2115
2116 if (init_file.Exists()) {
2117 const bool saved_batch = SetBatchCommandMode(true);
2118 CommandInterpreterRunOptions options;
2119 options.SetSilent(true);
2120 options.SetStopOnError(false);
2121 options.SetStopOnContinue(true);
2122
2123 HandleCommandsFromFile(init_file,
2124 nullptr, // Execution context
2125 options, result);
2126 SetBatchCommandMode(saved_batch);
2127 } else {
2128 // nothing to be done if the file doesn't exist
2129 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2130 }
2131}
2132
2133const char *CommandInterpreter::GetCommandPrefix() {
2134 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2135 return prefix == NULL ? "" : prefix;
2136}
2137
2138PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2139 PlatformSP platform_sp;
2140 if (prefer_target_platform) {
2141 ExecutionContext exe_ctx(GetExecutionContext());
2142 Target *target = exe_ctx.GetTargetPtr();
2143 if (target)
2144 platform_sp = target->GetPlatform();
2145 }
2146
2147 if (!platform_sp)
2148 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2149 return platform_sp;
2150}
2151
2152void CommandInterpreter::HandleCommands(const StringList &commands,
2153 ExecutionContext *override_context,
2154 CommandInterpreterRunOptions &options,
2155 CommandReturnObject &result) {
2156 size_t num_lines = commands.GetSize();
2157
2158 // If we are going to continue past a "continue" then we need to run the
Adrian Prantl05097242018-04-30 16:49:04 +00002159 // commands synchronously. Make sure you reset this value anywhere you return
2160 // from the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002161
2162 bool old_async_execution = m_debugger.GetAsyncExecution();
2163
2164 // If we've been given an execution context, set it at the start, but don't
Adrian Prantl05097242018-04-30 16:49:04 +00002165 // keep resetting it or we will cause series of commands that change the
2166 // context, then do an operation that relies on that context to fail.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002167
2168 if (override_context != nullptr)
2169 UpdateExecutionContext(override_context);
2170
2171 if (!options.GetStopOnContinue()) {
2172 m_debugger.SetAsyncExecution(false);
2173 }
2174
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002175 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002176 const char *cmd = commands.GetStringAtIndex(idx);
2177 if (cmd[0] == '\0')
2178 continue;
2179
2180 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002181 // TODO: Add Stream support.
2182 result.AppendMessageWithFormat("%s %s\n",
2183 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002184 }
2185
2186 CommandReturnObject tmp_result;
2187 // If override_context is not NULL, pass no_context_switching = true for
2188 // HandleCommand() since we updated our context already.
2189
2190 // We might call into a regex or alias command, in which case the
Adrian Prantl05097242018-04-30 16:49:04 +00002191 // add_to_history will get lost. This m_command_source_depth dingus is the
2192 // way we turn off adding to the history in that case, so set it up here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002193 if (!options.GetAddToHistory())
2194 m_command_source_depth++;
2195 bool success =
2196 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2197 nullptr, /* override_context */
2198 true, /* repeat_on_empty_command */
2199 override_context != nullptr /* no_context_switching */);
2200 if (!options.GetAddToHistory())
2201 m_command_source_depth--;
2202
2203 if (options.GetPrintResults()) {
2204 if (tmp_result.Succeeded())
Zachary Turner03c9f362016-11-14 23:23:31 +00002205 result.AppendMessage(tmp_result.GetOutputData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002206 }
2207
2208 if (!success || !tmp_result.Succeeded()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002209 llvm::StringRef error_msg = tmp_result.GetErrorData();
2210 if (error_msg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002211 error_msg = "<unknown error>.\n";
2212 if (options.GetStopOnError()) {
2213 result.AppendErrorWithFormat(
2214 "Aborting reading of commands after command #%" PRIu64
2215 ": '%s' failed with %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00002216 (uint64_t)idx, cmd, error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002217 result.SetStatus(eReturnStatusFailed);
2218 m_debugger.SetAsyncExecution(old_async_execution);
2219 return;
2220 } else if (options.GetPrintResults()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002221 result.AppendMessageWithFormat(
2222 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2223 error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002224 }
2225 }
2226
2227 if (result.GetImmediateOutputStream())
2228 result.GetImmediateOutputStream()->Flush();
2229
2230 if (result.GetImmediateErrorStream())
2231 result.GetImmediateErrorStream()->Flush();
2232
Adrian Prantl05097242018-04-30 16:49:04 +00002233 // N.B. Can't depend on DidChangeProcessState, because the state coming
2234 // into the command execution could be running (for instance in Breakpoint
2235 // Commands. So we check the return value to see if it is has running in
2236 // it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002237 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2238 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2239 if (options.GetStopOnContinue()) {
2240 // If we caused the target to proceed, and we're going to stop in that
Adrian Prantl05097242018-04-30 16:49:04 +00002241 // case, set the status in our real result before returning. This is
2242 // an error if the continue was not the last command in the set of
2243 // commands to be run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002244 if (idx != num_lines - 1)
2245 result.AppendErrorWithFormat(
2246 "Aborting reading of commands after command #%" PRIu64
2247 ": '%s' continued the target.\n",
2248 (uint64_t)idx + 1, cmd);
2249 else
2250 result.AppendMessageWithFormat("Command #%" PRIu64
2251 " '%s' continued the target.\n",
2252 (uint64_t)idx + 1, cmd);
2253
2254 result.SetStatus(tmp_result.GetStatus());
2255 m_debugger.SetAsyncExecution(old_async_execution);
2256
2257 return;
2258 }
2259 }
2260
2261 // Also check for "stop on crash here:
2262 bool should_stop = false;
2263 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2264 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2265 if (target_sp) {
2266 ProcessSP process_sp(target_sp->GetProcessSP());
2267 if (process_sp) {
2268 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2269 StopReason reason = thread_sp->GetStopReason();
2270 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2271 reason == eStopReasonInstrumentation) {
2272 should_stop = true;
2273 break;
2274 }
2275 }
2276 }
2277 }
2278 if (should_stop) {
2279 if (idx != num_lines - 1)
2280 result.AppendErrorWithFormat(
2281 "Aborting reading of commands after command #%" PRIu64
2282 ": '%s' stopped with a signal or exception.\n",
2283 (uint64_t)idx + 1, cmd);
2284 else
2285 result.AppendMessageWithFormat(
2286 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2287 (uint64_t)idx + 1, cmd);
2288
2289 result.SetStatus(tmp_result.GetStatus());
2290 m_debugger.SetAsyncExecution(old_async_execution);
2291
2292 return;
2293 }
2294 }
2295 }
2296
2297 result.SetStatus(eReturnStatusSuccessFinishResult);
2298 m_debugger.SetAsyncExecution(old_async_execution);
2299
2300 return;
2301}
2302
2303// Make flags that we can pass into the IOHandler so our delegates can do the
2304// right thing
2305enum {
2306 eHandleCommandFlagStopOnContinue = (1u << 0),
2307 eHandleCommandFlagStopOnError = (1u << 1),
2308 eHandleCommandFlagEchoCommand = (1u << 2),
2309 eHandleCommandFlagPrintResult = (1u << 3),
2310 eHandleCommandFlagStopOnCrash = (1u << 4)
2311};
2312
2313void CommandInterpreter::HandleCommandsFromFile(
2314 FileSpec &cmd_file, ExecutionContext *context,
2315 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2316 if (cmd_file.Exists()) {
2317 StreamFileSP input_file_sp(new StreamFile());
2318
2319 std::string cmd_file_path = cmd_file.GetPath();
Zachary Turner97206d52017-05-12 04:51:55 +00002320 Status error = input_file_sp->GetFile().Open(cmd_file_path.c_str(),
2321 File::eOpenOptionRead);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002322
2323 if (error.Success()) {
2324 Debugger &debugger = GetDebugger();
2325
2326 uint32_t flags = 0;
2327
2328 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2329 if (m_command_source_flags.empty()) {
2330 // Stop on continue by default
2331 flags |= eHandleCommandFlagStopOnContinue;
2332 } else if (m_command_source_flags.back() &
2333 eHandleCommandFlagStopOnContinue) {
2334 flags |= eHandleCommandFlagStopOnContinue;
2335 }
2336 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2337 flags |= eHandleCommandFlagStopOnContinue;
2338 }
2339
2340 if (options.m_stop_on_error == eLazyBoolCalculate) {
2341 if (m_command_source_flags.empty()) {
2342 if (GetStopCmdSourceOnError())
2343 flags |= eHandleCommandFlagStopOnError;
2344 } else if (m_command_source_flags.back() &
2345 eHandleCommandFlagStopOnError) {
2346 flags |= eHandleCommandFlagStopOnError;
2347 }
2348 } else if (options.m_stop_on_error == eLazyBoolYes) {
2349 flags |= eHandleCommandFlagStopOnError;
2350 }
2351
2352 if (options.GetStopOnCrash()) {
2353 if (m_command_source_flags.empty()) {
2354 // Echo command by default
2355 flags |= eHandleCommandFlagStopOnCrash;
2356 } else if (m_command_source_flags.back() &
2357 eHandleCommandFlagStopOnCrash) {
2358 flags |= eHandleCommandFlagStopOnCrash;
2359 }
2360 }
2361
2362 if (options.m_echo_commands == eLazyBoolCalculate) {
2363 if (m_command_source_flags.empty()) {
2364 // Echo command by default
2365 flags |= eHandleCommandFlagEchoCommand;
2366 } else if (m_command_source_flags.back() &
2367 eHandleCommandFlagEchoCommand) {
2368 flags |= eHandleCommandFlagEchoCommand;
2369 }
2370 } else if (options.m_echo_commands == eLazyBoolYes) {
2371 flags |= eHandleCommandFlagEchoCommand;
2372 }
2373
2374 if (options.m_print_results == eLazyBoolCalculate) {
2375 if (m_command_source_flags.empty()) {
2376 // Print output by default
2377 flags |= eHandleCommandFlagPrintResult;
2378 } else if (m_command_source_flags.back() &
2379 eHandleCommandFlagPrintResult) {
2380 flags |= eHandleCommandFlagPrintResult;
2381 }
2382 } else if (options.m_print_results == eLazyBoolYes) {
2383 flags |= eHandleCommandFlagPrintResult;
2384 }
2385
2386 if (flags & eHandleCommandFlagPrintResult) {
2387 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2388 cmd_file_path.c_str());
2389 }
2390
Adrian Prantl05097242018-04-30 16:49:04 +00002391 // Used for inheriting the right settings when "command source" might
2392 // have nested "command source" commands
Kate Stoneb9c1b512016-09-06 20:57:50 +00002393 lldb::StreamFileSP empty_stream_sp;
2394 m_command_source_flags.push_back(flags);
2395 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2396 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2397 empty_stream_sp, // Pass in an empty stream so we inherit the top
2398 // input reader output stream
2399 empty_stream_sp, // Pass in an empty stream so we inherit the top
2400 // input reader error stream
2401 flags,
2402 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2403 // or written
Zachary Turner514d8cd2016-09-23 18:06:53 +00002404 debugger.GetPrompt(), llvm::StringRef(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00002405 false, // Not multi-line
2406 debugger.GetUseColor(), 0, *this));
2407 const bool old_async_execution = debugger.GetAsyncExecution();
2408
2409 // Set synchronous execution if we are not stopping on continue
2410 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2411 debugger.SetAsyncExecution(false);
2412
2413 m_command_source_depth++;
2414
2415 debugger.RunIOHandler(io_handler_sp);
2416 if (!m_command_source_flags.empty())
2417 m_command_source_flags.pop_back();
2418 m_command_source_depth--;
2419 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2420 debugger.SetAsyncExecution(old_async_execution);
2421 } else {
2422 result.AppendErrorWithFormat(
2423 "error: an error occurred read file '%s': %s\n",
2424 cmd_file_path.c_str(), error.AsCString());
2425 result.SetStatus(eReturnStatusFailed);
2426 }
2427
2428 } else {
2429 result.AppendErrorWithFormat(
2430 "Error reading commands from file %s - file not found.\n",
2431 cmd_file.GetFilename().AsCString("<Unknown>"));
2432 result.SetStatus(eReturnStatusFailed);
2433 return;
2434 }
2435}
2436
2437ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
Jim Ingham30bac792017-07-13 19:45:54 +00002438 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
Greg Clayton79040462016-12-09 01:21:14 +00002439 if (!m_script_interpreter_sp) {
2440 if (!can_create)
2441 return nullptr;
2442 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2443 m_script_interpreter_sp =
2444 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2445 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002446 return m_script_interpreter_sp.get();
2447}
2448
2449bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2450
2451void CommandInterpreter::SetSynchronous(bool value) {
2452 m_synchronous_execution = value;
2453}
2454
2455void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002456 llvm::StringRef prefix,
2457 llvm::StringRef help_text) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002458 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002459
Zachary Turner0ac5f982016-11-08 04:12:42 +00002460 size_t line_width_max = max_columns - prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002461 if (line_width_max < 16)
Zachary Turner0ac5f982016-11-08 04:12:42 +00002462 line_width_max = help_text.size() + prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002463
Zachary Turner0ac5f982016-11-08 04:12:42 +00002464 strm.IndentMore(prefix.size());
2465 bool prefixed_yet = false;
2466 while (!help_text.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002467 // Prefix the first line, indent subsequent lines to line up
Zachary Turner0ac5f982016-11-08 04:12:42 +00002468 if (!prefixed_yet) {
2469 strm << prefix;
2470 prefixed_yet = true;
2471 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002472 strm.Indent();
Zachary Turner0ac5f982016-11-08 04:12:42 +00002473
2474 // Never print more than the maximum on one line.
2475 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2476
2477 // Always break on an explicit newline.
2478 std::size_t first_newline = this_line.find_first_of("\n");
2479
2480 // Don't break on space/tab unless the text is too long to fit on one line.
2481 std::size_t last_space = llvm::StringRef::npos;
2482 if (this_line.size() != help_text.size())
2483 last_space = this_line.find_last_of(" \t");
2484
2485 // Break at whichever condition triggered first.
2486 this_line = this_line.substr(0, std::min(first_newline, last_space));
2487 strm.PutCString(this_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002488 strm.EOL();
2489
Zachary Turner0ac5f982016-11-08 04:12:42 +00002490 // Remove whitespace / newlines after breaking.
2491 help_text = help_text.drop_front(this_line.size()).ltrim();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002492 }
Zachary Turner0ac5f982016-11-08 04:12:42 +00002493 strm.IndentLess(prefix.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002494}
2495
2496void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002497 llvm::StringRef word_text,
2498 llvm::StringRef separator,
2499 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002500 size_t max_word_len) {
2501 StreamString prefix_stream;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002502 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2503 (int)separator.size(), separator.data());
Zachary Turnerc1564272016-11-16 21:15:24 +00002504 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2505}
2506
Zachary Turner0ac5f982016-11-08 04:12:42 +00002507void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2508 llvm::StringRef separator,
2509 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002510 uint32_t max_word_len) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00002511 int indent_size = max_word_len + separator.size() + 2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002512
2513 strm.IndentMore(indent_size);
2514
2515 StreamString text_strm;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002516 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2517 text_strm << separator << " " << help_text;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002518
2519 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2520
Zachary Turnerc1564272016-11-16 21:15:24 +00002521 llvm::StringRef text = text_strm.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002522
2523 uint32_t chars_left = max_columns;
2524
Davide Italianocf8a8292017-04-14 22:36:08 +00002525 auto nextWordLength = [](llvm::StringRef S) {
2526 size_t pos = S.find_first_of(' ');
2527 return pos == llvm::StringRef::npos ? S.size() : pos;
2528 };
2529
Zachary Turnerc1564272016-11-16 21:15:24 +00002530 while (!text.empty()) {
2531 if (text.front() == '\n' ||
Jim Inghama81bd7f2017-07-27 00:18:18 +00002532 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002533 strm.EOL();
2534 strm.Indent();
Zachary Turnerc1564272016-11-16 21:15:24 +00002535 chars_left = max_columns - indent_size;
2536 if (text.front() == '\n')
2537 text = text.drop_front();
2538 else
2539 text = text.ltrim(' ');
Kate Stoneb9c1b512016-09-06 20:57:50 +00002540 } else {
Zachary Turnerc1564272016-11-16 21:15:24 +00002541 strm.PutChar(text.front());
2542 --chars_left;
2543 text = text.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002544 }
2545 }
2546
2547 strm.EOL();
2548 strm.IndentLess(indent_size);
2549}
2550
2551void CommandInterpreter::FindCommandsForApropos(
Zachary Turner067d1db2016-11-16 21:45:04 +00002552 llvm::StringRef search_word, StringList &commands_found,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002553 StringList &commands_help, CommandObject::CommandMap &command_map) {
2554 CommandObject::CommandMap::const_iterator pos;
2555
2556 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
Zachary Turner067d1db2016-11-16 21:45:04 +00002557 llvm::StringRef command_name = pos->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002558 CommandObject *cmd_obj = pos->second.get();
2559
2560 const bool search_short_help = true;
2561 const bool search_long_help = false;
2562 const bool search_syntax = false;
2563 const bool search_options = false;
Zachary Turner067d1db2016-11-16 21:45:04 +00002564 if (command_name.contains_lower(search_word) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002565 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2566 search_long_help, search_syntax,
2567 search_options)) {
2568 commands_found.AppendString(cmd_obj->GetCommandName());
2569 commands_help.AppendString(cmd_obj->GetHelp());
2570 }
2571
2572 if (cmd_obj->IsMultiwordObject()) {
2573 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2574 FindCommandsForApropos(search_word, commands_found, commands_help,
2575 cmd_multiword->GetSubcommandDictionary());
2576 }
2577 }
2578}
2579
Zachary Turner067d1db2016-11-16 21:45:04 +00002580void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002581 StringList &commands_found,
2582 StringList &commands_help,
2583 bool search_builtin_commands,
2584 bool search_user_commands,
2585 bool search_alias_commands) {
2586 CommandObject::CommandMap::const_iterator pos;
2587
2588 if (search_builtin_commands)
2589 FindCommandsForApropos(search_word, commands_found, commands_help,
2590 m_command_dict);
2591
2592 if (search_user_commands)
2593 FindCommandsForApropos(search_word, commands_found, commands_help,
2594 m_user_dict);
2595
2596 if (search_alias_commands)
2597 FindCommandsForApropos(search_word, commands_found, commands_help,
2598 m_alias_dict);
2599}
2600
2601void CommandInterpreter::UpdateExecutionContext(
2602 ExecutionContext *override_context) {
2603 if (override_context != nullptr) {
2604 m_exe_ctx_ref = *override_context;
2605 } else {
2606 const bool adopt_selected = true;
2607 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2608 adopt_selected);
2609 }
2610}
2611
2612size_t CommandInterpreter::GetProcessOutput() {
2613 // The process has stuff waiting for stderr; get it and write it out to the
2614 // appropriate place.
2615 char stdio_buffer[1024];
2616 size_t len;
2617 size_t total_bytes = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002618 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002619 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2620 if (target_sp) {
2621 ProcessSP process_sp(target_sp->GetProcessSP());
2622 if (process_sp) {
2623 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2624 error)) > 0) {
2625 size_t bytes_written = len;
2626 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2627 total_bytes += len;
2628 }
2629 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2630 error)) > 0) {
2631 size_t bytes_written = len;
2632 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2633 total_bytes += len;
2634 }
2635 }
2636 }
2637 return total_bytes;
2638}
2639
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002640void CommandInterpreter::StartHandlingCommand() {
2641 auto idle_state = CommandHandlingState::eIdle;
2642 if (m_command_state.compare_exchange_strong(
2643 idle_state, CommandHandlingState::eInProgress))
2644 lldbassert(m_iohandler_nesting_level == 0);
2645 else
2646 lldbassert(m_iohandler_nesting_level > 0);
2647 ++m_iohandler_nesting_level;
2648}
2649
2650void CommandInterpreter::FinishHandlingCommand() {
2651 lldbassert(m_iohandler_nesting_level > 0);
2652 if (--m_iohandler_nesting_level == 0) {
2653 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2654 lldbassert(prev_state != CommandHandlingState::eIdle);
2655 }
2656}
2657
2658bool CommandInterpreter::InterruptCommand() {
2659 auto in_progress = CommandHandlingState::eInProgress;
2660 return m_command_state.compare_exchange_strong(
2661 in_progress, CommandHandlingState::eInterrupted);
2662}
2663
2664bool CommandInterpreter::WasInterrupted() const {
2665 bool was_interrupted =
2666 (m_command_state == CommandHandlingState::eInterrupted);
2667 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2668 return was_interrupted;
2669}
2670
2671void CommandInterpreter::PrintCommandOutput(Stream &stream,
2672 llvm::StringRef str) {
2673 // Split the output into lines and poll for interrupt requests
2674 const char *data = str.data();
2675 size_t size = str.size();
2676 while (size > 0 && !WasInterrupted()) {
2677 size_t chunk_size = 0;
2678 for (; chunk_size < size; ++chunk_size) {
2679 lldbassert(data[chunk_size] != '\0');
2680 if (data[chunk_size] == '\n') {
2681 ++chunk_size;
2682 break;
2683 }
2684 }
2685 chunk_size = stream.Write(data, chunk_size);
2686 lldbassert(size >= chunk_size);
2687 data += chunk_size;
2688 size -= chunk_size;
2689 }
2690 if (size > 0) {
2691 stream.Printf("\n... Interrupted.\n");
2692 }
2693}
2694
Kate Stoneb9c1b512016-09-06 20:57:50 +00002695void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2696 std::string &line) {
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002697 // If we were interrupted, bail out...
2698 if (WasInterrupted())
2699 return;
2700
Kate Stoneb9c1b512016-09-06 20:57:50 +00002701 const bool is_interactive = io_handler.GetIsInteractive();
2702 if (is_interactive == false) {
2703 // When we are not interactive, don't execute blank lines. This will happen
2704 // sourcing a commands file. We don't want blank lines to repeat the
Adrian Prantl05097242018-04-30 16:49:04 +00002705 // previous command and cause any errors to occur (like redefining an
2706 // alias, get an error and stop parsing the commands file).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002707 if (line.empty())
2708 return;
2709
2710 // When using a non-interactive file handle (like when sourcing commands
Adrian Prantl05097242018-04-30 16:49:04 +00002711 // from a file) we need to echo the command out so we don't just see the
2712 // command output and no command...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002713 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2714 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2715 line.c_str());
2716 }
2717
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002718 StartHandlingCommand();
2719
Kate Stoneb9c1b512016-09-06 20:57:50 +00002720 lldb_private::CommandReturnObject result;
2721 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2722
2723 // Now emit the command output text from the command we just executed
2724 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2725 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2726 GetProcessOutput();
2727
2728 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002729 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002730 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002731 }
2732
2733 // Now emit the command error text from the command we just executed
2734 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002735 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002736 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002737 }
2738 }
2739
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002740 FinishHandlingCommand();
2741
Kate Stoneb9c1b512016-09-06 20:57:50 +00002742 switch (result.GetStatus()) {
2743 case eReturnStatusInvalid:
2744 case eReturnStatusSuccessFinishNoResult:
2745 case eReturnStatusSuccessFinishResult:
2746 case eReturnStatusStarted:
2747 break;
2748
2749 case eReturnStatusSuccessContinuingNoResult:
2750 case eReturnStatusSuccessContinuingResult:
2751 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2752 io_handler.SetIsDone(true);
2753 break;
2754
2755 case eReturnStatusFailed:
2756 m_num_errors++;
2757 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2758 io_handler.SetIsDone(true);
2759 break;
2760
2761 case eReturnStatusQuit:
2762 m_quit_requested = true;
2763 io_handler.SetIsDone(true);
2764 break;
2765 }
2766
2767 // Finally, if we're going to stop on crash, check that here:
2768 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2769 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2770 bool should_stop = false;
2771 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2772 if (target_sp) {
2773 ProcessSP process_sp(target_sp->GetProcessSP());
2774 if (process_sp) {
2775 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2776 StopReason reason = thread_sp->GetStopReason();
2777 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2778 reason == eStopReasonInstrumentation) &&
2779 !result.GetAbnormalStopWasExpected()) {
2780 should_stop = true;
2781 break;
2782 }
2783 }
2784 }
2785 }
2786 if (should_stop) {
2787 io_handler.SetIsDone(true);
2788 m_stopped_for_crash = true;
2789 }
2790 }
2791}
2792
2793bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2794 ExecutionContext exe_ctx(GetExecutionContext());
2795 Process *process = exe_ctx.GetProcessPtr();
2796
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002797 if (InterruptCommand())
2798 return true;
2799
Kate Stoneb9c1b512016-09-06 20:57:50 +00002800 if (process) {
2801 StateType state = process->GetState();
2802 if (StateIsRunningState(state)) {
2803 process->Halt();
2804 return true; // Don't do any updating when we are running
2805 }
2806 }
2807
2808 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2809 if (script_interpreter) {
2810 if (script_interpreter->Interrupt())
2811 return true;
2812 }
2813 return false;
2814}
2815
2816void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2817 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2818 void *baton) {
2819 Debugger &debugger = GetDebugger();
2820 IOHandlerSP io_handler_sp(
2821 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2822 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002823 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2824 llvm::StringRef(), // Continuation prompt
2825 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826 debugger.GetUseColor(),
2827 0, // Don't show line numbers
2828 delegate)); // IOHandlerDelegate
2829
2830 if (io_handler_sp) {
2831 io_handler_sp->SetUserData(baton);
2832 if (asynchronously)
2833 debugger.PushIOHandler(io_handler_sp);
2834 else
2835 debugger.RunIOHandler(io_handler_sp);
2836 }
2837}
2838
2839void CommandInterpreter::GetPythonCommandsFromIOHandler(
2840 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2841 void *baton) {
2842 Debugger &debugger = GetDebugger();
2843 IOHandlerSP io_handler_sp(
2844 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2845 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002846 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2847 llvm::StringRef(), // Continuation prompt
2848 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002849 debugger.GetUseColor(),
2850 0, // Don't show line numbers
2851 delegate)); // IOHandlerDelegate
2852
2853 if (io_handler_sp) {
2854 io_handler_sp->SetUserData(baton);
2855 if (asynchronously)
2856 debugger.PushIOHandler(io_handler_sp);
2857 else
2858 debugger.RunIOHandler(io_handler_sp);
2859 }
2860}
2861
2862bool CommandInterpreter::IsActive() {
2863 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2864}
2865
2866lldb::IOHandlerSP
2867CommandInterpreter::GetIOHandler(bool force_create,
2868 CommandInterpreterRunOptions *options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002869 // Always re-create the IOHandlerEditline in case the input changed. The old
2870 // instance might have had a non-interactive input and now it does or vice
2871 // versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002872 if (force_create || !m_command_io_handler_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002873 // Always re-create the IOHandlerEditline in case the input changed. The
2874 // old instance might have had a non-interactive input and now it does or
2875 // vice versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002876 uint32_t flags = 0;
2877
2878 if (options) {
2879 if (options->m_stop_on_continue == eLazyBoolYes)
2880 flags |= eHandleCommandFlagStopOnContinue;
2881 if (options->m_stop_on_error == eLazyBoolYes)
2882 flags |= eHandleCommandFlagStopOnError;
2883 if (options->m_stop_on_crash == eLazyBoolYes)
2884 flags |= eHandleCommandFlagStopOnCrash;
2885 if (options->m_echo_commands != eLazyBoolNo)
2886 flags |= eHandleCommandFlagEchoCommand;
2887 if (options->m_print_results != eLazyBoolNo)
2888 flags |= eHandleCommandFlagPrintResult;
2889 } else {
2890 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2891 }
2892
2893 m_command_io_handler_sp.reset(new IOHandlerEditline(
2894 m_debugger, IOHandler::Type::CommandInterpreter,
2895 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2896 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002897 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002898 false, // Don't enable multiple line input, just single line commands
2899 m_debugger.GetUseColor(),
2900 0, // Don't show line numbers
2901 *this));
2902 }
2903 return m_command_io_handler_sp;
2904}
2905
2906void CommandInterpreter::RunCommandInterpreter(
2907 bool auto_handle_events, bool spawn_thread,
2908 CommandInterpreterRunOptions &options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002909 // Always re-create the command interpreter when we run it in case any file
2910 // handles have changed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002911 bool force_create = true;
2912 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2913 m_stopped_for_crash = false;
2914
2915 if (auto_handle_events)
2916 m_debugger.StartEventHandlerThread();
2917
2918 if (spawn_thread) {
2919 m_debugger.StartIOHandlerThread();
2920 } else {
2921 m_debugger.ExecuteIOHandlers();
2922
2923 if (auto_handle_events)
2924 m_debugger.StopEventHandlerThread();
2925 }
2926}
2927
2928CommandObject *
2929CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2930 CommandReturnObject &result) {
2931 std::string scratch_command(command_line); // working copy so we don't modify
2932 // command_line unless we succeed
2933 CommandObject *cmd_obj = nullptr;
2934 StreamString revised_command_line;
2935 bool wants_raw_input = false;
2936 size_t actual_cmd_name_len = 0;
2937 std::string next_word;
2938 StringList matches;
2939 bool done = false;
2940 while (!done) {
2941 char quote_char = '\0';
2942 std::string suffix;
2943 ExtractCommand(scratch_command, next_word, suffix, quote_char);
2944 if (cmd_obj == nullptr) {
2945 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002946 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00002947 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002948 bool is_real_command =
2949 (is_alias == false) ||
2950 (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
2951 if (!is_real_command) {
2952 matches.Clear();
2953 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002954 cmd_obj =
2955 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002956 revised_command_line.Printf("%s", alias_result.c_str());
2957 if (cmd_obj) {
2958 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00002959 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002960 }
2961 } else {
2962 if (!cmd_obj)
Zachary Turnera4496982016-10-05 21:14:38 +00002963 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002964 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00002965 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
2966 actual_cmd_name_len += cmd_name.size();
2967 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002968 wants_raw_input = cmd_obj->WantsRawCommandString();
2969 } else {
2970 revised_command_line.Printf("%s", next_word.c_str());
2971 }
2972 }
2973 } else {
2974 if (cmd_obj->IsMultiwordObject()) {
2975 CommandObject *sub_cmd_obj =
2976 cmd_obj->GetSubcommandObject(next_word.c_str());
2977 if (sub_cmd_obj) {
Adrian Prantl05097242018-04-30 16:49:04 +00002978 // The subcommand's name includes the parent command's name, so
2979 // restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00002980 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
2981 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002982 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00002983 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002984 cmd_obj = sub_cmd_obj;
2985 wants_raw_input = cmd_obj->WantsRawCommandString();
2986 } else {
2987 if (quote_char)
2988 revised_command_line.Printf(" %c%s%s%c", quote_char,
2989 next_word.c_str(), suffix.c_str(),
2990 quote_char);
2991 else
2992 revised_command_line.Printf(" %s%s", next_word.c_str(),
2993 suffix.c_str());
2994 done = true;
2995 }
2996 } else {
2997 if (quote_char)
2998 revised_command_line.Printf(" %c%s%s%c", quote_char,
2999 next_word.c_str(), suffix.c_str(),
3000 quote_char);
3001 else
3002 revised_command_line.Printf(" %s%s", next_word.c_str(),
3003 suffix.c_str());
3004 done = true;
3005 }
3006 }
3007
3008 if (cmd_obj == nullptr) {
3009 const size_t num_matches = matches.GetSize();
3010 if (matches.GetSize() > 1) {
3011 StreamString error_msg;
3012 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3013 next_word.c_str());
3014
3015 for (uint32_t i = 0; i < num_matches; ++i) {
3016 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3017 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003018 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003019 } else {
3020 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003021 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003022 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3023 next_word.c_str());
3024 }
3025 result.SetStatus(eReturnStatusFailed);
3026 return nullptr;
3027 }
3028
3029 if (cmd_obj->IsMultiwordObject()) {
3030 if (!suffix.empty()) {
3031 result.AppendErrorWithFormat(
3032 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3033 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003034 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003035 next_word.empty() ? "" : next_word.c_str(),
3036 next_word.empty() ? " -- " : " ", suffix.c_str());
3037 result.SetStatus(eReturnStatusFailed);
3038 return nullptr;
3039 }
3040 } else {
3041 // If we found a normal command, we are done
3042 done = true;
3043 if (!suffix.empty()) {
3044 switch (suffix[0]) {
3045 case '/':
3046 // GDB format suffixes
3047 {
3048 Options *command_options = cmd_obj->GetOptions();
3049 if (command_options &&
3050 command_options->SupportsLongOption("gdb-format")) {
3051 std::string gdb_format_option("--gdb-format=");
3052 gdb_format_option += (suffix.c_str() + 1);
3053
Zachary Turnerc1564272016-11-16 21:15:24 +00003054 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003055 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3056 if (arg_terminator_idx != std::string::npos) {
3057 // Insert the gdb format option before the "--" that terminates
3058 // options
3059 gdb_format_option.append(1, ' ');
3060 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003061 revised_command_line.Clear();
3062 revised_command_line.PutCString(cmd);
3063 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003064 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3065
3066 if (wants_raw_input &&
3067 FindArgumentTerminator(cmd) == std::string::npos)
3068 revised_command_line.PutCString(" --");
3069 } else {
3070 result.AppendErrorWithFormat(
3071 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003072 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003073 result.SetStatus(eReturnStatusFailed);
3074 return nullptr;
3075 }
3076 }
3077 break;
3078
3079 default:
3080 result.AppendErrorWithFormat(
3081 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3082 result.SetStatus(eReturnStatusFailed);
3083 return nullptr;
3084 }
3085 }
3086 }
3087 if (scratch_command.empty())
3088 done = true;
3089 }
3090
3091 if (!scratch_command.empty())
3092 revised_command_line.Printf(" %s", scratch_command.c_str());
3093
3094 if (cmd_obj != NULL)
Zachary Turnerc1564272016-11-16 21:15:24 +00003095 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003096
3097 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003098}