blob: d2014afa869b5ae2847e9c365708bf42fbd7b6f5 [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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147void CommandInterpreter::ResolveCommand(const char *command_line,
148 CommandReturnObject &result) {
149 std::string command = command_line;
150 if (ResolveCommandImpl(command, result) != nullptr) {
151 result.AppendMessageWithFormat("%s", command.c_str());
152 result.SetStatus(eReturnStatusSuccessFinishResult);
153 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000154}
155
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156bool CommandInterpreter::GetStopCmdSourceOnError() const {
157 const uint32_t idx = ePropertyStopCmdSourceOnError;
158 return m_collection_sp->GetPropertyAtIndexAsBoolean(
159 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000160}
161
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162bool CommandInterpreter::GetSpaceReplPrompts() const {
163 const uint32_t idx = eSpaceReplPrompts;
164 return m_collection_sp->GetPropertyAtIndexAsBoolean(
165 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callanan66810412015-10-19 23:11:07 +0000166}
167
Kate Stoneb9c1b512016-09-06 20:57:50 +0000168void CommandInterpreter::Initialize() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000169 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
170 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000171
Kate Stoneb9c1b512016-09-06 20:57:50 +0000172 CommandReturnObject result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000173
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174 LoadCommandDictionary();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000175
Kate Stoneb9c1b512016-09-06 20:57:50 +0000176 // An alias arguments vector to reuse - reset it before use...
177 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
178
179 // Set up some initial aliases.
180 CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
181 if (cmd_obj_sp) {
182 AddAlias("q", cmd_obj_sp);
183 AddAlias("exit", cmd_obj_sp);
184 }
185
186 cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
187 if (cmd_obj_sp)
188 AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
189
190 cmd_obj_sp = GetCommandSPExact("process detach", false);
191 if (cmd_obj_sp) {
192 AddAlias("detach", cmd_obj_sp);
193 }
194
195 cmd_obj_sp = GetCommandSPExact("process continue", false);
196 if (cmd_obj_sp) {
197 AddAlias("c", cmd_obj_sp);
198 AddAlias("continue", cmd_obj_sp);
199 }
200
201 cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
202 if (cmd_obj_sp)
203 AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
204
205 cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
206 if (cmd_obj_sp)
207 AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
208
209 cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
210 if (cmd_obj_sp) {
211 AddAlias("stepi", cmd_obj_sp);
212 AddAlias("si", cmd_obj_sp);
213 }
214
215 cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
216 if (cmd_obj_sp) {
217 AddAlias("nexti", cmd_obj_sp);
218 AddAlias("ni", cmd_obj_sp);
219 }
220
221 cmd_obj_sp = GetCommandSPExact("thread step-in", false);
222 if (cmd_obj_sp) {
223 AddAlias("s", cmd_obj_sp);
224 AddAlias("step", cmd_obj_sp);
225 CommandAlias *sif_alias = AddAlias(
226 "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
227 if (sif_alias) {
228 sif_alias->SetHelp("Step through the current block, stopping if you step "
229 "directly into a function whose name matches the "
230 "TargetFunctionName.");
231 sif_alias->SetSyntax("sif <TargetFunctionName>");
Caroline Ticeca90c472011-05-06 21:37:15 +0000232 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000234
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235 cmd_obj_sp = GetCommandSPExact("thread step-over", false);
236 if (cmd_obj_sp) {
237 AddAlias("n", cmd_obj_sp);
238 AddAlias("next", cmd_obj_sp);
239 }
240
241 cmd_obj_sp = GetCommandSPExact("thread step-out", false);
242 if (cmd_obj_sp) {
243 AddAlias("finish", cmd_obj_sp);
244 }
245
246 cmd_obj_sp = GetCommandSPExact("frame select", false);
247 if (cmd_obj_sp) {
248 AddAlias("f", cmd_obj_sp);
249 }
250
251 cmd_obj_sp = GetCommandSPExact("thread select", false);
252 if (cmd_obj_sp) {
253 AddAlias("t", cmd_obj_sp);
254 }
255
256 cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
257 if (cmd_obj_sp) {
258 AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
259 AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
260 }
261
262 cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
263 if (cmd_obj_sp) {
264 AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
265 AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
266 }
267
268 cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
269 if (cmd_obj_sp)
270 AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
271
272 cmd_obj_sp = GetCommandSPExact("memory read", false);
273 if (cmd_obj_sp)
274 AddAlias("x", cmd_obj_sp);
275
276 cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
277 if (cmd_obj_sp)
278 AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
279
280 cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
281 if (cmd_obj_sp)
282 AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
283
284 cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
285 if (cmd_obj_sp)
286 AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
287
288 cmd_obj_sp = GetCommandSPExact("disassemble", false);
289 if (cmd_obj_sp)
290 AddAlias("dis", cmd_obj_sp);
291
292 cmd_obj_sp = GetCommandSPExact("disassemble", false);
293 if (cmd_obj_sp)
294 AddAlias("di", cmd_obj_sp);
295
296 cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
297 if (cmd_obj_sp)
298 AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
299
300 cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
301 if (cmd_obj_sp)
302 AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
303
304 cmd_obj_sp = GetCommandSPExact("target create", false);
305 if (cmd_obj_sp)
306 AddAlias("file", cmd_obj_sp);
307
308 cmd_obj_sp = GetCommandSPExact("target modules", false);
309 if (cmd_obj_sp)
310 AddAlias("image", cmd_obj_sp);
311
312 alias_arguments_vector_sp.reset(new OptionArgVector);
313
314 cmd_obj_sp = GetCommandSPExact("expression", false);
315 if (cmd_obj_sp) {
316 AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
317 AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
318 AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
319 if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
320 po->SetHelp("Evaluate an expression on the current thread. Displays any "
321 "returned value with formatting "
322 "controlled by the type's author.");
323 po->SetHelpLong("");
Johnny Chen6d675242012-08-24 18:15:45 +0000324 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
326 AddAlias("poarray", cmd_obj_sp,
327 "--object-description --element-count %1 --")
328 ->SetHelpLong("");
329 }
Johnny Chen6d675242012-08-24 18:15:45 +0000330
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331 cmd_obj_sp = GetCommandSPExact("process kill", false);
332 if (cmd_obj_sp) {
333 AddAlias("kill", cmd_obj_sp);
334 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000335
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 cmd_obj_sp = GetCommandSPExact("process launch", false);
337 if (cmd_obj_sp) {
Chaoren Lin6fc5c7f2016-02-26 03:36:27 +0000338 alias_arguments_vector_sp.reset(new OptionArgVector);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000339#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
340 AddAlias("r", cmd_obj_sp, "--");
341 AddAlias("run", cmd_obj_sp, "--");
Jason Molenda85da3122012-07-06 02:46:23 +0000342#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343#if defined(__APPLE__)
344 std::string shell_option;
345 shell_option.append("--shell-expand-args");
346 shell_option.append(" true");
347 shell_option.append(" --");
348 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
349 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
350#else
351 StreamString defaultshell;
352 defaultshell.Printf("--shell=%s --",
353 HostInfo::GetDefaultShell().GetPath().c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +0000354 AddAlias("r", cmd_obj_sp, defaultshell.GetString());
355 AddAlias("run", cmd_obj_sp, defaultshell.GetString());
Jason Molenda85da3122012-07-06 02:46:23 +0000356#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000357#endif
358 }
359
360 cmd_obj_sp = GetCommandSPExact("target symbols add", false);
361 if (cmd_obj_sp) {
362 AddAlias("add-dsym", cmd_obj_sp);
363 }
364
365 cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
366 if (cmd_obj_sp) {
367 AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
368 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000369}
370
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371void CommandInterpreter::Clear() {
372 m_command_io_handler_sp.reset();
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000373
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 if (m_script_interpreter_sp)
375 m_script_interpreter_sp->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000376}
377
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
379 // This function has not yet been implemented.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000380
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 // Look for any embedded script command
382 // If found,
383 // get interpreter object from the command dictionary,
384 // call execute_one_command on it,
385 // get the results as a string,
386 // substitute that string for current stuff.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000387
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 return arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000389}
390
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391void CommandInterpreter::LoadCommandDictionary() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000392 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
393 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000394
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
398 m_command_dict["breakpoint"] =
399 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
400 m_command_dict["bugreport"] =
401 CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
402 m_command_dict["command"] =
403 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
404 m_command_dict["disassemble"] =
405 CommandObjectSP(new CommandObjectDisassemble(*this));
406 m_command_dict["expression"] =
407 CommandObjectSP(new CommandObjectExpression(*this));
408 m_command_dict["frame"] =
409 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
410 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
411 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
412 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
413 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
414 m_command_dict["platform"] =
415 CommandObjectSP(new CommandObjectPlatform(*this));
416 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
417 m_command_dict["process"] =
418 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
419 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
420 m_command_dict["register"] =
421 CommandObjectSP(new CommandObjectRegister(*this));
422 m_command_dict["script"] =
423 CommandObjectSP(new CommandObjectScript(*this, script_language));
424 m_command_dict["settings"] =
425 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
426 m_command_dict["source"] =
427 CommandObjectSP(new CommandObjectMultiwordSource(*this));
Davide Italiano24fff242018-04-13 18:02:39 +0000428 m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000429 m_command_dict["target"] =
430 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
431 m_command_dict["thread"] =
432 CommandObjectSP(new CommandObjectMultiwordThread(*this));
433 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
434 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
435 m_command_dict["watchpoint"] =
436 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
437 m_command_dict["language"] =
438 CommandObjectSP(new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000439
Kate Stoneb9c1b512016-09-06 20:57:50 +0000440 const char *break_regexes[][2] = {
441 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
442 "breakpoint set --file '%1' --line %2"},
443 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
444 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
445 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
446 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
447 "breakpoint set --name '%1'"},
448 {"^(-.*)$", "breakpoint set %1"},
449 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
450 "breakpoint set --name '%2' --shlib '%1'"},
451 {"^\\&(.*[^[:space:]])[[:space:]]*$",
452 "breakpoint set --name '%1' --skip-prologue=0"},
453 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
454 "breakpoint set --name '%1'"}};
Kate Stone7428a182016-07-14 22:03:10 +0000455
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000457
Kate Stoneb9c1b512016-09-06 20:57:50 +0000458 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap(
459 new CommandObjectRegexCommand(
460 *this, "_regexp-break",
461 "Set a breakpoint using one of several shorthand formats.\n",
462 "\n"
463 "_regexp-break <filename>:<linenum>\n"
464 " main.c:12 // Break at line 12 of "
465 "main.c\n\n"
466 "_regexp-break <linenum>\n"
467 " 12 // Break at line 12 of current "
468 "file\n\n"
469 "_regexp-break 0x<address>\n"
470 " 0x1234000 // Break at address "
471 "0x1234000\n\n"
472 "_regexp-break <name>\n"
473 " main // Break in 'main' after the "
474 "prologue\n\n"
475 "_regexp-break &<name>\n"
476 " &main // Break at first instruction "
477 "in 'main'\n\n"
478 "_regexp-break <module>`<name>\n"
479 " libc.so`malloc // Break in 'malloc' from "
480 "'libc.so'\n\n"
481 "_regexp-break /<source-regex>/\n"
482 " /break here/ // Break on source lines in "
483 "current file\n"
484 " // containing text 'break "
485 "here'.\n",
486 2, CommandCompletions::eSymbolCompletion |
487 CommandCompletions::eSourceFileCompletion,
488 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000489
Kate Stoneb9c1b512016-09-06 20:57:50 +0000490 if (break_regex_cmd_ap.get()) {
491 bool success = true;
492 for (size_t i = 0; i < num_regexes; i++) {
493 success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0],
494 break_regexes[i][1]);
495 if (!success)
496 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000497 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000498 success =
499 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Jim Inghamffba2292011-03-22 02:29:32 +0000500
Kate Stoneb9c1b512016-09-06 20:57:50 +0000501 if (success) {
502 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
503 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
Jim Inghamca36cd12012-10-05 19:16:31 +0000504 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505 }
Jim Inghamca36cd12012-10-05 19:16:31 +0000506
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap(
508 new CommandObjectRegexCommand(
509 *this, "_regexp-tbreak",
510 "Set a one-shot breakpoint using one of several shorthand formats.\n",
511 "\n"
512 "_regexp-break <filename>:<linenum>\n"
513 " main.c:12 // Break at line 12 of "
514 "main.c\n\n"
515 "_regexp-break <linenum>\n"
516 " 12 // Break at line 12 of current "
517 "file\n\n"
518 "_regexp-break 0x<address>\n"
519 " 0x1234000 // Break at address "
520 "0x1234000\n\n"
521 "_regexp-break <name>\n"
522 " main // Break in 'main' after the "
523 "prologue\n\n"
524 "_regexp-break &<name>\n"
525 " &main // Break at first instruction "
526 "in 'main'\n\n"
527 "_regexp-break <module>`<name>\n"
528 " libc.so`malloc // Break in 'malloc' from "
529 "'libc.so'\n\n"
530 "_regexp-break /<source-regex>/\n"
531 " /break here/ // Break on source lines in "
532 "current file\n"
533 " // containing text 'break "
534 "here'.\n",
535 2, CommandCompletions::eSymbolCompletion |
536 CommandCompletions::eSourceFileCompletion,
537 false));
538
539 if (tbreak_regex_cmd_ap.get()) {
540 bool success = true;
541 for (size_t i = 0; i < num_regexes; i++) {
542 // If you add a resultant command string longer than 1024 characters be
543 // sure to increase the size of this buffer.
544 char buffer[1024];
545 int num_printed =
Frederic Riss49c9d8b2018-06-18 04:34:33 +0000546 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1");
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000547 lldbassert(num_printed < 1024);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 UNUSED_IF_ASSERT_DISABLED(num_printed);
549 success =
550 tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer);
551 if (!success)
552 break;
Johnny Chen6d675242012-08-24 18:15:45 +0000553 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 success =
555 tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Kate Stone7428a182016-07-14 22:03:10 +0000556
Kate Stoneb9c1b512016-09-06 20:57:50 +0000557 if (success) {
558 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
559 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
560 tbreak_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000561 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 }
Kate Stone7428a182016-07-14 22:03:10 +0000563
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap(
565 new CommandObjectRegexCommand(
566 *this, "_regexp-attach", "Attach to process by ID or name.",
567 "_regexp-attach <pid> | <process-name>", 2, 0, false));
568 if (attach_regex_cmd_ap.get()) {
569 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
570 "process attach --pid %1") &&
571 attach_regex_cmd_ap->AddRegexCommand(
572 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
573 // specified get passed to
574 // 'process attach'
575 attach_regex_cmd_ap->AddRegexCommand("^(.+)$",
576 "process attach --name '%1'") &&
577 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) {
578 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
579 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
580 attach_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000581 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000583
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap(
585 new CommandObjectRegexCommand(*this, "_regexp-down",
586 "Select a newer stack frame. Defaults to "
587 "moving one frame, a numeric argument can "
588 "specify an arbitrary number.",
589 "_regexp-down [<count>]", 2, 0, false));
590 if (down_regex_cmd_ap.get()) {
591 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
592 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
593 "frame select -r -%1")) {
594 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
595 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000596 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000598
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap(
600 new CommandObjectRegexCommand(
601 *this, "_regexp-up",
602 "Select an older stack frame. Defaults to moving one "
603 "frame, a numeric argument can specify an arbitrary number.",
604 "_regexp-up [<count>]", 2, 0, false));
605 if (up_regex_cmd_ap.get()) {
606 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
607 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
608 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
609 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000610 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000611 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000612
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap(
614 new CommandObjectRegexCommand(
615 *this, "_regexp-display",
616 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
617 "_regexp-display expression", 2, 0, false));
618 if (display_regex_cmd_ap.get()) {
619 if (display_regex_cmd_ap->AddRegexCommand(
620 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
621 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
622 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
623 display_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000624 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000625 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000626
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap(
628 new CommandObjectRegexCommand(
629 *this, "_regexp-undisplay", "Stop displaying expression at every "
630 "stop (specified by stop-hook index.)",
631 "_regexp-undisplay stop-hook-number", 2, 0, false));
632 if (undisplay_regex_cmd_ap.get()) {
633 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
634 "target stop-hook delete %1")) {
635 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
636 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
637 undisplay_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000638 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000639 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000640
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap(
642 new CommandObjectRegexCommand(
643 *this, "gdb-remote", "Connect to a process via remote GDB server. "
644 "If no host is specifed, localhost is assumed.",
645 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
646 if (connect_gdb_remote_cmd_ap.get()) {
647 if (connect_gdb_remote_cmd_ap->AddRegexCommand(
Chris Bieneman51978f52017-04-27 16:13:58 +0000648 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
649 "process connect --plugin gdb-remote connect://%1:%2") &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000650 connect_gdb_remote_cmd_ap->AddRegexCommand(
651 "^([[:digit:]]+)$",
652 "process connect --plugin gdb-remote connect://localhost:%1")) {
653 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
654 m_command_dict[command_sp->GetCommandName()] = command_sp;
Jason Molenda4cddfed2012-10-05 05:29:32 +0000655 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656 }
Jason Molenda4cddfed2012-10-05 05:29:32 +0000657
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap(
659 new CommandObjectRegexCommand(
660 *this, "kdp-remote", "Connect to a process via remote KDP server. "
661 "If no UDP port is specified, port 41139 is "
662 "assumed.",
663 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
664 if (connect_kdp_remote_cmd_ap.get()) {
665 if (connect_kdp_remote_cmd_ap->AddRegexCommand(
666 "^([^:]+:[[:digit:]]+)$",
667 "process connect --plugin kdp-remote udp://%1") &&
668 connect_kdp_remote_cmd_ap->AddRegexCommand(
669 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
670 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
671 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Clayton6bade322013-02-01 23:33:03 +0000672 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 }
Greg Clayton6bade322013-02-01 23:33:03 +0000674
Kate Stoneb9c1b512016-09-06 20:57:50 +0000675 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap(
676 new CommandObjectRegexCommand(
677 *this, "_regexp-bt",
678 "Show the current thread's call stack. Any numeric argument "
679 "displays at most that many "
680 "frames. The argument 'all' displays all threads.",
681 "bt [<digit> | all]", 2, 0, false));
682 if (bt_regex_cmd_ap.get()) {
683 // accept but don't document "bt -c <number>" -- before bt was a regex
Adrian Prantl05097242018-04-30 16:49:04 +0000684 // command if you wanted to backtrace three frames you would do "bt -c 3"
685 // but the intention is to have this emulate the gdb "bt" command and so
686 // now "bt 3" is the preferred form, in line with gdb.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000687 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$",
688 "thread backtrace -c %1") &&
689 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$",
690 "thread backtrace -c %1") &&
691 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
692 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) {
693 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
694 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Claytonef5651d2013-02-12 18:52:24 +0000695 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 }
Greg Claytonef5651d2013-02-12 18:52:24 +0000697
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap(
699 new CommandObjectRegexCommand(
700 *this, "_regexp-list",
701 "List relevant source code using one of several shorthand formats.",
702 "\n"
703 "_regexp-list <file>:<line> // List around specific file/line\n"
704 "_regexp-list <line> // List current file around specified "
705 "line\n"
706 "_regexp-list <function-name> // List specified function\n"
707 "_regexp-list 0x<address> // List around specified address\n"
708 "_regexp-list -[<count>] // List previous <count> lines\n"
709 "_regexp-list // List subsequent lines",
710 2, CommandCompletions::eSourceFileCompletion, false));
711 if (list_regex_cmd_ap.get()) {
712 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
713 "source list --line %1") &&
714 list_regex_cmd_ap->AddRegexCommand(
715 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
716 "]*$",
717 "source list --file '%1' --line %2") &&
718 list_regex_cmd_ap->AddRegexCommand(
719 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
720 "source list --address %1") &&
721 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$",
722 "source list --reverse") &&
723 list_regex_cmd_ap->AddRegexCommand(
724 "^-([[:digit:]]+)[[:space:]]*$",
725 "source list --reverse --count %1") &&
726 list_regex_cmd_ap->AddRegexCommand("^(.+)$",
727 "source list --name \"%1\"") &&
728 list_regex_cmd_ap->AddRegexCommand("^$", "source list")) {
729 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
730 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
Richard Mittonf86248d2013-09-12 02:20:34 +0000731 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732 }
Richard Mittonf86248d2013-09-12 02:20:34 +0000733
Kate Stoneb9c1b512016-09-06 20:57:50 +0000734 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap(
735 new CommandObjectRegexCommand(
736 *this, "_regexp-env",
737 "Shorthand for viewing and setting environment variables.",
738 "\n"
739 "_regexp-env // Show enrivonment\n"
740 "_regexp-env <name>=<value> // Set an environment variable",
741 2, 0, false));
742 if (env_regex_cmd_ap.get()) {
743 if (env_regex_cmd_ap->AddRegexCommand("^$",
744 "settings show target.env-vars") &&
745 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
746 "settings set target.env-vars %1")) {
747 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
748 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
749 }
750 }
751
752 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap(
753 new CommandObjectRegexCommand(
754 *this, "_regexp-jump", "Set the program counter to a new address.",
755 "\n"
756 "_regexp-jump <line>\n"
757 "_regexp-jump +<line-offset> | -<line-offset>\n"
758 "_regexp-jump <file>:<line>\n"
759 "_regexp-jump *<addr>\n",
760 2, 0, false));
761 if (jump_regex_cmd_ap.get()) {
762 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$",
763 "thread jump --addr %1") &&
764 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
765 "thread jump --line %1") &&
766 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$",
767 "thread jump --file %1 --line %2") &&
768 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$",
769 "thread jump --by %1")) {
770 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
771 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
772 }
773 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000774}
775
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776int CommandInterpreter::GetCommandNamesMatchingPartialString(
777 const char *cmd_str, bool include_aliases, StringList &matches) {
778 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000779
Kate Stoneb9c1b512016-09-06 20:57:50 +0000780 if (include_aliases) {
781 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches);
782 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000783
Kate Stoneb9c1b512016-09-06 20:57:50 +0000784 return matches.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000785}
786
Zachary Turnera4496982016-10-05 21:14:38 +0000787CommandObjectSP CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000788 bool include_aliases,
789 bool exact,
Zachary Turnera4496982016-10-05 21:14:38 +0000790 StringList *matches) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000791 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000792
Zachary Turnera4496982016-10-05 21:14:38 +0000793 std::string cmd = cmd_str;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000794
Kate Stoneb9c1b512016-09-06 20:57:50 +0000795 if (HasCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000796 auto pos = m_command_dict.find(cmd);
Greg Claytonb5472782015-01-09 19:08:20 +0000797 if (pos != m_command_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000798 command_sp = pos->second;
799 }
800
801 if (include_aliases && HasAliases()) {
802 auto alias_pos = m_alias_dict.find(cmd);
803 if (alias_pos != m_alias_dict.end())
804 command_sp = alias_pos->second;
805 }
806
807 if (HasUserCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000808 auto pos = m_user_dict.find(cmd);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000809 if (pos != m_user_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000810 command_sp = pos->second;
811 }
812
813 if (!exact && !command_sp) {
814 // We will only get into here if we didn't find any exact matches.
815
816 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
817
818 StringList local_matches;
819 if (matches == nullptr)
820 matches = &local_matches;
821
822 unsigned int num_cmd_matches = 0;
823 unsigned int num_alias_matches = 0;
824 unsigned int num_user_matches = 0;
825
826 // Look through the command dictionaries one by one, and if we get only one
Adrian Prantl05097242018-04-30 16:49:04 +0000827 // match from any of them in toto, then return that, otherwise return an
828 // empty CommandObjectSP and the list of matches.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000829
830 if (HasCommands()) {
831 num_cmd_matches =
Zachary Turnera4496982016-10-05 21:14:38 +0000832 AddNamesMatchingPartialString(m_command_dict, cmd_str, *matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000833 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834
835 if (num_cmd_matches == 1) {
836 cmd.assign(matches->GetStringAtIndex(0));
Zachary Turnera4496982016-10-05 21:14:38 +0000837 auto pos = m_command_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000838 if (pos != m_command_dict.end())
839 real_match_sp = pos->second;
840 }
841
842 if (include_aliases && HasAliases()) {
843 num_alias_matches =
Zachary Turnera4496982016-10-05 21:14:38 +0000844 AddNamesMatchingPartialString(m_alias_dict, cmd_str, *matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000845 }
846
847 if (num_alias_matches == 1) {
848 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
849 auto alias_pos = m_alias_dict.find(cmd);
850 if (alias_pos != m_alias_dict.end())
851 alias_match_sp = alias_pos->second;
852 }
853
854 if (HasUserCommands()) {
855 num_user_matches =
Zachary Turnera4496982016-10-05 21:14:38 +0000856 AddNamesMatchingPartialString(m_user_dict, cmd_str, *matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000857 }
858
859 if (num_user_matches == 1) {
860 cmd.assign(
861 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
862
Zachary Turnera4496982016-10-05 21:14:38 +0000863 auto pos = m_user_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000864 if (pos != m_user_dict.end())
865 user_match_sp = pos->second;
866 }
867
868 // If we got exactly one match, return that, otherwise return the match
869 // list.
870
871 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
872 if (num_cmd_matches)
873 return real_match_sp;
874 else if (num_alias_matches)
875 return alias_match_sp;
876 else
877 return user_match_sp;
878 }
879 } else if (matches && command_sp) {
Zachary Turnera4496982016-10-05 21:14:38 +0000880 matches->AppendString(cmd_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 }
882
883 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000884}
885
Zachary Turnera4496982016-10-05 21:14:38 +0000886bool CommandInterpreter::AddCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887 const lldb::CommandObjectSP &cmd_sp,
888 bool can_replace) {
889 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000890 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
891 "tried to add a CommandObject from a different interpreter");
Kate Stonea487aa42015-01-15 00:52:41 +0000892
Zachary Turnera4496982016-10-05 21:14:38 +0000893 if (name.empty())
894 return false;
895
896 std::string name_sstr(name);
897 auto name_iter = m_command_dict.find(name_sstr);
898 if (name_iter != m_command_dict.end()) {
899 if (!can_replace || !name_iter->second->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000900 return false;
Zachary Turnera4496982016-10-05 21:14:38 +0000901 name_iter->second = cmd_sp;
902 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000903 m_command_dict[name_sstr] = cmd_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904 }
Zachary Turnera4496982016-10-05 21:14:38 +0000905 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000906}
907
Zachary Turnera483f572016-10-05 21:14:49 +0000908bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000909 const lldb::CommandObjectSP &cmd_sp,
910 bool can_replace) {
911 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000912 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
913 "tried to add a CommandObject from a different interpreter");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000914
Kate Stoneb9c1b512016-09-06 20:57:50 +0000915 if (!name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000916 // do not allow replacement of internal commands
Zachary Turnera483f572016-10-05 21:14:49 +0000917 if (CommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000918 if (can_replace == false)
919 return false;
920 if (m_command_dict[name]->IsRemovable() == false)
Greg Clayton5a314712011-10-14 07:41:33 +0000921 return false;
922 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000923
Zachary Turnera483f572016-10-05 21:14:49 +0000924 if (UserCommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000925 if (can_replace == false)
926 return false;
927 if (m_user_dict[name]->IsRemovable() == false)
928 return false;
Caroline Tice844d2302010-12-09 22:52:49 +0000929 }
930
Kate Stoneb9c1b512016-09-06 20:57:50 +0000931 m_user_dict[name] = cmd_sp;
932 return true;
933 }
934 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000935}
936
Zachary Turnera4496982016-10-05 21:14:38 +0000937CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
938 bool include_aliases) const {
939 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +0000940 // it's a multi-word command.
941 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000942
Zachary Turnera4496982016-10-05 21:14:38 +0000943 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000944 return ret_val;
945
946 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +0000947 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948 else {
949 // We have a multi-word command (seemingly), so we need to do more work.
950 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +0000951 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 include_aliases, true, nullptr);
953 if (cmd_obj_sp.get() != nullptr) {
Adrian Prantl05097242018-04-30 16:49:04 +0000954 // Loop through the rest of the words in the command (everything passed
955 // in was supposed to be part of a command name), and find the
956 // appropriate sub-command SP for each command word....
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957 size_t end = cmd_words.GetArgumentCount();
958 for (size_t j = 1; j < end; ++j) {
959 if (cmd_obj_sp->IsMultiwordObject()) {
960 cmd_obj_sp =
961 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
962 if (cmd_obj_sp.get() == nullptr)
963 // The sub-command name was invalid. Fail and return the empty
964 // 'ret_val'.
965 return ret_val;
966 } else
967 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +0000968 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 return ret_val;
970 }
971 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +0000972 // command objects for them. Assign the last object retrieved to
973 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000975 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 }
977 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000978}
979
Zachary Turnera4496982016-10-05 21:14:38 +0000980CommandObject *CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
981 StringList *matches) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000982 CommandObject *command_obj =
Zachary Turnera4496982016-10-05 21:14:38 +0000983 GetCommandSP(cmd_str, false, true, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000984
Kate Stoneb9c1b512016-09-06 20:57:50 +0000985 // If we didn't find an exact match to the command string in the commands,
Adrian Prantl05097242018-04-30 16:49:04 +0000986 // look in the aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000987
988 if (command_obj)
989 return command_obj;
990
Zachary Turnera4496982016-10-05 21:14:38 +0000991 command_obj = GetCommandSP(cmd_str, true, true, matches).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000992
993 if (command_obj)
994 return command_obj;
995
996 // If there wasn't an exact match then look for an inexact one in just the
997 // commands
Zachary Turnera4496982016-10-05 21:14:38 +0000998 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999
1000 // Finally, if there wasn't an inexact match among the commands, look for an
Adrian Prantl05097242018-04-30 16:49:04 +00001001 // inexact match in both the commands and aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002
1003 if (command_obj) {
1004 if (matches)
1005 matches->AppendString(command_obj->GetCommandName());
1006 return command_obj;
1007 }
1008
Zachary Turnera4496982016-10-05 21:14:38 +00001009 return GetCommandSP(cmd_str, true, false, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001010}
1011
Zachary Turnera483f572016-10-05 21:14:49 +00001012bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001013 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001014}
1015
Zachary Turnera483f572016-10-05 21:14:49 +00001016bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1017 std::string &full_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1019 if (exact_match) {
1020 full_name.assign(cmd);
1021 return exact_match;
1022 } else {
1023 StringList matches;
1024 size_t num_alias_matches;
1025 num_alias_matches =
1026 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1027 if (num_alias_matches == 1) {
1028 // Make sure this isn't shadowing a command in the regular command space:
1029 StringList regular_matches;
1030 const bool include_aliases = false;
1031 const bool exact = false;
1032 CommandObjectSP cmd_obj_sp(
1033 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1034 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1035 return false;
1036 else {
1037 full_name.assign(matches.GetStringAtIndex(0));
1038 return true;
1039 }
1040 } else
1041 return false;
1042 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001043}
1044
Zachary Turnera483f572016-10-05 21:14:49 +00001045bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001046 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047}
1048
Zachary Turnera483f572016-10-05 21:14:49 +00001049bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001050 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001051}
1052
Kate Stoneb9c1b512016-09-06 20:57:50 +00001053CommandAlias *
Zachary Turnera483f572016-10-05 21:14:49 +00001054CommandInterpreter::AddAlias(llvm::StringRef alias_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001055 lldb::CommandObjectSP &command_obj_sp,
Zachary Turnera483f572016-10-05 21:14:49 +00001056 llvm::StringRef args_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 if (command_obj_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001058 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1059 "tried to add a CommandObject from a different interpreter");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001060
1061 std::unique_ptr<CommandAlias> command_alias_up(
1062 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1063
1064 if (command_alias_up && command_alias_up->IsValid()) {
1065 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1066 return command_alias_up.release();
1067 }
1068
1069 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070}
1071
Zachary Turnera483f572016-10-05 21:14:49 +00001072bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073 auto pos = m_alias_dict.find(alias_name);
1074 if (pos != m_alias_dict.end()) {
1075 m_alias_dict.erase(pos);
1076 return true;
1077 }
1078 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001079}
1080
Zachary Turnera483f572016-10-05 21:14:49 +00001081bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001082 auto pos = m_command_dict.find(cmd);
1083 if (pos != m_command_dict.end()) {
1084 if (pos->second->IsRemovable()) {
1085 // Only regular expression objects or python commands are removable
1086 m_command_dict.erase(pos);
1087 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001088 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001089 }
1090 return false;
1091}
Zachary Turnera483f572016-10-05 21:14:49 +00001092bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1094 if (pos != m_user_dict.end()) {
1095 m_user_dict.erase(pos);
1096 return true;
1097 }
1098 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001099}
1100
Kate Stoneb9c1b512016-09-06 20:57:50 +00001101void CommandInterpreter::GetHelp(CommandReturnObject &result,
1102 uint32_t cmd_types) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001103 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1104 if (!help_prologue.empty()) {
1105 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1106 help_prologue);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001107 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001108
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109 CommandObject::CommandMap::const_iterator pos;
1110 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001111
Kate Stoneb9c1b512016-09-06 20:57:50 +00001112 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1113 result.AppendMessage("Debugger commands:");
1114 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001115
Kate Stoneb9c1b512016-09-06 20:57:50 +00001116 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1117 if (!(cmd_types & eCommandTypesHidden) &&
1118 (pos->first.compare(0, 1, "_") == 0))
1119 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001120
Zachary Turner0ac5f982016-11-08 04:12:42 +00001121 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1122 pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001123 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124 result.AppendMessage("");
1125 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001126
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127 if (!m_alias_dict.empty() &&
1128 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1129 result.AppendMessageWithFormat(
1130 "Current command abbreviations "
1131 "(type '%shelp command alias' for more info):\n",
1132 GetCommandPrefix());
1133 result.AppendMessage("");
1134 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001135
Kate Stoneb9c1b512016-09-06 20:57:50 +00001136 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1137 ++alias_pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001138 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001140 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001141 result.AppendMessage("");
1142 }
Greg Clayton14a35512011-09-11 00:01:44 +00001143
Kate Stoneb9c1b512016-09-06 20:57:50 +00001144 if (!m_user_dict.empty() &&
1145 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1146 result.AppendMessage("Current user-defined commands:");
1147 result.AppendMessage("");
1148 max_len = FindLongestCommandWord(m_user_dict);
1149 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001150 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1151 pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001152 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001153 result.AppendMessage("");
1154 }
Greg Clayton14a35512011-09-11 00:01:44 +00001155
Kate Stoneb9c1b512016-09-06 20:57:50 +00001156 result.AppendMessageWithFormat(
1157 "For more information on any command, type '%shelp <command-name>'.\n",
1158 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001159}
1160
Zachary Turnera01bccd2016-10-05 21:14:56 +00001161CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1162 llvm::StringRef &command_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163 // This function finds the final, lowest-level, alias-resolved command object
Adrian Prantl05097242018-04-30 16:49:04 +00001164 // whose 'Execute' function will eventually be invoked by the given command
1165 // line.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001166
1167 CommandObject *cmd_obj = nullptr;
1168 size_t start = command_string.find_first_not_of(k_white_space);
1169 size_t end = 0;
1170 bool done = false;
1171 while (!done) {
1172 if (start != std::string::npos) {
1173 // Get the next word from command_string.
1174 end = command_string.find_first_of(k_white_space, start);
1175 if (end == std::string::npos)
1176 end = command_string.size();
1177 std::string cmd_word = command_string.substr(start, end - start);
1178
1179 if (cmd_obj == nullptr)
1180 // Since cmd_obj is NULL we are on our first time through this loop.
Zachary Turnera01bccd2016-10-05 21:14:56 +00001181 // Check to see if cmd_word is a valid command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001182 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001183 else if (cmd_obj->IsMultiwordObject()) {
1184 // Our current object is a multi-word object; see if the cmd_word is a
1185 // valid sub-command for our object.
1186 CommandObject *sub_cmd_obj =
1187 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1188 if (sub_cmd_obj)
1189 cmd_obj = sub_cmd_obj;
1190 else // cmd_word was not a valid sub-command word, so we are done
1191 done = true;
1192 } else
1193 // We have a cmd_obj and it is not a multi-word object, so we are done.
1194 done = true;
1195
1196 // If we didn't find a valid command object, or our command object is not
Zachary Turnera01bccd2016-10-05 21:14:56 +00001197 // a multi-word object, or we are at the end of the command_string, then
1198 // we are done. Otherwise, find the start of the next word.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001199
1200 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1201 end >= command_string.size())
1202 done = true;
1203 else
1204 start = command_string.find_first_not_of(k_white_space, end);
1205 } else
1206 // Unable to find any more words.
1207 done = true;
1208 }
1209
Zachary Turnera01bccd2016-10-05 21:14:56 +00001210 command_string = command_string.substr(end);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001211 return cmd_obj;
1212}
1213
1214static const char *k_valid_command_chars =
1215 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1216static void StripLeadingSpaces(std::string &s) {
1217 if (!s.empty()) {
1218 size_t pos = s.find_first_not_of(k_white_space);
1219 if (pos == std::string::npos)
1220 s.clear();
1221 else if (pos == 0)
1222 return;
1223 s.erase(0, pos);
1224 }
1225}
1226
1227static size_t FindArgumentTerminator(const std::string &s) {
1228 const size_t s_len = s.size();
1229 size_t offset = 0;
1230 while (offset < s_len) {
1231 size_t pos = s.find("--", offset);
1232 if (pos == std::string::npos)
1233 break;
1234 if (pos > 0) {
1235 if (isspace(s[pos - 1])) {
Adrian Prantl05097242018-04-30 16:49:04 +00001236 // Check if the string ends "\s--" (where \s is a space character) or
1237 // if we have "\s--\s".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001238 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1239 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001240 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241 }
1242 }
1243 offset = pos + 2;
1244 }
1245 return std::string::npos;
1246}
1247
1248static bool ExtractCommand(std::string &command_string, std::string &command,
1249 std::string &suffix, char &quote_char) {
1250 command.clear();
1251 suffix.clear();
1252 StripLeadingSpaces(command_string);
1253
1254 bool result = false;
1255 quote_char = '\0';
1256
1257 if (!command_string.empty()) {
1258 const char first_char = command_string[0];
1259 if (first_char == '\'' || first_char == '"') {
1260 quote_char = first_char;
1261 const size_t end_quote_pos = command_string.find(quote_char, 1);
1262 if (end_quote_pos == std::string::npos) {
1263 command.swap(command_string);
1264 command_string.erase();
1265 } else {
1266 command.assign(command_string, 1, end_quote_pos - 1);
1267 if (end_quote_pos + 1 < command_string.size())
1268 command_string.erase(0, command_string.find_first_not_of(
1269 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001270 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001271 command_string.erase();
1272 }
1273 } else {
1274 const size_t first_space_pos =
1275 command_string.find_first_of(k_white_space);
1276 if (first_space_pos == std::string::npos) {
1277 command.swap(command_string);
1278 command_string.erase();
1279 } else {
1280 command.assign(command_string, 0, first_space_pos);
1281 command_string.erase(0, command_string.find_first_not_of(
1282 k_white_space, first_space_pos));
1283 }
1284 }
1285 result = true;
1286 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001287
Kate Stoneb9c1b512016-09-06 20:57:50 +00001288 if (!command.empty()) {
1289 // actual commands can't start with '-' or '_'
1290 if (command[0] != '-' && command[0] != '_') {
1291 size_t pos = command.find_first_not_of(k_valid_command_chars);
1292 if (pos > 0 && pos != std::string::npos) {
1293 suffix.assign(command.begin() + pos, command.end());
1294 command.erase(pos);
1295 }
1296 }
1297 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001298
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 return result;
1300}
1301
1302CommandObject *CommandInterpreter::BuildAliasResult(
Zachary Turnera483f572016-10-05 21:14:49 +00001303 llvm::StringRef alias_name, std::string &raw_input_string,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304 std::string &alias_result, CommandReturnObject &result) {
1305 CommandObject *alias_cmd_obj = nullptr;
1306 Args cmd_args(raw_input_string);
1307 alias_cmd_obj = GetCommandObject(alias_name);
1308 StreamString result_str;
1309
Zachary Turner5c28c662016-10-03 23:20:36 +00001310 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1311 alias_result.clear();
1312 return alias_cmd_obj;
1313 }
1314 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1315 ((CommandAlias *)alias_cmd_obj)->Desugar();
1316 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1317 alias_cmd_obj = desugared.first.get();
1318 std::string alias_name_str = alias_name;
1319 if ((cmd_args.GetArgumentCount() == 0) ||
1320 (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0))
1321 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001322
Zachary Turnera4496982016-10-05 21:14:38 +00001323 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001324
Zachary Turner5c28c662016-10-03 23:20:36 +00001325 if (!option_arg_vector_sp.get()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001326 alias_result = result_str.GetString();
Zachary Turner5c28c662016-10-03 23:20:36 +00001327 return alias_cmd_obj;
1328 }
1329 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330
Zachary Turner5c28c662016-10-03 23:20:36 +00001331 int value_type;
1332 std::string option;
1333 std::string value;
1334 for (const auto &entry : *option_arg_vector) {
1335 std::tie(option, value_type, value) = entry;
1336 if (option == "<argument>") {
1337 result_str.Printf(" %s", value.c_str());
1338 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001339 }
1340
Zachary Turner5c28c662016-10-03 23:20:36 +00001341 result_str.Printf(" %s", option.c_str());
1342 if (value_type == OptionParser::eNoArgument)
1343 continue;
1344
1345 if (value_type != OptionParser::eOptionalArgument)
1346 result_str.Printf(" ");
1347 int index = GetOptionArgumentPosition(value.c_str());
1348 if (index == 0)
1349 result_str.Printf("%s", value.c_str());
1350 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1351
1352 result.AppendErrorWithFormat("Not enough arguments provided; you "
1353 "need at least %d arguments to use "
1354 "this alias.\n",
1355 index);
1356 result.SetStatus(eReturnStatusFailed);
1357 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001358 } else {
1359 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1360 if (strpos != std::string::npos)
1361 raw_input_string = raw_input_string.erase(
1362 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1363 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001364 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001365 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001366
Zachary Turnerc1564272016-11-16 21:15:24 +00001367 alias_result = result_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001368 return alias_cmd_obj;
1369}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001370
Zachary Turner97206d52017-05-12 04:51:55 +00001371Status CommandInterpreter::PreprocessCommand(std::string &command) {
Adrian Prantl05097242018-04-30 16:49:04 +00001372 // The command preprocessor needs to do things to the command line before any
1373 // parsing of arguments or anything else is done. The only current stuff that
1374 // gets preprocessed is anything enclosed in backtick ('`') characters is
1375 // evaluated as an expression and the result of the expression must be a
1376 // scalar that can be substituted into the command. An example would be:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001377 // (lldb) memory read `$rsp + 20`
Zachary Turner97206d52017-05-12 04:51:55 +00001378 Status error; // Status for any expressions that might not evaluate
Kate Stoneb9c1b512016-09-06 20:57:50 +00001379 size_t start_backtick;
1380 size_t pos = 0;
1381 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1382 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
Adrian Prantl05097242018-04-30 16:49:04 +00001383 // The backtick was preceded by a '\' character, remove the slash and
1384 // don't treat the backtick as the start of an expression
Kate Stoneb9c1b512016-09-06 20:57:50 +00001385 command.erase(start_backtick - 1, 1);
1386 // No need to add one to start_backtick since we just deleted a char
1387 pos = start_backtick;
1388 } else {
1389 const size_t expr_content_start = start_backtick + 1;
1390 const size_t end_backtick = command.find('`', expr_content_start);
1391 if (end_backtick == std::string::npos)
1392 return error;
1393 else if (end_backtick == expr_content_start) {
1394 // Empty expression (two backticks in a row)
1395 command.erase(start_backtick, 2);
1396 } else {
1397 std::string expr_str(command, expr_content_start,
1398 end_backtick - expr_content_start);
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001399
Kate Stoneb9c1b512016-09-06 20:57:50 +00001400 ExecutionContext exe_ctx(GetExecutionContext());
1401 Target *target = exe_ctx.GetTargetPtr();
1402 // Get a dummy target to allow for calculator mode while processing
Adrian Prantl05097242018-04-30 16:49:04 +00001403 // backticks. This also helps break the infinite loop caused when
1404 // target is null.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001405 if (!target)
1406 target = m_debugger.GetDummyTarget();
1407 if (target) {
1408 ValueObjectSP expr_result_valobj_sp;
1409
1410 EvaluateExpressionOptions options;
1411 options.SetCoerceToId(false);
1412 options.SetUnwindOnError(true);
1413 options.SetIgnoreBreakpoints(true);
1414 options.SetKeepInMemory(false);
1415 options.SetTryAllThreads(true);
Pavel Labath43d35412016-12-06 11:24:51 +00001416 options.SetTimeout(llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001417
1418 ExpressionResults expr_result = target->EvaluateExpression(
1419 expr_str.c_str(), exe_ctx.GetFramePtr(), expr_result_valobj_sp,
1420 options);
1421
1422 if (expr_result == eExpressionCompleted) {
1423 Scalar scalar;
1424 if (expr_result_valobj_sp)
1425 expr_result_valobj_sp =
1426 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1427 expr_result_valobj_sp->GetDynamicValueType(), true);
1428 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1429 command.erase(start_backtick, end_backtick - start_backtick + 1);
1430 StreamString value_strm;
1431 const bool show_type = false;
1432 scalar.GetValue(&value_strm, show_type);
1433 size_t value_string_size = value_strm.GetSize();
1434 if (value_string_size) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001435 command.insert(start_backtick, value_strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001436 pos = start_backtick + value_string_size;
1437 continue;
1438 } else {
1439 error.SetErrorStringWithFormat("expression value didn't result "
1440 "in a scalar value for the "
1441 "expression '%s'",
1442 expr_str.c_str());
1443 }
1444 } else {
1445 error.SetErrorStringWithFormat("expression value didn't result "
1446 "in a scalar value for the "
1447 "expression '%s'",
1448 expr_str.c_str());
1449 }
1450 } else {
1451 if (expr_result_valobj_sp)
1452 error = expr_result_valobj_sp->GetError();
1453 if (error.Success()) {
1454
1455 switch (expr_result) {
1456 case eExpressionSetupError:
1457 error.SetErrorStringWithFormat(
1458 "expression setup error for the expression '%s'",
1459 expr_str.c_str());
1460 break;
1461 case eExpressionParseError:
1462 error.SetErrorStringWithFormat(
1463 "expression parse error for the expression '%s'",
1464 expr_str.c_str());
1465 break;
1466 case eExpressionResultUnavailable:
1467 error.SetErrorStringWithFormat(
1468 "expression error fetching result for the expression '%s'",
1469 expr_str.c_str());
1470 break;
1471 case eExpressionCompleted:
1472 break;
1473 case eExpressionDiscarded:
1474 error.SetErrorStringWithFormat(
1475 "expression discarded for the expression '%s'",
1476 expr_str.c_str());
1477 break;
1478 case eExpressionInterrupted:
1479 error.SetErrorStringWithFormat(
1480 "expression interrupted for the expression '%s'",
1481 expr_str.c_str());
1482 break;
1483 case eExpressionHitBreakpoint:
1484 error.SetErrorStringWithFormat(
1485 "expression hit breakpoint for the expression '%s'",
1486 expr_str.c_str());
1487 break;
1488 case eExpressionTimedOut:
1489 error.SetErrorStringWithFormat(
1490 "expression timed out for the expression '%s'",
1491 expr_str.c_str());
1492 break;
1493 case eExpressionStoppedForDebug:
1494 error.SetErrorStringWithFormat("expression stop at entry point "
1495 "for debugging for the "
1496 "expression '%s'",
1497 expr_str.c_str());
1498 break;
1499 }
1500 }
1501 }
1502 }
1503 }
1504 if (error.Fail())
1505 break;
1506 }
1507 }
1508 return error;
1509}
1510
1511bool CommandInterpreter::HandleCommand(const char *command_line,
1512 LazyBool lazy_add_to_history,
1513 CommandReturnObject &result,
1514 ExecutionContext *override_context,
1515 bool repeat_on_empty_command,
1516 bool no_context_switching)
1517
1518{
1519
1520 std::string command_string(command_line);
1521 std::string original_command_string(command_line);
1522
1523 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
Jim Ingham8f7db522016-12-15 00:30:30 +00001524 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
Sean Callanan237c3ed2016-12-14 21:31:31 +00001525 command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001526
1527 if (log)
1528 log->Printf("Processing command: %s", command_line);
1529
Pavel Labathf9d16472017-05-15 13:02:37 +00001530 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1531 Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001532
1533 if (!no_context_switching)
1534 UpdateExecutionContext(override_context);
1535
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001536 if (WasInterrupted()) {
1537 result.AppendError("interrupted");
1538 result.SetStatus(eReturnStatusFailed);
1539 return false;
1540 }
1541
Kate Stoneb9c1b512016-09-06 20:57:50 +00001542 bool add_to_history;
1543 if (lazy_add_to_history == eLazyBoolCalculate)
1544 add_to_history = (m_command_source_depth == 0);
1545 else
1546 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1547
1548 bool empty_command = false;
1549 bool comment_command = false;
1550 if (command_string.empty())
1551 empty_command = true;
1552 else {
1553 const char *k_space_characters = "\t\n\v\f\r ";
1554
1555 size_t non_space = command_string.find_first_not_of(k_space_characters);
Adrian Prantl05097242018-04-30 16:49:04 +00001556 // Check for empty line or comment line (lines whose first non-space
1557 // character is the comment character for this interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001558 if (non_space == std::string::npos)
1559 empty_command = true;
1560 else if (command_string[non_space] == m_comment_char)
1561 comment_command = true;
1562 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001563 llvm::StringRef search_str(command_string);
1564 search_str = search_str.drop_front(non_space);
1565 if (auto hist_str = m_command_history.FindString(search_str)) {
1566 add_to_history = false;
1567 command_string = *hist_str;
1568 original_command_string = *hist_str;
1569 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001570 result.AppendErrorWithFormat("Could not find entry: %s in history",
1571 command_string.c_str());
1572 result.SetStatus(eReturnStatusFailed);
1573 return false;
1574 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001575 }
1576 }
1577
1578 if (empty_command) {
1579 if (repeat_on_empty_command) {
1580 if (m_command_history.IsEmpty()) {
1581 result.AppendError("empty command");
1582 result.SetStatus(eReturnStatusFailed);
1583 return false;
1584 } else {
1585 command_line = m_repeat_command.c_str();
1586 command_string = command_line;
1587 original_command_string = command_line;
1588 if (m_repeat_command.empty()) {
1589 result.AppendErrorWithFormat("No auto repeat.\n");
1590 result.SetStatus(eReturnStatusFailed);
1591 return false;
1592 }
1593 }
1594 add_to_history = false;
1595 } else {
1596 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1597 return true;
1598 }
1599 } else if (comment_command) {
1600 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1601 return true;
1602 }
1603
Zachary Turner97206d52017-05-12 04:51:55 +00001604 Status error(PreprocessCommand(command_string));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001605
1606 if (error.Fail()) {
1607 result.AppendError(error.AsCString());
1608 result.SetStatus(eReturnStatusFailed);
1609 return false;
1610 }
1611
1612 // Phase 1.
1613
1614 // Before we do ANY kind of argument processing, we need to figure out what
1615 // the real/final command object is for the specified command. This gets
1616 // complicated by the fact that the user could have specified an alias, and,
1617 // in translating the alias, there may also be command options and/or even
1618 // data (including raw text strings) that need to be found and inserted into
1619 // the command line as part of the translation. So this first step is plain
1620 // look-up and replacement, resulting in:
1621 // 1. the command object whose Execute method will actually be called
1622 // 2. a revised command string, with all substitutions and replacements
1623 // taken care of
1624 // From 1 above, we can determine whether the Execute function wants raw
1625 // input or not.
1626
1627 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1628
1629 // Although the user may have abbreviated the command, the command_string now
Adrian Prantl05097242018-04-30 16:49:04 +00001630 // has the command expanded to the full name. For example, if the input was
1631 // "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001632 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001633 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1634 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001635 log->Printf("HandleCommand, (revised) command_string: '%s'",
1636 command_string.c_str());
1637 const bool wants_raw_input =
1638 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1639 log->Printf("HandleCommand, wants_raw_input:'%s'",
1640 wants_raw_input ? "True" : "False");
1641 }
1642
1643 // Phase 2.
1644 // Take care of things like setting up the history command & calling the
Adrian Prantl05097242018-04-30 16:49:04 +00001645 // appropriate Execute method on the CommandObject, with the appropriate
1646 // arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001647
1648 if (cmd_obj != nullptr) {
1649 if (add_to_history) {
1650 Args command_args(command_string);
1651 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1652 if (repeat_command != nullptr)
1653 m_repeat_command.assign(repeat_command);
1654 else
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001655 m_repeat_command.assign(original_command_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001656
1657 m_command_history.AppendString(original_command_string);
1658 }
1659
1660 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001661 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001662 if (actual_cmd_name_len < command_string.length())
1663 remainder = command_string.substr(actual_cmd_name_len);
1664
1665 // Remove any initial spaces
1666 size_t pos = remainder.find_first_not_of(k_white_space);
1667 if (pos != 0 && pos != std::string::npos)
1668 remainder.erase(0, pos);
1669
1670 if (log)
1671 log->Printf(
1672 "HandleCommand, command line after removing command name(s): '%s'",
1673 remainder.c_str());
1674
1675 cmd_obj->Execute(remainder.c_str(), result);
1676 } else {
1677 // We didn't find the first command object, so complete the first argument.
1678 Args command_args(command_string);
1679 StringList matches;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001680 int cursor_index = 0;
1681 int cursor_char_position = strlen(command_args.GetArgumentAtIndex(0));
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001682 bool word_complete = true;
1683 CompletionRequest request(command_line, cursor_char_position, command_args,
1684 cursor_index, cursor_char_position, 0, -1,
1685 word_complete, matches);
1686 int num_matches = HandleCompletionMatches(request);
1687 word_complete = request.GetWordComplete();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001688
1689 if (num_matches > 0) {
1690 std::string error_msg;
1691 error_msg.assign("ambiguous command '");
1692 error_msg.append(command_args.GetArgumentAtIndex(0));
1693 error_msg.append("'.");
1694
1695 error_msg.append(" Possible completions:");
1696 for (int i = 0; i < num_matches; i++) {
1697 error_msg.append("\n\t");
1698 error_msg.append(matches.GetStringAtIndex(i));
1699 }
1700 error_msg.append("\n");
1701 result.AppendRawError(error_msg.c_str());
1702 } else
1703 result.AppendErrorWithFormat("Unrecognized command '%s'.\n",
1704 command_args.GetArgumentAtIndex(0));
1705
1706 result.SetStatus(eReturnStatusFailed);
1707 }
1708
1709 if (log)
1710 log->Printf("HandleCommand, command %s",
1711 (result.Succeeded() ? "succeeded" : "did not succeed"));
1712
1713 return result.Succeeded();
1714}
1715
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001716int CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
1717 auto &matches = request.GetMatches();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001718 int num_command_matches = 0;
1719 bool look_for_subcommand = false;
1720
1721 // For any of the command completions a unique match will be a complete word.
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001722 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001723
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001724 if (request.GetCursorIndex() == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001725 // We got nothing on the command line, so return the list of commands
1726 bool include_aliases = true;
1727 num_command_matches =
1728 GetCommandNamesMatchingPartialString("", include_aliases, matches);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001729 } else if (request.GetCursorIndex() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730 // The cursor is in the first argument, so just do a lookup in the
1731 // dictionary.
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001732 CommandObject *cmd_obj = GetCommandObject(
1733 request.GetParsedLine().GetArgumentAtIndex(0), &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001734 num_command_matches = matches.GetSize();
1735
1736 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
1737 matches.GetStringAtIndex(0) != nullptr &&
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001738 strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001739 matches.GetStringAtIndex(0)) == 0) {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001740 if (request.GetParsedLine().GetArgumentCount() == 1) {
1741 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001742 } else {
1743 look_for_subcommand = true;
1744 num_command_matches = 0;
1745 matches.DeleteStringAtIndex(0);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001746 request.GetParsedLine().AppendArgument(llvm::StringRef());
1747 request.SetCursorIndex(request.GetCursorIndex() + 1);
1748 request.SetCursorCharPosition(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001749 }
1750 }
1751 }
1752
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001753 if (request.GetCursorIndex() > 0 || look_for_subcommand) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001754 // We are completing further on into a commands arguments, so find the
Adrian Prantl05097242018-04-30 16:49:04 +00001755 // command and tell it to complete the command. First see if there is a
1756 // matching initial command:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001757 CommandObject *command_object =
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001758 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001759 if (command_object == nullptr) {
1760 return 0;
1761 } else {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001762 request.GetParsedLine().Shift();
1763 request.SetCursorIndex(request.GetCursorIndex() - 1);
1764 num_command_matches = command_object->HandleCompletion(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001765 }
1766 }
1767
1768 return num_command_matches;
1769}
1770
1771int CommandInterpreter::HandleCompletion(
1772 const char *current_line, const char *cursor, const char *last_char,
1773 int match_start_point, int max_return_elements, StringList &matches) {
Adrian Prantl05097242018-04-30 16:49:04 +00001774 // We parse the argument up to the cursor, so the last argument in
1775 // parsed_line is the one containing the cursor, and the cursor is after the
1776 // last character.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001777
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001778 llvm::StringRef command_line(current_line, last_char - current_line);
1779 Args parsed_line(command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001780 Args partial_parsed_line(
1781 llvm::StringRef(current_line, cursor - current_line));
1782
1783 // Don't complete comments, and if the line we are completing is just the
Adrian Prantl05097242018-04-30 16:49:04 +00001784 // history repeat character, substitute the appropriate history line.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001785 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1786 if (first_arg) {
1787 if (first_arg[0] == m_comment_char)
1788 return 0;
1789 else if (first_arg[0] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001790 if (auto hist_str = m_command_history.FindString(first_arg)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001791 matches.Clear();
Zachary Turner53877af2016-11-18 23:22:42 +00001792 matches.InsertStringAtIndex(0, *hist_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001793 return -2;
1794 } else
1795 return 0;
1796 }
1797 }
1798
1799 int num_args = partial_parsed_line.GetArgumentCount();
1800 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1801 int cursor_char_position;
1802
1803 if (cursor_index == -1)
1804 cursor_char_position = 0;
1805 else
1806 cursor_char_position =
1807 strlen(partial_parsed_line.GetArgumentAtIndex(cursor_index));
1808
1809 if (cursor > current_line && cursor[-1] == ' ') {
1810 // We are just after a space. If we are in an argument, then we will
Adrian Prantl05097242018-04-30 16:49:04 +00001811 // continue parsing, but if we are between arguments, then we have to
1812 // complete whatever the next element would be. We can distinguish the two
1813 // cases because if we are in an argument (e.g. because the space is
Kate Stoneb9c1b512016-09-06 20:57:50 +00001814 // protected by a quote) then the space will also be in the parsed
1815 // argument...
1816
1817 const char *current_elem =
1818 partial_parsed_line.GetArgumentAtIndex(cursor_index);
1819 if (cursor_char_position == 0 ||
1820 current_elem[cursor_char_position - 1] != ' ') {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001821 parsed_line.InsertArgumentAtIndex(cursor_index + 1, llvm::StringRef(),
1822 '\0');
Kate Stoneb9c1b512016-09-06 20:57:50 +00001823 cursor_index++;
1824 cursor_char_position = 0;
1825 }
1826 }
1827
1828 int num_command_matches;
1829
1830 matches.Clear();
1831
1832 // Only max_return_elements == -1 is supported at present:
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001833 lldbassert(max_return_elements == -1);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001834 bool word_complete = false;
1835
1836 CompletionRequest request(command_line, cursor - current_line, parsed_line,
1837 cursor_index, cursor_char_position,
1838 match_start_point, max_return_elements,
1839 word_complete, matches);
1840
1841 num_command_matches = HandleCompletionMatches(request);
1842 word_complete = request.GetWordComplete();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001843
1844 if (num_command_matches <= 0)
1845 return num_command_matches;
1846
1847 if (num_args == 0) {
1848 // If we got an empty string, insert nothing.
1849 matches.InsertStringAtIndex(0, "");
1850 } else {
1851 // Now figure out if there is a common substring, and if so put that in
Adrian Prantl05097242018-04-30 16:49:04 +00001852 // element 0, otherwise put an empty string in element 0.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001853 std::string command_partial_str;
1854 if (cursor_index >= 0)
Zachary Turnerd6a24752016-11-22 17:10:15 +00001855 command_partial_str =
1856 parsed_line[cursor_index].ref.take_front(cursor_char_position);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001857
1858 std::string common_prefix;
1859 matches.LongestCommonPrefix(common_prefix);
1860 const size_t partial_name_len = command_partial_str.size();
1861 common_prefix.erase(0, partial_name_len);
1862
Adrian Prantl05097242018-04-30 16:49:04 +00001863 // If we matched a unique single command, add a space... Only do this if
1864 // the completer told us this was a complete word, however...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001865 if (num_command_matches == 1 && word_complete) {
Zachary Turnerd6a24752016-11-22 17:10:15 +00001866 char quote_char = parsed_line[cursor_index].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001867 common_prefix =
1868 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1869 if (quote_char != '\0')
1870 common_prefix.push_back(quote_char);
1871 common_prefix.push_back(' ');
1872 }
1873 matches.InsertStringAtIndex(0, common_prefix.c_str());
1874 }
1875 return num_command_matches;
1876}
1877
1878CommandInterpreter::~CommandInterpreter() {}
1879
Zachary Turner514d8cd2016-09-23 18:06:53 +00001880void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001881 EventSP prompt_change_event_sp(
1882 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1883 ;
1884 BroadcastEvent(prompt_change_event_sp);
1885 if (m_command_io_handler_sp)
1886 m_command_io_handler_sp->SetPrompt(new_prompt);
1887}
1888
Zachary Turner7a120c82016-11-13 03:05:58 +00001889bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001890 // Check AutoConfirm first:
1891 if (m_debugger.GetAutoConfirm())
1892 return default_answer;
1893
1894 IOHandlerConfirm *confirm =
1895 new IOHandlerConfirm(m_debugger, message, default_answer);
1896 IOHandlerSP io_handler_sp(confirm);
1897 m_debugger.RunIOHandler(io_handler_sp);
1898 return confirm->GetResponse();
1899}
1900
Zachary Turnera483f572016-10-05 21:14:49 +00001901const CommandAlias *
1902CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001903 OptionArgVectorSP ret_val;
1904
Zachary Turnera483f572016-10-05 21:14:49 +00001905 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001906 if (pos != m_alias_dict.end())
1907 return (CommandAlias *)pos->second.get();
1908
1909 return nullptr;
1910}
1911
Zachary Turnera4496982016-10-05 21:14:38 +00001912bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001913
Zachary Turnera4496982016-10-05 21:14:38 +00001914bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001915
Zachary Turnera4496982016-10-05 21:14:38 +00001916bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001917
Zachary Turnera4496982016-10-05 21:14:38 +00001918bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001919
1920void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1921 const char *alias_name,
1922 Args &cmd_args,
1923 std::string &raw_input_string,
1924 CommandReturnObject &result) {
1925 OptionArgVectorSP option_arg_vector_sp =
1926 GetAlias(alias_name)->GetOptionArguments();
1927
1928 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1929
1930 // Make sure that the alias name is the 0th element in cmd_args
1931 std::string alias_name_str = alias_name;
1932 if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)
Zachary Turner5c725f32016-09-19 21:56:59 +00001933 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001934
1935 Args new_args(alias_cmd_obj->GetCommandName());
1936 if (new_args.GetArgumentCount() == 2)
1937 new_args.Shift();
1938
1939 if (option_arg_vector_sp.get()) {
1940 if (wants_raw_input) {
1941 // We have a command that both has command options and takes raw input.
Adrian Prantl05097242018-04-30 16:49:04 +00001942 // Make *sure* it has a " -- " in the right place in the
1943 // raw_input_string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001944 size_t pos = raw_input_string.find(" -- ");
1945 if (pos == std::string::npos) {
1946 // None found; assume it goes at the beginning of the raw input string
1947 raw_input_string.insert(0, " -- ");
1948 }
1949 }
1950
1951 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1952 const size_t old_size = cmd_args.GetArgumentCount();
1953 std::vector<bool> used(old_size + 1, false);
1954
1955 used[0] = true;
1956
Zachary Turner5c28c662016-10-03 23:20:36 +00001957 int value_type;
1958 std::string option;
1959 std::string value;
1960 for (const auto &option_entry : *option_arg_vector) {
1961 std::tie(option, value_type, value) = option_entry;
1962 if (option == "<argument>") {
1963 if (!wants_raw_input || (value != "--")) {
1964 // Since we inserted this above, make sure we don't insert it twice
1965 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001966 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001967 continue;
1968 }
1969
1970 if (value_type != OptionParser::eOptionalArgument)
1971 new_args.AppendArgument(option);
1972
1973 if (value == "<no-argument>")
1974 continue;
1975
1976 int index = GetOptionArgumentPosition(value.c_str());
1977 if (index == 0) {
1978 // value was NOT a positional argument; must be a real value
1979 if (value_type != OptionParser::eOptionalArgument)
1980 new_args.AppendArgument(value);
1981 else {
1982 char buffer[255];
1983 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1984 value.c_str());
1985 new_args.AppendArgument(llvm::StringRef(buffer));
1986 }
1987
1988 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1989 result.AppendErrorWithFormat("Not enough arguments provided; you "
1990 "need at least %d arguments to use "
1991 "this alias.\n",
1992 index);
1993 result.SetStatus(eReturnStatusFailed);
1994 return;
1995 } else {
1996 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1997 size_t strpos =
1998 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1999 if (strpos != std::string::npos) {
2000 raw_input_string = raw_input_string.erase(
2001 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2002 }
2003
2004 if (value_type != OptionParser::eOptionalArgument)
2005 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2006 else {
2007 char buffer[255];
2008 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2009 cmd_args.GetArgumentAtIndex(index));
2010 new_args.AppendArgument(buffer);
2011 }
2012 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002013 }
2014 }
2015
Zachary Turner97d2c402016-10-05 23:40:23 +00002016 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00002017 if (!used[entry.index()] && !wants_raw_input)
2018 new_args.AppendArgument(entry.value().ref);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002019 }
2020
2021 cmd_args.Clear();
2022 cmd_args.SetArguments(new_args.GetArgumentCount(),
2023 new_args.GetConstArgumentVector());
2024 } else {
2025 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2026 // This alias was not created with any options; nothing further needs to be
Adrian Prantl05097242018-04-30 16:49:04 +00002027 // done, unless it is a command that wants raw input, in which case we need
2028 // to clear the rest of the data from cmd_args, since its in the raw input
2029 // string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002030 if (wants_raw_input) {
2031 cmd_args.Clear();
2032 cmd_args.SetArguments(new_args.GetArgumentCount(),
2033 new_args.GetConstArgumentVector());
2034 }
2035 return;
2036 }
2037
2038 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2039 return;
2040}
2041
2042int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2043 int position = 0; // Any string that isn't an argument position, i.e. '%'
2044 // followed by an integer, gets a position
2045 // of zero.
2046
2047 const char *cptr = in_string;
2048
2049 // Does it start with '%'
2050 if (cptr[0] == '%') {
2051 ++cptr;
2052
2053 // Is the rest of it entirely digits?
2054 if (isdigit(cptr[0])) {
2055 const char *start = cptr;
2056 while (isdigit(cptr[0]))
2057 ++cptr;
2058
Adrian Prantl05097242018-04-30 16:49:04 +00002059 // We've gotten to the end of the digits; are we at the end of the
2060 // string?
Kate Stoneb9c1b512016-09-06 20:57:50 +00002061 if (cptr[0] == '\0')
2062 position = atoi(start);
2063 }
2064 }
2065
2066 return position;
2067}
2068
2069void CommandInterpreter::SourceInitFile(bool in_cwd,
2070 CommandReturnObject &result) {
2071 FileSpec init_file;
2072 if (in_cwd) {
2073 ExecutionContext exe_ctx(GetExecutionContext());
2074 Target *target = exe_ctx.GetTargetPtr();
2075 if (target) {
2076 // In the current working directory we don't load any program specific
2077 // .lldbinit files, we only look for a ".lldbinit" file.
2078 if (m_skip_lldbinit_files)
2079 return;
2080
2081 LoadCWDlldbinitFile should_load =
2082 target->TargetProperties::GetLoadCWDlldbinitFile();
2083 if (should_load == eLoadCWDlldbinitWarn) {
2084 FileSpec dot_lldb(".lldbinit", true);
2085 llvm::SmallString<64> home_dir_path;
2086 llvm::sys::path::home_directory(home_dir_path);
2087 FileSpec homedir_dot_lldb(home_dir_path.c_str(), false);
2088 homedir_dot_lldb.AppendPathComponent(".lldbinit");
2089 homedir_dot_lldb.ResolvePath();
2090 if (dot_lldb.Exists() &&
2091 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2092 result.AppendErrorWithFormat(
2093 "There is a .lldbinit file in the current directory which is not "
2094 "being read.\n"
2095 "To silence this warning without sourcing in the local "
2096 ".lldbinit,\n"
2097 "add the following to the lldbinit file in your home directory:\n"
2098 " settings set target.load-cwd-lldbinit false\n"
2099 "To allow lldb to source .lldbinit files in the current working "
2100 "directory,\n"
2101 "set the value of this variable to true. Only do so if you "
2102 "understand and\n"
2103 "accept the security risk.");
2104 result.SetStatus(eReturnStatusFailed);
2105 return;
2106 }
2107 } else if (should_load == eLoadCWDlldbinitTrue) {
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002108 init_file.SetFile("./.lldbinit", true, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002109 }
2110 }
2111 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002112 // If we aren't looking in the current working directory we are looking in
2113 // the home directory. We will first see if there is an application
2114 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a "-"
2115 // and the name of the program. If this file doesn't exist, we fall back to
2116 // just the "~/.lldbinit" file. We also obey any requests to not load the
2117 // init files.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002118 llvm::SmallString<64> home_dir_path;
2119 llvm::sys::path::home_directory(home_dir_path);
2120 FileSpec profilePath(home_dir_path.c_str(), false);
2121 profilePath.AppendPathComponent(".lldbinit");
2122 std::string init_file_path = profilePath.GetPath();
2123
2124 if (m_skip_app_init_files == false) {
2125 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2126 const char *program_name = program_file_spec.GetFilename().AsCString();
2127
2128 if (program_name) {
2129 char program_init_file_name[PATH_MAX];
2130 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2131 "%s-%s", init_file_path.c_str(), program_name);
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002132 init_file.SetFile(program_init_file_name, true,
2133 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002134 if (!init_file.Exists())
2135 init_file.Clear();
2136 }
2137 }
2138
2139 if (!init_file && !m_skip_lldbinit_files)
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002140 init_file.SetFile(init_file_path, false, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002141 }
2142
2143 // If the file exists, tell HandleCommand to 'source' it; this will do the
Adrian Prantl05097242018-04-30 16:49:04 +00002144 // actual broadcasting of the commands back to any appropriate listener (see
Kate Stoneb9c1b512016-09-06 20:57:50 +00002145 // CommandObjectSource::Execute for more details).
2146
2147 if (init_file.Exists()) {
2148 const bool saved_batch = SetBatchCommandMode(true);
2149 CommandInterpreterRunOptions options;
2150 options.SetSilent(true);
2151 options.SetStopOnError(false);
2152 options.SetStopOnContinue(true);
2153
2154 HandleCommandsFromFile(init_file,
2155 nullptr, // Execution context
2156 options, result);
2157 SetBatchCommandMode(saved_batch);
2158 } else {
2159 // nothing to be done if the file doesn't exist
2160 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2161 }
2162}
2163
2164const char *CommandInterpreter::GetCommandPrefix() {
2165 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2166 return prefix == NULL ? "" : prefix;
2167}
2168
2169PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2170 PlatformSP platform_sp;
2171 if (prefer_target_platform) {
2172 ExecutionContext exe_ctx(GetExecutionContext());
2173 Target *target = exe_ctx.GetTargetPtr();
2174 if (target)
2175 platform_sp = target->GetPlatform();
2176 }
2177
2178 if (!platform_sp)
2179 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2180 return platform_sp;
2181}
2182
2183void CommandInterpreter::HandleCommands(const StringList &commands,
2184 ExecutionContext *override_context,
2185 CommandInterpreterRunOptions &options,
2186 CommandReturnObject &result) {
2187 size_t num_lines = commands.GetSize();
2188
2189 // If we are going to continue past a "continue" then we need to run the
Adrian Prantl05097242018-04-30 16:49:04 +00002190 // commands synchronously. Make sure you reset this value anywhere you return
2191 // from the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002192
2193 bool old_async_execution = m_debugger.GetAsyncExecution();
2194
2195 // If we've been given an execution context, set it at the start, but don't
Adrian Prantl05097242018-04-30 16:49:04 +00002196 // keep resetting it or we will cause series of commands that change the
2197 // context, then do an operation that relies on that context to fail.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002198
2199 if (override_context != nullptr)
2200 UpdateExecutionContext(override_context);
2201
2202 if (!options.GetStopOnContinue()) {
2203 m_debugger.SetAsyncExecution(false);
2204 }
2205
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002206 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002207 const char *cmd = commands.GetStringAtIndex(idx);
2208 if (cmd[0] == '\0')
2209 continue;
2210
2211 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002212 // TODO: Add Stream support.
2213 result.AppendMessageWithFormat("%s %s\n",
2214 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002215 }
2216
2217 CommandReturnObject tmp_result;
2218 // If override_context is not NULL, pass no_context_switching = true for
2219 // HandleCommand() since we updated our context already.
2220
2221 // We might call into a regex or alias command, in which case the
Adrian Prantl05097242018-04-30 16:49:04 +00002222 // add_to_history will get lost. This m_command_source_depth dingus is the
2223 // way we turn off adding to the history in that case, so set it up here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002224 if (!options.GetAddToHistory())
2225 m_command_source_depth++;
2226 bool success =
2227 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2228 nullptr, /* override_context */
2229 true, /* repeat_on_empty_command */
2230 override_context != nullptr /* no_context_switching */);
2231 if (!options.GetAddToHistory())
2232 m_command_source_depth--;
2233
2234 if (options.GetPrintResults()) {
2235 if (tmp_result.Succeeded())
Zachary Turner03c9f362016-11-14 23:23:31 +00002236 result.AppendMessage(tmp_result.GetOutputData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002237 }
2238
2239 if (!success || !tmp_result.Succeeded()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002240 llvm::StringRef error_msg = tmp_result.GetErrorData();
2241 if (error_msg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002242 error_msg = "<unknown error>.\n";
2243 if (options.GetStopOnError()) {
2244 result.AppendErrorWithFormat(
2245 "Aborting reading of commands after command #%" PRIu64
2246 ": '%s' failed with %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00002247 (uint64_t)idx, cmd, error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002248 result.SetStatus(eReturnStatusFailed);
2249 m_debugger.SetAsyncExecution(old_async_execution);
2250 return;
2251 } else if (options.GetPrintResults()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002252 result.AppendMessageWithFormat(
2253 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2254 error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002255 }
2256 }
2257
2258 if (result.GetImmediateOutputStream())
2259 result.GetImmediateOutputStream()->Flush();
2260
2261 if (result.GetImmediateErrorStream())
2262 result.GetImmediateErrorStream()->Flush();
2263
Adrian Prantl05097242018-04-30 16:49:04 +00002264 // N.B. Can't depend on DidChangeProcessState, because the state coming
2265 // into the command execution could be running (for instance in Breakpoint
2266 // Commands. So we check the return value to see if it is has running in
2267 // it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002268 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2269 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2270 if (options.GetStopOnContinue()) {
2271 // If we caused the target to proceed, and we're going to stop in that
Adrian Prantl05097242018-04-30 16:49:04 +00002272 // case, set the status in our real result before returning. This is
2273 // an error if the continue was not the last command in the set of
2274 // commands to be run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002275 if (idx != num_lines - 1)
2276 result.AppendErrorWithFormat(
2277 "Aborting reading of commands after command #%" PRIu64
2278 ": '%s' continued the target.\n",
2279 (uint64_t)idx + 1, cmd);
2280 else
2281 result.AppendMessageWithFormat("Command #%" PRIu64
2282 " '%s' continued the target.\n",
2283 (uint64_t)idx + 1, cmd);
2284
2285 result.SetStatus(tmp_result.GetStatus());
2286 m_debugger.SetAsyncExecution(old_async_execution);
2287
2288 return;
2289 }
2290 }
2291
2292 // Also check for "stop on crash here:
2293 bool should_stop = false;
2294 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2295 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2296 if (target_sp) {
2297 ProcessSP process_sp(target_sp->GetProcessSP());
2298 if (process_sp) {
2299 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2300 StopReason reason = thread_sp->GetStopReason();
2301 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2302 reason == eStopReasonInstrumentation) {
2303 should_stop = true;
2304 break;
2305 }
2306 }
2307 }
2308 }
2309 if (should_stop) {
2310 if (idx != num_lines - 1)
2311 result.AppendErrorWithFormat(
2312 "Aborting reading of commands after command #%" PRIu64
2313 ": '%s' stopped with a signal or exception.\n",
2314 (uint64_t)idx + 1, cmd);
2315 else
2316 result.AppendMessageWithFormat(
2317 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2318 (uint64_t)idx + 1, cmd);
2319
2320 result.SetStatus(tmp_result.GetStatus());
2321 m_debugger.SetAsyncExecution(old_async_execution);
2322
2323 return;
2324 }
2325 }
2326 }
2327
2328 result.SetStatus(eReturnStatusSuccessFinishResult);
2329 m_debugger.SetAsyncExecution(old_async_execution);
2330
2331 return;
2332}
2333
2334// Make flags that we can pass into the IOHandler so our delegates can do the
2335// right thing
2336enum {
2337 eHandleCommandFlagStopOnContinue = (1u << 0),
2338 eHandleCommandFlagStopOnError = (1u << 1),
2339 eHandleCommandFlagEchoCommand = (1u << 2),
2340 eHandleCommandFlagPrintResult = (1u << 3),
2341 eHandleCommandFlagStopOnCrash = (1u << 4)
2342};
2343
2344void CommandInterpreter::HandleCommandsFromFile(
2345 FileSpec &cmd_file, ExecutionContext *context,
2346 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2347 if (cmd_file.Exists()) {
2348 StreamFileSP input_file_sp(new StreamFile());
2349
2350 std::string cmd_file_path = cmd_file.GetPath();
Zachary Turner97206d52017-05-12 04:51:55 +00002351 Status error = input_file_sp->GetFile().Open(cmd_file_path.c_str(),
2352 File::eOpenOptionRead);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002353
2354 if (error.Success()) {
2355 Debugger &debugger = GetDebugger();
2356
2357 uint32_t flags = 0;
2358
2359 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2360 if (m_command_source_flags.empty()) {
2361 // Stop on continue by default
2362 flags |= eHandleCommandFlagStopOnContinue;
2363 } else if (m_command_source_flags.back() &
2364 eHandleCommandFlagStopOnContinue) {
2365 flags |= eHandleCommandFlagStopOnContinue;
2366 }
2367 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2368 flags |= eHandleCommandFlagStopOnContinue;
2369 }
2370
2371 if (options.m_stop_on_error == eLazyBoolCalculate) {
2372 if (m_command_source_flags.empty()) {
2373 if (GetStopCmdSourceOnError())
2374 flags |= eHandleCommandFlagStopOnError;
2375 } else if (m_command_source_flags.back() &
2376 eHandleCommandFlagStopOnError) {
2377 flags |= eHandleCommandFlagStopOnError;
2378 }
2379 } else if (options.m_stop_on_error == eLazyBoolYes) {
2380 flags |= eHandleCommandFlagStopOnError;
2381 }
2382
2383 if (options.GetStopOnCrash()) {
2384 if (m_command_source_flags.empty()) {
2385 // Echo command by default
2386 flags |= eHandleCommandFlagStopOnCrash;
2387 } else if (m_command_source_flags.back() &
2388 eHandleCommandFlagStopOnCrash) {
2389 flags |= eHandleCommandFlagStopOnCrash;
2390 }
2391 }
2392
2393 if (options.m_echo_commands == eLazyBoolCalculate) {
2394 if (m_command_source_flags.empty()) {
2395 // Echo command by default
2396 flags |= eHandleCommandFlagEchoCommand;
2397 } else if (m_command_source_flags.back() &
2398 eHandleCommandFlagEchoCommand) {
2399 flags |= eHandleCommandFlagEchoCommand;
2400 }
2401 } else if (options.m_echo_commands == eLazyBoolYes) {
2402 flags |= eHandleCommandFlagEchoCommand;
2403 }
2404
2405 if (options.m_print_results == eLazyBoolCalculate) {
2406 if (m_command_source_flags.empty()) {
2407 // Print output by default
2408 flags |= eHandleCommandFlagPrintResult;
2409 } else if (m_command_source_flags.back() &
2410 eHandleCommandFlagPrintResult) {
2411 flags |= eHandleCommandFlagPrintResult;
2412 }
2413 } else if (options.m_print_results == eLazyBoolYes) {
2414 flags |= eHandleCommandFlagPrintResult;
2415 }
2416
2417 if (flags & eHandleCommandFlagPrintResult) {
2418 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2419 cmd_file_path.c_str());
2420 }
2421
Adrian Prantl05097242018-04-30 16:49:04 +00002422 // Used for inheriting the right settings when "command source" might
2423 // have nested "command source" commands
Kate Stoneb9c1b512016-09-06 20:57:50 +00002424 lldb::StreamFileSP empty_stream_sp;
2425 m_command_source_flags.push_back(flags);
2426 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2427 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2428 empty_stream_sp, // Pass in an empty stream so we inherit the top
2429 // input reader output stream
2430 empty_stream_sp, // Pass in an empty stream so we inherit the top
2431 // input reader error stream
2432 flags,
2433 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2434 // or written
Zachary Turner514d8cd2016-09-23 18:06:53 +00002435 debugger.GetPrompt(), llvm::StringRef(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00002436 false, // Not multi-line
2437 debugger.GetUseColor(), 0, *this));
2438 const bool old_async_execution = debugger.GetAsyncExecution();
2439
2440 // Set synchronous execution if we are not stopping on continue
2441 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2442 debugger.SetAsyncExecution(false);
2443
2444 m_command_source_depth++;
2445
2446 debugger.RunIOHandler(io_handler_sp);
2447 if (!m_command_source_flags.empty())
2448 m_command_source_flags.pop_back();
2449 m_command_source_depth--;
2450 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2451 debugger.SetAsyncExecution(old_async_execution);
2452 } else {
2453 result.AppendErrorWithFormat(
2454 "error: an error occurred read file '%s': %s\n",
2455 cmd_file_path.c_str(), error.AsCString());
2456 result.SetStatus(eReturnStatusFailed);
2457 }
2458
2459 } else {
2460 result.AppendErrorWithFormat(
2461 "Error reading commands from file %s - file not found.\n",
2462 cmd_file.GetFilename().AsCString("<Unknown>"));
2463 result.SetStatus(eReturnStatusFailed);
2464 return;
2465 }
2466}
2467
2468ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
Jim Ingham30bac792017-07-13 19:45:54 +00002469 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
Greg Clayton79040462016-12-09 01:21:14 +00002470 if (!m_script_interpreter_sp) {
2471 if (!can_create)
2472 return nullptr;
2473 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2474 m_script_interpreter_sp =
2475 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2476 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002477 return m_script_interpreter_sp.get();
2478}
2479
2480bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2481
2482void CommandInterpreter::SetSynchronous(bool value) {
2483 m_synchronous_execution = value;
2484}
2485
2486void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002487 llvm::StringRef prefix,
2488 llvm::StringRef help_text) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002489 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002490
Zachary Turner0ac5f982016-11-08 04:12:42 +00002491 size_t line_width_max = max_columns - prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002492 if (line_width_max < 16)
Zachary Turner0ac5f982016-11-08 04:12:42 +00002493 line_width_max = help_text.size() + prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002494
Zachary Turner0ac5f982016-11-08 04:12:42 +00002495 strm.IndentMore(prefix.size());
2496 bool prefixed_yet = false;
2497 while (!help_text.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002498 // Prefix the first line, indent subsequent lines to line up
Zachary Turner0ac5f982016-11-08 04:12:42 +00002499 if (!prefixed_yet) {
2500 strm << prefix;
2501 prefixed_yet = true;
2502 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002503 strm.Indent();
Zachary Turner0ac5f982016-11-08 04:12:42 +00002504
2505 // Never print more than the maximum on one line.
2506 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2507
2508 // Always break on an explicit newline.
2509 std::size_t first_newline = this_line.find_first_of("\n");
2510
2511 // Don't break on space/tab unless the text is too long to fit on one line.
2512 std::size_t last_space = llvm::StringRef::npos;
2513 if (this_line.size() != help_text.size())
2514 last_space = this_line.find_last_of(" \t");
2515
2516 // Break at whichever condition triggered first.
2517 this_line = this_line.substr(0, std::min(first_newline, last_space));
2518 strm.PutCString(this_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002519 strm.EOL();
2520
Zachary Turner0ac5f982016-11-08 04:12:42 +00002521 // Remove whitespace / newlines after breaking.
2522 help_text = help_text.drop_front(this_line.size()).ltrim();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002523 }
Zachary Turner0ac5f982016-11-08 04:12:42 +00002524 strm.IndentLess(prefix.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002525}
2526
2527void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002528 llvm::StringRef word_text,
2529 llvm::StringRef separator,
2530 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002531 size_t max_word_len) {
2532 StreamString prefix_stream;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002533 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2534 (int)separator.size(), separator.data());
Zachary Turnerc1564272016-11-16 21:15:24 +00002535 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2536}
2537
Zachary Turner0ac5f982016-11-08 04:12:42 +00002538void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2539 llvm::StringRef separator,
2540 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002541 uint32_t max_word_len) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00002542 int indent_size = max_word_len + separator.size() + 2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002543
2544 strm.IndentMore(indent_size);
2545
2546 StreamString text_strm;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002547 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2548 text_strm << separator << " " << help_text;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002549
2550 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2551
Zachary Turnerc1564272016-11-16 21:15:24 +00002552 llvm::StringRef text = text_strm.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002553
2554 uint32_t chars_left = max_columns;
2555
Davide Italianocf8a8292017-04-14 22:36:08 +00002556 auto nextWordLength = [](llvm::StringRef S) {
2557 size_t pos = S.find_first_of(' ');
2558 return pos == llvm::StringRef::npos ? S.size() : pos;
2559 };
2560
Zachary Turnerc1564272016-11-16 21:15:24 +00002561 while (!text.empty()) {
2562 if (text.front() == '\n' ||
Jim Inghama81bd7f2017-07-27 00:18:18 +00002563 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002564 strm.EOL();
2565 strm.Indent();
Zachary Turnerc1564272016-11-16 21:15:24 +00002566 chars_left = max_columns - indent_size;
2567 if (text.front() == '\n')
2568 text = text.drop_front();
2569 else
2570 text = text.ltrim(' ');
Kate Stoneb9c1b512016-09-06 20:57:50 +00002571 } else {
Zachary Turnerc1564272016-11-16 21:15:24 +00002572 strm.PutChar(text.front());
2573 --chars_left;
2574 text = text.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002575 }
2576 }
2577
2578 strm.EOL();
2579 strm.IndentLess(indent_size);
2580}
2581
2582void CommandInterpreter::FindCommandsForApropos(
Zachary Turner067d1db2016-11-16 21:45:04 +00002583 llvm::StringRef search_word, StringList &commands_found,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002584 StringList &commands_help, CommandObject::CommandMap &command_map) {
2585 CommandObject::CommandMap::const_iterator pos;
2586
2587 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
Zachary Turner067d1db2016-11-16 21:45:04 +00002588 llvm::StringRef command_name = pos->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002589 CommandObject *cmd_obj = pos->second.get();
2590
2591 const bool search_short_help = true;
2592 const bool search_long_help = false;
2593 const bool search_syntax = false;
2594 const bool search_options = false;
Zachary Turner067d1db2016-11-16 21:45:04 +00002595 if (command_name.contains_lower(search_word) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002596 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2597 search_long_help, search_syntax,
2598 search_options)) {
2599 commands_found.AppendString(cmd_obj->GetCommandName());
2600 commands_help.AppendString(cmd_obj->GetHelp());
2601 }
2602
2603 if (cmd_obj->IsMultiwordObject()) {
2604 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2605 FindCommandsForApropos(search_word, commands_found, commands_help,
2606 cmd_multiword->GetSubcommandDictionary());
2607 }
2608 }
2609}
2610
Zachary Turner067d1db2016-11-16 21:45:04 +00002611void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002612 StringList &commands_found,
2613 StringList &commands_help,
2614 bool search_builtin_commands,
2615 bool search_user_commands,
2616 bool search_alias_commands) {
2617 CommandObject::CommandMap::const_iterator pos;
2618
2619 if (search_builtin_commands)
2620 FindCommandsForApropos(search_word, commands_found, commands_help,
2621 m_command_dict);
2622
2623 if (search_user_commands)
2624 FindCommandsForApropos(search_word, commands_found, commands_help,
2625 m_user_dict);
2626
2627 if (search_alias_commands)
2628 FindCommandsForApropos(search_word, commands_found, commands_help,
2629 m_alias_dict);
2630}
2631
2632void CommandInterpreter::UpdateExecutionContext(
2633 ExecutionContext *override_context) {
2634 if (override_context != nullptr) {
2635 m_exe_ctx_ref = *override_context;
2636 } else {
2637 const bool adopt_selected = true;
2638 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2639 adopt_selected);
2640 }
2641}
2642
2643size_t CommandInterpreter::GetProcessOutput() {
2644 // The process has stuff waiting for stderr; get it and write it out to the
2645 // appropriate place.
2646 char stdio_buffer[1024];
2647 size_t len;
2648 size_t total_bytes = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002649 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002650 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2651 if (target_sp) {
2652 ProcessSP process_sp(target_sp->GetProcessSP());
2653 if (process_sp) {
2654 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2655 error)) > 0) {
2656 size_t bytes_written = len;
2657 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2658 total_bytes += len;
2659 }
2660 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2661 error)) > 0) {
2662 size_t bytes_written = len;
2663 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2664 total_bytes += len;
2665 }
2666 }
2667 }
2668 return total_bytes;
2669}
2670
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002671void CommandInterpreter::StartHandlingCommand() {
2672 auto idle_state = CommandHandlingState::eIdle;
2673 if (m_command_state.compare_exchange_strong(
2674 idle_state, CommandHandlingState::eInProgress))
2675 lldbassert(m_iohandler_nesting_level == 0);
2676 else
2677 lldbassert(m_iohandler_nesting_level > 0);
2678 ++m_iohandler_nesting_level;
2679}
2680
2681void CommandInterpreter::FinishHandlingCommand() {
2682 lldbassert(m_iohandler_nesting_level > 0);
2683 if (--m_iohandler_nesting_level == 0) {
2684 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2685 lldbassert(prev_state != CommandHandlingState::eIdle);
2686 }
2687}
2688
2689bool CommandInterpreter::InterruptCommand() {
2690 auto in_progress = CommandHandlingState::eInProgress;
2691 return m_command_state.compare_exchange_strong(
2692 in_progress, CommandHandlingState::eInterrupted);
2693}
2694
2695bool CommandInterpreter::WasInterrupted() const {
2696 bool was_interrupted =
2697 (m_command_state == CommandHandlingState::eInterrupted);
2698 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2699 return was_interrupted;
2700}
2701
2702void CommandInterpreter::PrintCommandOutput(Stream &stream,
2703 llvm::StringRef str) {
2704 // Split the output into lines and poll for interrupt requests
2705 const char *data = str.data();
2706 size_t size = str.size();
2707 while (size > 0 && !WasInterrupted()) {
2708 size_t chunk_size = 0;
2709 for (; chunk_size < size; ++chunk_size) {
2710 lldbassert(data[chunk_size] != '\0');
2711 if (data[chunk_size] == '\n') {
2712 ++chunk_size;
2713 break;
2714 }
2715 }
2716 chunk_size = stream.Write(data, chunk_size);
2717 lldbassert(size >= chunk_size);
2718 data += chunk_size;
2719 size -= chunk_size;
2720 }
2721 if (size > 0) {
2722 stream.Printf("\n... Interrupted.\n");
2723 }
2724}
2725
Kate Stoneb9c1b512016-09-06 20:57:50 +00002726void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2727 std::string &line) {
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002728 // If we were interrupted, bail out...
2729 if (WasInterrupted())
2730 return;
2731
Kate Stoneb9c1b512016-09-06 20:57:50 +00002732 const bool is_interactive = io_handler.GetIsInteractive();
2733 if (is_interactive == false) {
2734 // When we are not interactive, don't execute blank lines. This will happen
2735 // sourcing a commands file. We don't want blank lines to repeat the
Adrian Prantl05097242018-04-30 16:49:04 +00002736 // previous command and cause any errors to occur (like redefining an
2737 // alias, get an error and stop parsing the commands file).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002738 if (line.empty())
2739 return;
2740
2741 // When using a non-interactive file handle (like when sourcing commands
Adrian Prantl05097242018-04-30 16:49:04 +00002742 // from a file) we need to echo the command out so we don't just see the
2743 // command output and no command...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002744 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2745 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2746 line.c_str());
2747 }
2748
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002749 StartHandlingCommand();
2750
Kate Stoneb9c1b512016-09-06 20:57:50 +00002751 lldb_private::CommandReturnObject result;
2752 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2753
2754 // Now emit the command output text from the command we just executed
2755 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2756 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2757 GetProcessOutput();
2758
2759 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002760 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002761 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002762 }
2763
2764 // Now emit the command error text from the command we just executed
2765 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002766 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002767 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002768 }
2769 }
2770
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002771 FinishHandlingCommand();
2772
Kate Stoneb9c1b512016-09-06 20:57:50 +00002773 switch (result.GetStatus()) {
2774 case eReturnStatusInvalid:
2775 case eReturnStatusSuccessFinishNoResult:
2776 case eReturnStatusSuccessFinishResult:
2777 case eReturnStatusStarted:
2778 break;
2779
2780 case eReturnStatusSuccessContinuingNoResult:
2781 case eReturnStatusSuccessContinuingResult:
2782 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2783 io_handler.SetIsDone(true);
2784 break;
2785
2786 case eReturnStatusFailed:
2787 m_num_errors++;
2788 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2789 io_handler.SetIsDone(true);
2790 break;
2791
2792 case eReturnStatusQuit:
2793 m_quit_requested = true;
2794 io_handler.SetIsDone(true);
2795 break;
2796 }
2797
2798 // Finally, if we're going to stop on crash, check that here:
2799 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2800 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2801 bool should_stop = false;
2802 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2803 if (target_sp) {
2804 ProcessSP process_sp(target_sp->GetProcessSP());
2805 if (process_sp) {
2806 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2807 StopReason reason = thread_sp->GetStopReason();
2808 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2809 reason == eStopReasonInstrumentation) &&
2810 !result.GetAbnormalStopWasExpected()) {
2811 should_stop = true;
2812 break;
2813 }
2814 }
2815 }
2816 }
2817 if (should_stop) {
2818 io_handler.SetIsDone(true);
2819 m_stopped_for_crash = true;
2820 }
2821 }
2822}
2823
2824bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2825 ExecutionContext exe_ctx(GetExecutionContext());
2826 Process *process = exe_ctx.GetProcessPtr();
2827
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002828 if (InterruptCommand())
2829 return true;
2830
Kate Stoneb9c1b512016-09-06 20:57:50 +00002831 if (process) {
2832 StateType state = process->GetState();
2833 if (StateIsRunningState(state)) {
2834 process->Halt();
2835 return true; // Don't do any updating when we are running
2836 }
2837 }
2838
2839 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2840 if (script_interpreter) {
2841 if (script_interpreter->Interrupt())
2842 return true;
2843 }
2844 return false;
2845}
2846
2847void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2848 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2849 void *baton) {
2850 Debugger &debugger = GetDebugger();
2851 IOHandlerSP io_handler_sp(
2852 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2853 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002854 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2855 llvm::StringRef(), // Continuation prompt
2856 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002857 debugger.GetUseColor(),
2858 0, // Don't show line numbers
2859 delegate)); // IOHandlerDelegate
2860
2861 if (io_handler_sp) {
2862 io_handler_sp->SetUserData(baton);
2863 if (asynchronously)
2864 debugger.PushIOHandler(io_handler_sp);
2865 else
2866 debugger.RunIOHandler(io_handler_sp);
2867 }
2868}
2869
2870void CommandInterpreter::GetPythonCommandsFromIOHandler(
2871 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2872 void *baton) {
2873 Debugger &debugger = GetDebugger();
2874 IOHandlerSP io_handler_sp(
2875 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2876 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002877 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2878 llvm::StringRef(), // Continuation prompt
2879 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002880 debugger.GetUseColor(),
2881 0, // Don't show line numbers
2882 delegate)); // IOHandlerDelegate
2883
2884 if (io_handler_sp) {
2885 io_handler_sp->SetUserData(baton);
2886 if (asynchronously)
2887 debugger.PushIOHandler(io_handler_sp);
2888 else
2889 debugger.RunIOHandler(io_handler_sp);
2890 }
2891}
2892
2893bool CommandInterpreter::IsActive() {
2894 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2895}
2896
2897lldb::IOHandlerSP
2898CommandInterpreter::GetIOHandler(bool force_create,
2899 CommandInterpreterRunOptions *options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002900 // Always re-create the IOHandlerEditline in case the input changed. The old
2901 // instance might have had a non-interactive input and now it does or vice
2902 // versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002903 if (force_create || !m_command_io_handler_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002904 // Always re-create the IOHandlerEditline in case the input changed. The
2905 // old instance might have had a non-interactive input and now it does or
2906 // vice versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002907 uint32_t flags = 0;
2908
2909 if (options) {
2910 if (options->m_stop_on_continue == eLazyBoolYes)
2911 flags |= eHandleCommandFlagStopOnContinue;
2912 if (options->m_stop_on_error == eLazyBoolYes)
2913 flags |= eHandleCommandFlagStopOnError;
2914 if (options->m_stop_on_crash == eLazyBoolYes)
2915 flags |= eHandleCommandFlagStopOnCrash;
2916 if (options->m_echo_commands != eLazyBoolNo)
2917 flags |= eHandleCommandFlagEchoCommand;
2918 if (options->m_print_results != eLazyBoolNo)
2919 flags |= eHandleCommandFlagPrintResult;
2920 } else {
2921 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2922 }
2923
2924 m_command_io_handler_sp.reset(new IOHandlerEditline(
2925 m_debugger, IOHandler::Type::CommandInterpreter,
2926 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2927 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002928 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002929 false, // Don't enable multiple line input, just single line commands
2930 m_debugger.GetUseColor(),
2931 0, // Don't show line numbers
2932 *this));
2933 }
2934 return m_command_io_handler_sp;
2935}
2936
2937void CommandInterpreter::RunCommandInterpreter(
2938 bool auto_handle_events, bool spawn_thread,
2939 CommandInterpreterRunOptions &options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002940 // Always re-create the command interpreter when we run it in case any file
2941 // handles have changed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002942 bool force_create = true;
2943 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2944 m_stopped_for_crash = false;
2945
2946 if (auto_handle_events)
2947 m_debugger.StartEventHandlerThread();
2948
2949 if (spawn_thread) {
2950 m_debugger.StartIOHandlerThread();
2951 } else {
2952 m_debugger.ExecuteIOHandlers();
2953
2954 if (auto_handle_events)
2955 m_debugger.StopEventHandlerThread();
2956 }
2957}
2958
2959CommandObject *
2960CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2961 CommandReturnObject &result) {
2962 std::string scratch_command(command_line); // working copy so we don't modify
2963 // command_line unless we succeed
2964 CommandObject *cmd_obj = nullptr;
2965 StreamString revised_command_line;
2966 bool wants_raw_input = false;
2967 size_t actual_cmd_name_len = 0;
2968 std::string next_word;
2969 StringList matches;
2970 bool done = false;
2971 while (!done) {
2972 char quote_char = '\0';
2973 std::string suffix;
2974 ExtractCommand(scratch_command, next_word, suffix, quote_char);
2975 if (cmd_obj == nullptr) {
2976 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002977 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00002978 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002979 bool is_real_command =
2980 (is_alias == false) ||
2981 (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
2982 if (!is_real_command) {
2983 matches.Clear();
2984 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002985 cmd_obj =
2986 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002987 revised_command_line.Printf("%s", alias_result.c_str());
2988 if (cmd_obj) {
2989 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00002990 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002991 }
2992 } else {
2993 if (!cmd_obj)
Zachary Turnera4496982016-10-05 21:14:38 +00002994 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002995 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00002996 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
2997 actual_cmd_name_len += cmd_name.size();
2998 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002999 wants_raw_input = cmd_obj->WantsRawCommandString();
3000 } else {
3001 revised_command_line.Printf("%s", next_word.c_str());
3002 }
3003 }
3004 } else {
3005 if (cmd_obj->IsMultiwordObject()) {
3006 CommandObject *sub_cmd_obj =
3007 cmd_obj->GetSubcommandObject(next_word.c_str());
3008 if (sub_cmd_obj) {
Adrian Prantl05097242018-04-30 16:49:04 +00003009 // The subcommand's name includes the parent command's name, so
3010 // restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00003011 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3012 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003013 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00003014 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003015 cmd_obj = sub_cmd_obj;
3016 wants_raw_input = cmd_obj->WantsRawCommandString();
3017 } else {
3018 if (quote_char)
3019 revised_command_line.Printf(" %c%s%s%c", quote_char,
3020 next_word.c_str(), suffix.c_str(),
3021 quote_char);
3022 else
3023 revised_command_line.Printf(" %s%s", next_word.c_str(),
3024 suffix.c_str());
3025 done = true;
3026 }
3027 } else {
3028 if (quote_char)
3029 revised_command_line.Printf(" %c%s%s%c", quote_char,
3030 next_word.c_str(), suffix.c_str(),
3031 quote_char);
3032 else
3033 revised_command_line.Printf(" %s%s", next_word.c_str(),
3034 suffix.c_str());
3035 done = true;
3036 }
3037 }
3038
3039 if (cmd_obj == nullptr) {
3040 const size_t num_matches = matches.GetSize();
3041 if (matches.GetSize() > 1) {
3042 StreamString error_msg;
3043 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3044 next_word.c_str());
3045
3046 for (uint32_t i = 0; i < num_matches; ++i) {
3047 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3048 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003049 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003050 } else {
3051 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003052 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003053 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3054 next_word.c_str());
3055 }
3056 result.SetStatus(eReturnStatusFailed);
3057 return nullptr;
3058 }
3059
3060 if (cmd_obj->IsMultiwordObject()) {
3061 if (!suffix.empty()) {
3062 result.AppendErrorWithFormat(
3063 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3064 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003065 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003066 next_word.empty() ? "" : next_word.c_str(),
3067 next_word.empty() ? " -- " : " ", suffix.c_str());
3068 result.SetStatus(eReturnStatusFailed);
3069 return nullptr;
3070 }
3071 } else {
3072 // If we found a normal command, we are done
3073 done = true;
3074 if (!suffix.empty()) {
3075 switch (suffix[0]) {
3076 case '/':
3077 // GDB format suffixes
3078 {
3079 Options *command_options = cmd_obj->GetOptions();
3080 if (command_options &&
3081 command_options->SupportsLongOption("gdb-format")) {
3082 std::string gdb_format_option("--gdb-format=");
3083 gdb_format_option += (suffix.c_str() + 1);
3084
Zachary Turnerc1564272016-11-16 21:15:24 +00003085 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003086 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3087 if (arg_terminator_idx != std::string::npos) {
3088 // Insert the gdb format option before the "--" that terminates
3089 // options
3090 gdb_format_option.append(1, ' ');
3091 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003092 revised_command_line.Clear();
3093 revised_command_line.PutCString(cmd);
3094 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003095 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3096
3097 if (wants_raw_input &&
3098 FindArgumentTerminator(cmd) == std::string::npos)
3099 revised_command_line.PutCString(" --");
3100 } else {
3101 result.AppendErrorWithFormat(
3102 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003103 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003104 result.SetStatus(eReturnStatusFailed);
3105 return nullptr;
3106 }
3107 }
3108 break;
3109
3110 default:
3111 result.AppendErrorWithFormat(
3112 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3113 result.SetStatus(eReturnStatusFailed);
3114 return nullptr;
3115 }
3116 }
3117 }
3118 if (scratch_command.empty())
3119 done = true;
3120 }
3121
3122 if (!scratch_command.empty())
3123 revised_command_line.Printf(" %s", scratch_command.c_str());
3124
3125 if (cmd_obj != NULL)
Zachary Turnerc1564272016-11-16 21:15:24 +00003126 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003127
3128 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003129}