blob: 8f309512172f95b203822970c6a9bb823edf2cd8 [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 =
546 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
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;
1680 int num_matches;
1681 int cursor_index = 0;
1682 int cursor_char_position = strlen(command_args.GetArgumentAtIndex(0));
1683 bool word_complete;
1684 num_matches = HandleCompletionMatches(command_args, cursor_index,
1685 cursor_char_position, 0, -1,
1686 word_complete, matches);
1687
1688 if (num_matches > 0) {
1689 std::string error_msg;
1690 error_msg.assign("ambiguous command '");
1691 error_msg.append(command_args.GetArgumentAtIndex(0));
1692 error_msg.append("'.");
1693
1694 error_msg.append(" Possible completions:");
1695 for (int i = 0; i < num_matches; i++) {
1696 error_msg.append("\n\t");
1697 error_msg.append(matches.GetStringAtIndex(i));
1698 }
1699 error_msg.append("\n");
1700 result.AppendRawError(error_msg.c_str());
1701 } else
1702 result.AppendErrorWithFormat("Unrecognized command '%s'.\n",
1703 command_args.GetArgumentAtIndex(0));
1704
1705 result.SetStatus(eReturnStatusFailed);
1706 }
1707
1708 if (log)
1709 log->Printf("HandleCommand, command %s",
1710 (result.Succeeded() ? "succeeded" : "did not succeed"));
1711
1712 return result.Succeeded();
1713}
1714
1715int CommandInterpreter::HandleCompletionMatches(
1716 Args &parsed_line, int &cursor_index, int &cursor_char_position,
1717 int match_start_point, int max_return_elements, bool &word_complete,
1718 StringList &matches) {
1719 int num_command_matches = 0;
1720 bool look_for_subcommand = false;
1721
1722 // For any of the command completions a unique match will be a complete word.
1723 word_complete = true;
1724
1725 if (cursor_index == -1) {
1726 // We got nothing on the command line, so return the list of commands
1727 bool include_aliases = true;
1728 num_command_matches =
1729 GetCommandNamesMatchingPartialString("", include_aliases, matches);
1730 } else if (cursor_index == 0) {
1731 // The cursor is in the first argument, so just do a lookup in the
1732 // dictionary.
1733 CommandObject *cmd_obj =
1734 GetCommandObject(parsed_line.GetArgumentAtIndex(0), &matches);
1735 num_command_matches = matches.GetSize();
1736
1737 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
1738 matches.GetStringAtIndex(0) != nullptr &&
1739 strcmp(parsed_line.GetArgumentAtIndex(0),
1740 matches.GetStringAtIndex(0)) == 0) {
1741 if (parsed_line.GetArgumentCount() == 1) {
1742 word_complete = true;
1743 } else {
1744 look_for_subcommand = true;
1745 num_command_matches = 0;
1746 matches.DeleteStringAtIndex(0);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001747 parsed_line.AppendArgument(llvm::StringRef());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001748 cursor_index++;
1749 cursor_char_position = 0;
1750 }
1751 }
1752 }
1753
1754 if (cursor_index > 0 || look_for_subcommand) {
1755 // We are completing further on into a commands arguments, so find the
Adrian Prantl05097242018-04-30 16:49:04 +00001756 // command and tell it to complete the command. First see if there is a
1757 // matching initial command:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001758 CommandObject *command_object =
1759 GetCommandObject(parsed_line.GetArgumentAtIndex(0));
1760 if (command_object == nullptr) {
1761 return 0;
1762 } else {
1763 parsed_line.Shift();
1764 cursor_index--;
1765 num_command_matches = command_object->HandleCompletion(
1766 parsed_line, cursor_index, cursor_char_position, match_start_point,
1767 max_return_elements, word_complete, matches);
1768 }
1769 }
1770
1771 return num_command_matches;
1772}
1773
1774int CommandInterpreter::HandleCompletion(
1775 const char *current_line, const char *cursor, const char *last_char,
1776 int match_start_point, int max_return_elements, StringList &matches) {
Adrian Prantl05097242018-04-30 16:49:04 +00001777 // We parse the argument up to the cursor, so the last argument in
1778 // parsed_line is the one containing the cursor, and the cursor is after the
1779 // last character.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001780
1781 Args parsed_line(llvm::StringRef(current_line, last_char - current_line));
1782 Args partial_parsed_line(
1783 llvm::StringRef(current_line, cursor - current_line));
1784
1785 // Don't complete comments, and if the line we are completing is just the
Adrian Prantl05097242018-04-30 16:49:04 +00001786 // history repeat character, substitute the appropriate history line.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001787 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1788 if (first_arg) {
1789 if (first_arg[0] == m_comment_char)
1790 return 0;
1791 else if (first_arg[0] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001792 if (auto hist_str = m_command_history.FindString(first_arg)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001793 matches.Clear();
Zachary Turner53877af2016-11-18 23:22:42 +00001794 matches.InsertStringAtIndex(0, *hist_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001795 return -2;
1796 } else
1797 return 0;
1798 }
1799 }
1800
1801 int num_args = partial_parsed_line.GetArgumentCount();
1802 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1803 int cursor_char_position;
1804
1805 if (cursor_index == -1)
1806 cursor_char_position = 0;
1807 else
1808 cursor_char_position =
1809 strlen(partial_parsed_line.GetArgumentAtIndex(cursor_index));
1810
1811 if (cursor > current_line && cursor[-1] == ' ') {
1812 // We are just after a space. If we are in an argument, then we will
Adrian Prantl05097242018-04-30 16:49:04 +00001813 // continue parsing, but if we are between arguments, then we have to
1814 // complete whatever the next element would be. We can distinguish the two
1815 // cases because if we are in an argument (e.g. because the space is
Kate Stoneb9c1b512016-09-06 20:57:50 +00001816 // protected by a quote) then the space will also be in the parsed
1817 // argument...
1818
1819 const char *current_elem =
1820 partial_parsed_line.GetArgumentAtIndex(cursor_index);
1821 if (cursor_char_position == 0 ||
1822 current_elem[cursor_char_position - 1] != ' ') {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001823 parsed_line.InsertArgumentAtIndex(cursor_index + 1, llvm::StringRef(),
1824 '\0');
Kate Stoneb9c1b512016-09-06 20:57:50 +00001825 cursor_index++;
1826 cursor_char_position = 0;
1827 }
1828 }
1829
1830 int num_command_matches;
1831
1832 matches.Clear();
1833
1834 // Only max_return_elements == -1 is supported at present:
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001835 lldbassert(max_return_elements == -1);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001836 bool word_complete;
1837 num_command_matches = HandleCompletionMatches(
1838 parsed_line, cursor_index, cursor_char_position, match_start_point,
1839 max_return_elements, word_complete, matches);
1840
1841 if (num_command_matches <= 0)
1842 return num_command_matches;
1843
1844 if (num_args == 0) {
1845 // If we got an empty string, insert nothing.
1846 matches.InsertStringAtIndex(0, "");
1847 } else {
1848 // Now figure out if there is a common substring, and if so put that in
Adrian Prantl05097242018-04-30 16:49:04 +00001849 // element 0, otherwise put an empty string in element 0.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001850 std::string command_partial_str;
1851 if (cursor_index >= 0)
Zachary Turnerd6a24752016-11-22 17:10:15 +00001852 command_partial_str =
1853 parsed_line[cursor_index].ref.take_front(cursor_char_position);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001854
1855 std::string common_prefix;
1856 matches.LongestCommonPrefix(common_prefix);
1857 const size_t partial_name_len = command_partial_str.size();
1858 common_prefix.erase(0, partial_name_len);
1859
Adrian Prantl05097242018-04-30 16:49:04 +00001860 // If we matched a unique single command, add a space... Only do this if
1861 // the completer told us this was a complete word, however...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001862 if (num_command_matches == 1 && word_complete) {
Zachary Turnerd6a24752016-11-22 17:10:15 +00001863 char quote_char = parsed_line[cursor_index].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001864 common_prefix =
1865 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1866 if (quote_char != '\0')
1867 common_prefix.push_back(quote_char);
1868 common_prefix.push_back(' ');
1869 }
1870 matches.InsertStringAtIndex(0, common_prefix.c_str());
1871 }
1872 return num_command_matches;
1873}
1874
1875CommandInterpreter::~CommandInterpreter() {}
1876
Zachary Turner514d8cd2016-09-23 18:06:53 +00001877void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001878 EventSP prompt_change_event_sp(
1879 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1880 ;
1881 BroadcastEvent(prompt_change_event_sp);
1882 if (m_command_io_handler_sp)
1883 m_command_io_handler_sp->SetPrompt(new_prompt);
1884}
1885
Zachary Turner7a120c82016-11-13 03:05:58 +00001886bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001887 // Check AutoConfirm first:
1888 if (m_debugger.GetAutoConfirm())
1889 return default_answer;
1890
1891 IOHandlerConfirm *confirm =
1892 new IOHandlerConfirm(m_debugger, message, default_answer);
1893 IOHandlerSP io_handler_sp(confirm);
1894 m_debugger.RunIOHandler(io_handler_sp);
1895 return confirm->GetResponse();
1896}
1897
Zachary Turnera483f572016-10-05 21:14:49 +00001898const CommandAlias *
1899CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001900 OptionArgVectorSP ret_val;
1901
Zachary Turnera483f572016-10-05 21:14:49 +00001902 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001903 if (pos != m_alias_dict.end())
1904 return (CommandAlias *)pos->second.get();
1905
1906 return nullptr;
1907}
1908
Zachary Turnera4496982016-10-05 21:14:38 +00001909bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001910
Zachary Turnera4496982016-10-05 21:14:38 +00001911bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001912
Zachary Turnera4496982016-10-05 21:14:38 +00001913bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001914
Zachary Turnera4496982016-10-05 21:14:38 +00001915bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001916
1917void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1918 const char *alias_name,
1919 Args &cmd_args,
1920 std::string &raw_input_string,
1921 CommandReturnObject &result) {
1922 OptionArgVectorSP option_arg_vector_sp =
1923 GetAlias(alias_name)->GetOptionArguments();
1924
1925 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1926
1927 // Make sure that the alias name is the 0th element in cmd_args
1928 std::string alias_name_str = alias_name;
1929 if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)
Zachary Turner5c725f32016-09-19 21:56:59 +00001930 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001931
1932 Args new_args(alias_cmd_obj->GetCommandName());
1933 if (new_args.GetArgumentCount() == 2)
1934 new_args.Shift();
1935
1936 if (option_arg_vector_sp.get()) {
1937 if (wants_raw_input) {
1938 // We have a command that both has command options and takes raw input.
Adrian Prantl05097242018-04-30 16:49:04 +00001939 // Make *sure* it has a " -- " in the right place in the
1940 // raw_input_string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001941 size_t pos = raw_input_string.find(" -- ");
1942 if (pos == std::string::npos) {
1943 // None found; assume it goes at the beginning of the raw input string
1944 raw_input_string.insert(0, " -- ");
1945 }
1946 }
1947
1948 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1949 const size_t old_size = cmd_args.GetArgumentCount();
1950 std::vector<bool> used(old_size + 1, false);
1951
1952 used[0] = true;
1953
Zachary Turner5c28c662016-10-03 23:20:36 +00001954 int value_type;
1955 std::string option;
1956 std::string value;
1957 for (const auto &option_entry : *option_arg_vector) {
1958 std::tie(option, value_type, value) = option_entry;
1959 if (option == "<argument>") {
1960 if (!wants_raw_input || (value != "--")) {
1961 // Since we inserted this above, make sure we don't insert it twice
1962 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001963 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001964 continue;
1965 }
1966
1967 if (value_type != OptionParser::eOptionalArgument)
1968 new_args.AppendArgument(option);
1969
1970 if (value == "<no-argument>")
1971 continue;
1972
1973 int index = GetOptionArgumentPosition(value.c_str());
1974 if (index == 0) {
1975 // value was NOT a positional argument; must be a real value
1976 if (value_type != OptionParser::eOptionalArgument)
1977 new_args.AppendArgument(value);
1978 else {
1979 char buffer[255];
1980 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1981 value.c_str());
1982 new_args.AppendArgument(llvm::StringRef(buffer));
1983 }
1984
1985 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1986 result.AppendErrorWithFormat("Not enough arguments provided; you "
1987 "need at least %d arguments to use "
1988 "this alias.\n",
1989 index);
1990 result.SetStatus(eReturnStatusFailed);
1991 return;
1992 } else {
1993 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1994 size_t strpos =
1995 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1996 if (strpos != std::string::npos) {
1997 raw_input_string = raw_input_string.erase(
1998 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1999 }
2000
2001 if (value_type != OptionParser::eOptionalArgument)
2002 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2003 else {
2004 char buffer[255];
2005 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2006 cmd_args.GetArgumentAtIndex(index));
2007 new_args.AppendArgument(buffer);
2008 }
2009 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002010 }
2011 }
2012
Zachary Turner97d2c402016-10-05 23:40:23 +00002013 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00002014 if (!used[entry.index()] && !wants_raw_input)
2015 new_args.AppendArgument(entry.value().ref);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002016 }
2017
2018 cmd_args.Clear();
2019 cmd_args.SetArguments(new_args.GetArgumentCount(),
2020 new_args.GetConstArgumentVector());
2021 } else {
2022 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2023 // This alias was not created with any options; nothing further needs to be
Adrian Prantl05097242018-04-30 16:49:04 +00002024 // done, unless it is a command that wants raw input, in which case we need
2025 // to clear the rest of the data from cmd_args, since its in the raw input
2026 // string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002027 if (wants_raw_input) {
2028 cmd_args.Clear();
2029 cmd_args.SetArguments(new_args.GetArgumentCount(),
2030 new_args.GetConstArgumentVector());
2031 }
2032 return;
2033 }
2034
2035 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2036 return;
2037}
2038
2039int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2040 int position = 0; // Any string that isn't an argument position, i.e. '%'
2041 // followed by an integer, gets a position
2042 // of zero.
2043
2044 const char *cptr = in_string;
2045
2046 // Does it start with '%'
2047 if (cptr[0] == '%') {
2048 ++cptr;
2049
2050 // Is the rest of it entirely digits?
2051 if (isdigit(cptr[0])) {
2052 const char *start = cptr;
2053 while (isdigit(cptr[0]))
2054 ++cptr;
2055
Adrian Prantl05097242018-04-30 16:49:04 +00002056 // We've gotten to the end of the digits; are we at the end of the
2057 // string?
Kate Stoneb9c1b512016-09-06 20:57:50 +00002058 if (cptr[0] == '\0')
2059 position = atoi(start);
2060 }
2061 }
2062
2063 return position;
2064}
2065
2066void CommandInterpreter::SourceInitFile(bool in_cwd,
2067 CommandReturnObject &result) {
2068 FileSpec init_file;
2069 if (in_cwd) {
2070 ExecutionContext exe_ctx(GetExecutionContext());
2071 Target *target = exe_ctx.GetTargetPtr();
2072 if (target) {
2073 // In the current working directory we don't load any program specific
2074 // .lldbinit files, we only look for a ".lldbinit" file.
2075 if (m_skip_lldbinit_files)
2076 return;
2077
2078 LoadCWDlldbinitFile should_load =
2079 target->TargetProperties::GetLoadCWDlldbinitFile();
2080 if (should_load == eLoadCWDlldbinitWarn) {
2081 FileSpec dot_lldb(".lldbinit", true);
2082 llvm::SmallString<64> home_dir_path;
2083 llvm::sys::path::home_directory(home_dir_path);
2084 FileSpec homedir_dot_lldb(home_dir_path.c_str(), false);
2085 homedir_dot_lldb.AppendPathComponent(".lldbinit");
2086 homedir_dot_lldb.ResolvePath();
2087 if (dot_lldb.Exists() &&
2088 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2089 result.AppendErrorWithFormat(
2090 "There is a .lldbinit file in the current directory which is not "
2091 "being read.\n"
2092 "To silence this warning without sourcing in the local "
2093 ".lldbinit,\n"
2094 "add the following to the lldbinit file in your home directory:\n"
2095 " settings set target.load-cwd-lldbinit false\n"
2096 "To allow lldb to source .lldbinit files in the current working "
2097 "directory,\n"
2098 "set the value of this variable to true. Only do so if you "
2099 "understand and\n"
2100 "accept the security risk.");
2101 result.SetStatus(eReturnStatusFailed);
2102 return;
2103 }
2104 } else if (should_load == eLoadCWDlldbinitTrue) {
2105 init_file.SetFile("./.lldbinit", true);
2106 }
2107 }
2108 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002109 // If we aren't looking in the current working directory we are looking in
2110 // the home directory. We will first see if there is an application
2111 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a "-"
2112 // and the name of the program. If this file doesn't exist, we fall back to
2113 // just the "~/.lldbinit" file. We also obey any requests to not load the
2114 // init files.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002115 llvm::SmallString<64> home_dir_path;
2116 llvm::sys::path::home_directory(home_dir_path);
2117 FileSpec profilePath(home_dir_path.c_str(), false);
2118 profilePath.AppendPathComponent(".lldbinit");
2119 std::string init_file_path = profilePath.GetPath();
2120
2121 if (m_skip_app_init_files == false) {
2122 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2123 const char *program_name = program_file_spec.GetFilename().AsCString();
2124
2125 if (program_name) {
2126 char program_init_file_name[PATH_MAX];
2127 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2128 "%s-%s", init_file_path.c_str(), program_name);
2129 init_file.SetFile(program_init_file_name, true);
2130 if (!init_file.Exists())
2131 init_file.Clear();
2132 }
2133 }
2134
2135 if (!init_file && !m_skip_lldbinit_files)
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002136 init_file.SetFile(init_file_path, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002137 }
2138
2139 // If the file exists, tell HandleCommand to 'source' it; this will do the
Adrian Prantl05097242018-04-30 16:49:04 +00002140 // actual broadcasting of the commands back to any appropriate listener (see
Kate Stoneb9c1b512016-09-06 20:57:50 +00002141 // CommandObjectSource::Execute for more details).
2142
2143 if (init_file.Exists()) {
2144 const bool saved_batch = SetBatchCommandMode(true);
2145 CommandInterpreterRunOptions options;
2146 options.SetSilent(true);
2147 options.SetStopOnError(false);
2148 options.SetStopOnContinue(true);
2149
2150 HandleCommandsFromFile(init_file,
2151 nullptr, // Execution context
2152 options, result);
2153 SetBatchCommandMode(saved_batch);
2154 } else {
2155 // nothing to be done if the file doesn't exist
2156 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2157 }
2158}
2159
2160const char *CommandInterpreter::GetCommandPrefix() {
2161 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2162 return prefix == NULL ? "" : prefix;
2163}
2164
2165PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2166 PlatformSP platform_sp;
2167 if (prefer_target_platform) {
2168 ExecutionContext exe_ctx(GetExecutionContext());
2169 Target *target = exe_ctx.GetTargetPtr();
2170 if (target)
2171 platform_sp = target->GetPlatform();
2172 }
2173
2174 if (!platform_sp)
2175 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2176 return platform_sp;
2177}
2178
2179void CommandInterpreter::HandleCommands(const StringList &commands,
2180 ExecutionContext *override_context,
2181 CommandInterpreterRunOptions &options,
2182 CommandReturnObject &result) {
2183 size_t num_lines = commands.GetSize();
2184
2185 // If we are going to continue past a "continue" then we need to run the
Adrian Prantl05097242018-04-30 16:49:04 +00002186 // commands synchronously. Make sure you reset this value anywhere you return
2187 // from the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002188
2189 bool old_async_execution = m_debugger.GetAsyncExecution();
2190
2191 // If we've been given an execution context, set it at the start, but don't
Adrian Prantl05097242018-04-30 16:49:04 +00002192 // keep resetting it or we will cause series of commands that change the
2193 // context, then do an operation that relies on that context to fail.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002194
2195 if (override_context != nullptr)
2196 UpdateExecutionContext(override_context);
2197
2198 if (!options.GetStopOnContinue()) {
2199 m_debugger.SetAsyncExecution(false);
2200 }
2201
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002202 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002203 const char *cmd = commands.GetStringAtIndex(idx);
2204 if (cmd[0] == '\0')
2205 continue;
2206
2207 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002208 // TODO: Add Stream support.
2209 result.AppendMessageWithFormat("%s %s\n",
2210 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002211 }
2212
2213 CommandReturnObject tmp_result;
2214 // If override_context is not NULL, pass no_context_switching = true for
2215 // HandleCommand() since we updated our context already.
2216
2217 // We might call into a regex or alias command, in which case the
Adrian Prantl05097242018-04-30 16:49:04 +00002218 // add_to_history will get lost. This m_command_source_depth dingus is the
2219 // way we turn off adding to the history in that case, so set it up here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002220 if (!options.GetAddToHistory())
2221 m_command_source_depth++;
2222 bool success =
2223 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2224 nullptr, /* override_context */
2225 true, /* repeat_on_empty_command */
2226 override_context != nullptr /* no_context_switching */);
2227 if (!options.GetAddToHistory())
2228 m_command_source_depth--;
2229
2230 if (options.GetPrintResults()) {
2231 if (tmp_result.Succeeded())
Zachary Turner03c9f362016-11-14 23:23:31 +00002232 result.AppendMessage(tmp_result.GetOutputData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002233 }
2234
2235 if (!success || !tmp_result.Succeeded()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002236 llvm::StringRef error_msg = tmp_result.GetErrorData();
2237 if (error_msg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002238 error_msg = "<unknown error>.\n";
2239 if (options.GetStopOnError()) {
2240 result.AppendErrorWithFormat(
2241 "Aborting reading of commands after command #%" PRIu64
2242 ": '%s' failed with %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00002243 (uint64_t)idx, cmd, error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002244 result.SetStatus(eReturnStatusFailed);
2245 m_debugger.SetAsyncExecution(old_async_execution);
2246 return;
2247 } else if (options.GetPrintResults()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002248 result.AppendMessageWithFormat(
2249 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2250 error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002251 }
2252 }
2253
2254 if (result.GetImmediateOutputStream())
2255 result.GetImmediateOutputStream()->Flush();
2256
2257 if (result.GetImmediateErrorStream())
2258 result.GetImmediateErrorStream()->Flush();
2259
Adrian Prantl05097242018-04-30 16:49:04 +00002260 // N.B. Can't depend on DidChangeProcessState, because the state coming
2261 // into the command execution could be running (for instance in Breakpoint
2262 // Commands. So we check the return value to see if it is has running in
2263 // it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002264 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2265 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2266 if (options.GetStopOnContinue()) {
2267 // If we caused the target to proceed, and we're going to stop in that
Adrian Prantl05097242018-04-30 16:49:04 +00002268 // case, set the status in our real result before returning. This is
2269 // an error if the continue was not the last command in the set of
2270 // commands to be run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002271 if (idx != num_lines - 1)
2272 result.AppendErrorWithFormat(
2273 "Aborting reading of commands after command #%" PRIu64
2274 ": '%s' continued the target.\n",
2275 (uint64_t)idx + 1, cmd);
2276 else
2277 result.AppendMessageWithFormat("Command #%" PRIu64
2278 " '%s' continued the target.\n",
2279 (uint64_t)idx + 1, cmd);
2280
2281 result.SetStatus(tmp_result.GetStatus());
2282 m_debugger.SetAsyncExecution(old_async_execution);
2283
2284 return;
2285 }
2286 }
2287
2288 // Also check for "stop on crash here:
2289 bool should_stop = false;
2290 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2291 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2292 if (target_sp) {
2293 ProcessSP process_sp(target_sp->GetProcessSP());
2294 if (process_sp) {
2295 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2296 StopReason reason = thread_sp->GetStopReason();
2297 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2298 reason == eStopReasonInstrumentation) {
2299 should_stop = true;
2300 break;
2301 }
2302 }
2303 }
2304 }
2305 if (should_stop) {
2306 if (idx != num_lines - 1)
2307 result.AppendErrorWithFormat(
2308 "Aborting reading of commands after command #%" PRIu64
2309 ": '%s' stopped with a signal or exception.\n",
2310 (uint64_t)idx + 1, cmd);
2311 else
2312 result.AppendMessageWithFormat(
2313 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2314 (uint64_t)idx + 1, cmd);
2315
2316 result.SetStatus(tmp_result.GetStatus());
2317 m_debugger.SetAsyncExecution(old_async_execution);
2318
2319 return;
2320 }
2321 }
2322 }
2323
2324 result.SetStatus(eReturnStatusSuccessFinishResult);
2325 m_debugger.SetAsyncExecution(old_async_execution);
2326
2327 return;
2328}
2329
2330// Make flags that we can pass into the IOHandler so our delegates can do the
2331// right thing
2332enum {
2333 eHandleCommandFlagStopOnContinue = (1u << 0),
2334 eHandleCommandFlagStopOnError = (1u << 1),
2335 eHandleCommandFlagEchoCommand = (1u << 2),
2336 eHandleCommandFlagPrintResult = (1u << 3),
2337 eHandleCommandFlagStopOnCrash = (1u << 4)
2338};
2339
2340void CommandInterpreter::HandleCommandsFromFile(
2341 FileSpec &cmd_file, ExecutionContext *context,
2342 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2343 if (cmd_file.Exists()) {
2344 StreamFileSP input_file_sp(new StreamFile());
2345
2346 std::string cmd_file_path = cmd_file.GetPath();
Zachary Turner97206d52017-05-12 04:51:55 +00002347 Status error = input_file_sp->GetFile().Open(cmd_file_path.c_str(),
2348 File::eOpenOptionRead);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002349
2350 if (error.Success()) {
2351 Debugger &debugger = GetDebugger();
2352
2353 uint32_t flags = 0;
2354
2355 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2356 if (m_command_source_flags.empty()) {
2357 // Stop on continue by default
2358 flags |= eHandleCommandFlagStopOnContinue;
2359 } else if (m_command_source_flags.back() &
2360 eHandleCommandFlagStopOnContinue) {
2361 flags |= eHandleCommandFlagStopOnContinue;
2362 }
2363 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2364 flags |= eHandleCommandFlagStopOnContinue;
2365 }
2366
2367 if (options.m_stop_on_error == eLazyBoolCalculate) {
2368 if (m_command_source_flags.empty()) {
2369 if (GetStopCmdSourceOnError())
2370 flags |= eHandleCommandFlagStopOnError;
2371 } else if (m_command_source_flags.back() &
2372 eHandleCommandFlagStopOnError) {
2373 flags |= eHandleCommandFlagStopOnError;
2374 }
2375 } else if (options.m_stop_on_error == eLazyBoolYes) {
2376 flags |= eHandleCommandFlagStopOnError;
2377 }
2378
2379 if (options.GetStopOnCrash()) {
2380 if (m_command_source_flags.empty()) {
2381 // Echo command by default
2382 flags |= eHandleCommandFlagStopOnCrash;
2383 } else if (m_command_source_flags.back() &
2384 eHandleCommandFlagStopOnCrash) {
2385 flags |= eHandleCommandFlagStopOnCrash;
2386 }
2387 }
2388
2389 if (options.m_echo_commands == eLazyBoolCalculate) {
2390 if (m_command_source_flags.empty()) {
2391 // Echo command by default
2392 flags |= eHandleCommandFlagEchoCommand;
2393 } else if (m_command_source_flags.back() &
2394 eHandleCommandFlagEchoCommand) {
2395 flags |= eHandleCommandFlagEchoCommand;
2396 }
2397 } else if (options.m_echo_commands == eLazyBoolYes) {
2398 flags |= eHandleCommandFlagEchoCommand;
2399 }
2400
2401 if (options.m_print_results == eLazyBoolCalculate) {
2402 if (m_command_source_flags.empty()) {
2403 // Print output by default
2404 flags |= eHandleCommandFlagPrintResult;
2405 } else if (m_command_source_flags.back() &
2406 eHandleCommandFlagPrintResult) {
2407 flags |= eHandleCommandFlagPrintResult;
2408 }
2409 } else if (options.m_print_results == eLazyBoolYes) {
2410 flags |= eHandleCommandFlagPrintResult;
2411 }
2412
2413 if (flags & eHandleCommandFlagPrintResult) {
2414 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2415 cmd_file_path.c_str());
2416 }
2417
Adrian Prantl05097242018-04-30 16:49:04 +00002418 // Used for inheriting the right settings when "command source" might
2419 // have nested "command source" commands
Kate Stoneb9c1b512016-09-06 20:57:50 +00002420 lldb::StreamFileSP empty_stream_sp;
2421 m_command_source_flags.push_back(flags);
2422 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2423 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2424 empty_stream_sp, // Pass in an empty stream so we inherit the top
2425 // input reader output stream
2426 empty_stream_sp, // Pass in an empty stream so we inherit the top
2427 // input reader error stream
2428 flags,
2429 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2430 // or written
Zachary Turner514d8cd2016-09-23 18:06:53 +00002431 debugger.GetPrompt(), llvm::StringRef(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00002432 false, // Not multi-line
2433 debugger.GetUseColor(), 0, *this));
2434 const bool old_async_execution = debugger.GetAsyncExecution();
2435
2436 // Set synchronous execution if we are not stopping on continue
2437 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2438 debugger.SetAsyncExecution(false);
2439
2440 m_command_source_depth++;
2441
2442 debugger.RunIOHandler(io_handler_sp);
2443 if (!m_command_source_flags.empty())
2444 m_command_source_flags.pop_back();
2445 m_command_source_depth--;
2446 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2447 debugger.SetAsyncExecution(old_async_execution);
2448 } else {
2449 result.AppendErrorWithFormat(
2450 "error: an error occurred read file '%s': %s\n",
2451 cmd_file_path.c_str(), error.AsCString());
2452 result.SetStatus(eReturnStatusFailed);
2453 }
2454
2455 } else {
2456 result.AppendErrorWithFormat(
2457 "Error reading commands from file %s - file not found.\n",
2458 cmd_file.GetFilename().AsCString("<Unknown>"));
2459 result.SetStatus(eReturnStatusFailed);
2460 return;
2461 }
2462}
2463
2464ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
Jim Ingham30bac792017-07-13 19:45:54 +00002465 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
Greg Clayton79040462016-12-09 01:21:14 +00002466 if (!m_script_interpreter_sp) {
2467 if (!can_create)
2468 return nullptr;
2469 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2470 m_script_interpreter_sp =
2471 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2472 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002473 return m_script_interpreter_sp.get();
2474}
2475
2476bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2477
2478void CommandInterpreter::SetSynchronous(bool value) {
2479 m_synchronous_execution = value;
2480}
2481
2482void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002483 llvm::StringRef prefix,
2484 llvm::StringRef help_text) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002485 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002486
Zachary Turner0ac5f982016-11-08 04:12:42 +00002487 size_t line_width_max = max_columns - prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002488 if (line_width_max < 16)
Zachary Turner0ac5f982016-11-08 04:12:42 +00002489 line_width_max = help_text.size() + prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002490
Zachary Turner0ac5f982016-11-08 04:12:42 +00002491 strm.IndentMore(prefix.size());
2492 bool prefixed_yet = false;
2493 while (!help_text.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002494 // Prefix the first line, indent subsequent lines to line up
Zachary Turner0ac5f982016-11-08 04:12:42 +00002495 if (!prefixed_yet) {
2496 strm << prefix;
2497 prefixed_yet = true;
2498 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002499 strm.Indent();
Zachary Turner0ac5f982016-11-08 04:12:42 +00002500
2501 // Never print more than the maximum on one line.
2502 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2503
2504 // Always break on an explicit newline.
2505 std::size_t first_newline = this_line.find_first_of("\n");
2506
2507 // Don't break on space/tab unless the text is too long to fit on one line.
2508 std::size_t last_space = llvm::StringRef::npos;
2509 if (this_line.size() != help_text.size())
2510 last_space = this_line.find_last_of(" \t");
2511
2512 // Break at whichever condition triggered first.
2513 this_line = this_line.substr(0, std::min(first_newline, last_space));
2514 strm.PutCString(this_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002515 strm.EOL();
2516
Zachary Turner0ac5f982016-11-08 04:12:42 +00002517 // Remove whitespace / newlines after breaking.
2518 help_text = help_text.drop_front(this_line.size()).ltrim();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002519 }
Zachary Turner0ac5f982016-11-08 04:12:42 +00002520 strm.IndentLess(prefix.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002521}
2522
2523void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002524 llvm::StringRef word_text,
2525 llvm::StringRef separator,
2526 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002527 size_t max_word_len) {
2528 StreamString prefix_stream;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002529 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2530 (int)separator.size(), separator.data());
Zachary Turnerc1564272016-11-16 21:15:24 +00002531 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2532}
2533
Zachary Turner0ac5f982016-11-08 04:12:42 +00002534void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2535 llvm::StringRef separator,
2536 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002537 uint32_t max_word_len) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00002538 int indent_size = max_word_len + separator.size() + 2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002539
2540 strm.IndentMore(indent_size);
2541
2542 StreamString text_strm;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002543 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2544 text_strm << separator << " " << help_text;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002545
2546 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2547
Zachary Turnerc1564272016-11-16 21:15:24 +00002548 llvm::StringRef text = text_strm.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002549
2550 uint32_t chars_left = max_columns;
2551
Davide Italianocf8a8292017-04-14 22:36:08 +00002552 auto nextWordLength = [](llvm::StringRef S) {
2553 size_t pos = S.find_first_of(' ');
2554 return pos == llvm::StringRef::npos ? S.size() : pos;
2555 };
2556
Zachary Turnerc1564272016-11-16 21:15:24 +00002557 while (!text.empty()) {
2558 if (text.front() == '\n' ||
Jim Inghama81bd7f2017-07-27 00:18:18 +00002559 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002560 strm.EOL();
2561 strm.Indent();
Zachary Turnerc1564272016-11-16 21:15:24 +00002562 chars_left = max_columns - indent_size;
2563 if (text.front() == '\n')
2564 text = text.drop_front();
2565 else
2566 text = text.ltrim(' ');
Kate Stoneb9c1b512016-09-06 20:57:50 +00002567 } else {
Zachary Turnerc1564272016-11-16 21:15:24 +00002568 strm.PutChar(text.front());
2569 --chars_left;
2570 text = text.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002571 }
2572 }
2573
2574 strm.EOL();
2575 strm.IndentLess(indent_size);
2576}
2577
2578void CommandInterpreter::FindCommandsForApropos(
Zachary Turner067d1db2016-11-16 21:45:04 +00002579 llvm::StringRef search_word, StringList &commands_found,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002580 StringList &commands_help, CommandObject::CommandMap &command_map) {
2581 CommandObject::CommandMap::const_iterator pos;
2582
2583 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
Zachary Turner067d1db2016-11-16 21:45:04 +00002584 llvm::StringRef command_name = pos->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002585 CommandObject *cmd_obj = pos->second.get();
2586
2587 const bool search_short_help = true;
2588 const bool search_long_help = false;
2589 const bool search_syntax = false;
2590 const bool search_options = false;
Zachary Turner067d1db2016-11-16 21:45:04 +00002591 if (command_name.contains_lower(search_word) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002592 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2593 search_long_help, search_syntax,
2594 search_options)) {
2595 commands_found.AppendString(cmd_obj->GetCommandName());
2596 commands_help.AppendString(cmd_obj->GetHelp());
2597 }
2598
2599 if (cmd_obj->IsMultiwordObject()) {
2600 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2601 FindCommandsForApropos(search_word, commands_found, commands_help,
2602 cmd_multiword->GetSubcommandDictionary());
2603 }
2604 }
2605}
2606
Zachary Turner067d1db2016-11-16 21:45:04 +00002607void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002608 StringList &commands_found,
2609 StringList &commands_help,
2610 bool search_builtin_commands,
2611 bool search_user_commands,
2612 bool search_alias_commands) {
2613 CommandObject::CommandMap::const_iterator pos;
2614
2615 if (search_builtin_commands)
2616 FindCommandsForApropos(search_word, commands_found, commands_help,
2617 m_command_dict);
2618
2619 if (search_user_commands)
2620 FindCommandsForApropos(search_word, commands_found, commands_help,
2621 m_user_dict);
2622
2623 if (search_alias_commands)
2624 FindCommandsForApropos(search_word, commands_found, commands_help,
2625 m_alias_dict);
2626}
2627
2628void CommandInterpreter::UpdateExecutionContext(
2629 ExecutionContext *override_context) {
2630 if (override_context != nullptr) {
2631 m_exe_ctx_ref = *override_context;
2632 } else {
2633 const bool adopt_selected = true;
2634 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2635 adopt_selected);
2636 }
2637}
2638
2639size_t CommandInterpreter::GetProcessOutput() {
2640 // The process has stuff waiting for stderr; get it and write it out to the
2641 // appropriate place.
2642 char stdio_buffer[1024];
2643 size_t len;
2644 size_t total_bytes = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002645 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002646 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2647 if (target_sp) {
2648 ProcessSP process_sp(target_sp->GetProcessSP());
2649 if (process_sp) {
2650 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2651 error)) > 0) {
2652 size_t bytes_written = len;
2653 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2654 total_bytes += len;
2655 }
2656 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2657 error)) > 0) {
2658 size_t bytes_written = len;
2659 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2660 total_bytes += len;
2661 }
2662 }
2663 }
2664 return total_bytes;
2665}
2666
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002667void CommandInterpreter::StartHandlingCommand() {
2668 auto idle_state = CommandHandlingState::eIdle;
2669 if (m_command_state.compare_exchange_strong(
2670 idle_state, CommandHandlingState::eInProgress))
2671 lldbassert(m_iohandler_nesting_level == 0);
2672 else
2673 lldbassert(m_iohandler_nesting_level > 0);
2674 ++m_iohandler_nesting_level;
2675}
2676
2677void CommandInterpreter::FinishHandlingCommand() {
2678 lldbassert(m_iohandler_nesting_level > 0);
2679 if (--m_iohandler_nesting_level == 0) {
2680 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2681 lldbassert(prev_state != CommandHandlingState::eIdle);
2682 }
2683}
2684
2685bool CommandInterpreter::InterruptCommand() {
2686 auto in_progress = CommandHandlingState::eInProgress;
2687 return m_command_state.compare_exchange_strong(
2688 in_progress, CommandHandlingState::eInterrupted);
2689}
2690
2691bool CommandInterpreter::WasInterrupted() const {
2692 bool was_interrupted =
2693 (m_command_state == CommandHandlingState::eInterrupted);
2694 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2695 return was_interrupted;
2696}
2697
2698void CommandInterpreter::PrintCommandOutput(Stream &stream,
2699 llvm::StringRef str) {
2700 // Split the output into lines and poll for interrupt requests
2701 const char *data = str.data();
2702 size_t size = str.size();
2703 while (size > 0 && !WasInterrupted()) {
2704 size_t chunk_size = 0;
2705 for (; chunk_size < size; ++chunk_size) {
2706 lldbassert(data[chunk_size] != '\0');
2707 if (data[chunk_size] == '\n') {
2708 ++chunk_size;
2709 break;
2710 }
2711 }
2712 chunk_size = stream.Write(data, chunk_size);
2713 lldbassert(size >= chunk_size);
2714 data += chunk_size;
2715 size -= chunk_size;
2716 }
2717 if (size > 0) {
2718 stream.Printf("\n... Interrupted.\n");
2719 }
2720}
2721
Kate Stoneb9c1b512016-09-06 20:57:50 +00002722void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2723 std::string &line) {
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002724 // If we were interrupted, bail out...
2725 if (WasInterrupted())
2726 return;
2727
Kate Stoneb9c1b512016-09-06 20:57:50 +00002728 const bool is_interactive = io_handler.GetIsInteractive();
2729 if (is_interactive == false) {
2730 // When we are not interactive, don't execute blank lines. This will happen
2731 // sourcing a commands file. We don't want blank lines to repeat the
Adrian Prantl05097242018-04-30 16:49:04 +00002732 // previous command and cause any errors to occur (like redefining an
2733 // alias, get an error and stop parsing the commands file).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002734 if (line.empty())
2735 return;
2736
2737 // When using a non-interactive file handle (like when sourcing commands
Adrian Prantl05097242018-04-30 16:49:04 +00002738 // from a file) we need to echo the command out so we don't just see the
2739 // command output and no command...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002740 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2741 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2742 line.c_str());
2743 }
2744
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002745 StartHandlingCommand();
2746
Kate Stoneb9c1b512016-09-06 20:57:50 +00002747 lldb_private::CommandReturnObject result;
2748 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2749
2750 // Now emit the command output text from the command we just executed
2751 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2752 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2753 GetProcessOutput();
2754
2755 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002756 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002757 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002758 }
2759
2760 // Now emit the command error text from the command we just executed
2761 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002762 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002763 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002764 }
2765 }
2766
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002767 FinishHandlingCommand();
2768
Kate Stoneb9c1b512016-09-06 20:57:50 +00002769 switch (result.GetStatus()) {
2770 case eReturnStatusInvalid:
2771 case eReturnStatusSuccessFinishNoResult:
2772 case eReturnStatusSuccessFinishResult:
2773 case eReturnStatusStarted:
2774 break;
2775
2776 case eReturnStatusSuccessContinuingNoResult:
2777 case eReturnStatusSuccessContinuingResult:
2778 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2779 io_handler.SetIsDone(true);
2780 break;
2781
2782 case eReturnStatusFailed:
2783 m_num_errors++;
2784 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2785 io_handler.SetIsDone(true);
2786 break;
2787
2788 case eReturnStatusQuit:
2789 m_quit_requested = true;
2790 io_handler.SetIsDone(true);
2791 break;
2792 }
2793
2794 // Finally, if we're going to stop on crash, check that here:
2795 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2796 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2797 bool should_stop = false;
2798 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2799 if (target_sp) {
2800 ProcessSP process_sp(target_sp->GetProcessSP());
2801 if (process_sp) {
2802 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2803 StopReason reason = thread_sp->GetStopReason();
2804 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2805 reason == eStopReasonInstrumentation) &&
2806 !result.GetAbnormalStopWasExpected()) {
2807 should_stop = true;
2808 break;
2809 }
2810 }
2811 }
2812 }
2813 if (should_stop) {
2814 io_handler.SetIsDone(true);
2815 m_stopped_for_crash = true;
2816 }
2817 }
2818}
2819
2820bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2821 ExecutionContext exe_ctx(GetExecutionContext());
2822 Process *process = exe_ctx.GetProcessPtr();
2823
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002824 if (InterruptCommand())
2825 return true;
2826
Kate Stoneb9c1b512016-09-06 20:57:50 +00002827 if (process) {
2828 StateType state = process->GetState();
2829 if (StateIsRunningState(state)) {
2830 process->Halt();
2831 return true; // Don't do any updating when we are running
2832 }
2833 }
2834
2835 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2836 if (script_interpreter) {
2837 if (script_interpreter->Interrupt())
2838 return true;
2839 }
2840 return false;
2841}
2842
2843void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2844 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2845 void *baton) {
2846 Debugger &debugger = GetDebugger();
2847 IOHandlerSP io_handler_sp(
2848 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2849 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002850 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2851 llvm::StringRef(), // Continuation prompt
2852 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002853 debugger.GetUseColor(),
2854 0, // Don't show line numbers
2855 delegate)); // IOHandlerDelegate
2856
2857 if (io_handler_sp) {
2858 io_handler_sp->SetUserData(baton);
2859 if (asynchronously)
2860 debugger.PushIOHandler(io_handler_sp);
2861 else
2862 debugger.RunIOHandler(io_handler_sp);
2863 }
2864}
2865
2866void CommandInterpreter::GetPythonCommandsFromIOHandler(
2867 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2868 void *baton) {
2869 Debugger &debugger = GetDebugger();
2870 IOHandlerSP io_handler_sp(
2871 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2872 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002873 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2874 llvm::StringRef(), // Continuation prompt
2875 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002876 debugger.GetUseColor(),
2877 0, // Don't show line numbers
2878 delegate)); // IOHandlerDelegate
2879
2880 if (io_handler_sp) {
2881 io_handler_sp->SetUserData(baton);
2882 if (asynchronously)
2883 debugger.PushIOHandler(io_handler_sp);
2884 else
2885 debugger.RunIOHandler(io_handler_sp);
2886 }
2887}
2888
2889bool CommandInterpreter::IsActive() {
2890 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2891}
2892
2893lldb::IOHandlerSP
2894CommandInterpreter::GetIOHandler(bool force_create,
2895 CommandInterpreterRunOptions *options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002896 // Always re-create the IOHandlerEditline in case the input changed. The old
2897 // instance might have had a non-interactive input and now it does or vice
2898 // versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002899 if (force_create || !m_command_io_handler_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002900 // Always re-create the IOHandlerEditline in case the input changed. The
2901 // old instance might have had a non-interactive input and now it does or
2902 // vice versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002903 uint32_t flags = 0;
2904
2905 if (options) {
2906 if (options->m_stop_on_continue == eLazyBoolYes)
2907 flags |= eHandleCommandFlagStopOnContinue;
2908 if (options->m_stop_on_error == eLazyBoolYes)
2909 flags |= eHandleCommandFlagStopOnError;
2910 if (options->m_stop_on_crash == eLazyBoolYes)
2911 flags |= eHandleCommandFlagStopOnCrash;
2912 if (options->m_echo_commands != eLazyBoolNo)
2913 flags |= eHandleCommandFlagEchoCommand;
2914 if (options->m_print_results != eLazyBoolNo)
2915 flags |= eHandleCommandFlagPrintResult;
2916 } else {
2917 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2918 }
2919
2920 m_command_io_handler_sp.reset(new IOHandlerEditline(
2921 m_debugger, IOHandler::Type::CommandInterpreter,
2922 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2923 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002924 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002925 false, // Don't enable multiple line input, just single line commands
2926 m_debugger.GetUseColor(),
2927 0, // Don't show line numbers
2928 *this));
2929 }
2930 return m_command_io_handler_sp;
2931}
2932
2933void CommandInterpreter::RunCommandInterpreter(
2934 bool auto_handle_events, bool spawn_thread,
2935 CommandInterpreterRunOptions &options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002936 // Always re-create the command interpreter when we run it in case any file
2937 // handles have changed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002938 bool force_create = true;
2939 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2940 m_stopped_for_crash = false;
2941
2942 if (auto_handle_events)
2943 m_debugger.StartEventHandlerThread();
2944
2945 if (spawn_thread) {
2946 m_debugger.StartIOHandlerThread();
2947 } else {
2948 m_debugger.ExecuteIOHandlers();
2949
2950 if (auto_handle_events)
2951 m_debugger.StopEventHandlerThread();
2952 }
2953}
2954
2955CommandObject *
2956CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2957 CommandReturnObject &result) {
2958 std::string scratch_command(command_line); // working copy so we don't modify
2959 // command_line unless we succeed
2960 CommandObject *cmd_obj = nullptr;
2961 StreamString revised_command_line;
2962 bool wants_raw_input = false;
2963 size_t actual_cmd_name_len = 0;
2964 std::string next_word;
2965 StringList matches;
2966 bool done = false;
2967 while (!done) {
2968 char quote_char = '\0';
2969 std::string suffix;
2970 ExtractCommand(scratch_command, next_word, suffix, quote_char);
2971 if (cmd_obj == nullptr) {
2972 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002973 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00002974 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002975 bool is_real_command =
2976 (is_alias == false) ||
2977 (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
2978 if (!is_real_command) {
2979 matches.Clear();
2980 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002981 cmd_obj =
2982 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002983 revised_command_line.Printf("%s", alias_result.c_str());
2984 if (cmd_obj) {
2985 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00002986 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002987 }
2988 } else {
2989 if (!cmd_obj)
Zachary Turnera4496982016-10-05 21:14:38 +00002990 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002991 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00002992 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
2993 actual_cmd_name_len += cmd_name.size();
2994 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002995 wants_raw_input = cmd_obj->WantsRawCommandString();
2996 } else {
2997 revised_command_line.Printf("%s", next_word.c_str());
2998 }
2999 }
3000 } else {
3001 if (cmd_obj->IsMultiwordObject()) {
3002 CommandObject *sub_cmd_obj =
3003 cmd_obj->GetSubcommandObject(next_word.c_str());
3004 if (sub_cmd_obj) {
Adrian Prantl05097242018-04-30 16:49:04 +00003005 // The subcommand's name includes the parent command's name, so
3006 // restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00003007 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3008 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003009 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00003010 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003011 cmd_obj = sub_cmd_obj;
3012 wants_raw_input = cmd_obj->WantsRawCommandString();
3013 } else {
3014 if (quote_char)
3015 revised_command_line.Printf(" %c%s%s%c", quote_char,
3016 next_word.c_str(), suffix.c_str(),
3017 quote_char);
3018 else
3019 revised_command_line.Printf(" %s%s", next_word.c_str(),
3020 suffix.c_str());
3021 done = true;
3022 }
3023 } else {
3024 if (quote_char)
3025 revised_command_line.Printf(" %c%s%s%c", quote_char,
3026 next_word.c_str(), suffix.c_str(),
3027 quote_char);
3028 else
3029 revised_command_line.Printf(" %s%s", next_word.c_str(),
3030 suffix.c_str());
3031 done = true;
3032 }
3033 }
3034
3035 if (cmd_obj == nullptr) {
3036 const size_t num_matches = matches.GetSize();
3037 if (matches.GetSize() > 1) {
3038 StreamString error_msg;
3039 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3040 next_word.c_str());
3041
3042 for (uint32_t i = 0; i < num_matches; ++i) {
3043 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3044 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003045 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003046 } else {
3047 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003048 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003049 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3050 next_word.c_str());
3051 }
3052 result.SetStatus(eReturnStatusFailed);
3053 return nullptr;
3054 }
3055
3056 if (cmd_obj->IsMultiwordObject()) {
3057 if (!suffix.empty()) {
3058 result.AppendErrorWithFormat(
3059 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3060 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003061 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003062 next_word.empty() ? "" : next_word.c_str(),
3063 next_word.empty() ? " -- " : " ", suffix.c_str());
3064 result.SetStatus(eReturnStatusFailed);
3065 return nullptr;
3066 }
3067 } else {
3068 // If we found a normal command, we are done
3069 done = true;
3070 if (!suffix.empty()) {
3071 switch (suffix[0]) {
3072 case '/':
3073 // GDB format suffixes
3074 {
3075 Options *command_options = cmd_obj->GetOptions();
3076 if (command_options &&
3077 command_options->SupportsLongOption("gdb-format")) {
3078 std::string gdb_format_option("--gdb-format=");
3079 gdb_format_option += (suffix.c_str() + 1);
3080
Zachary Turnerc1564272016-11-16 21:15:24 +00003081 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003082 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3083 if (arg_terminator_idx != std::string::npos) {
3084 // Insert the gdb format option before the "--" that terminates
3085 // options
3086 gdb_format_option.append(1, ' ');
3087 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003088 revised_command_line.Clear();
3089 revised_command_line.PutCString(cmd);
3090 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003091 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3092
3093 if (wants_raw_input &&
3094 FindArgumentTerminator(cmd) == std::string::npos)
3095 revised_command_line.PutCString(" --");
3096 } else {
3097 result.AppendErrorWithFormat(
3098 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003099 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003100 result.SetStatus(eReturnStatusFailed);
3101 return nullptr;
3102 }
3103 }
3104 break;
3105
3106 default:
3107 result.AppendErrorWithFormat(
3108 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3109 result.SetStatus(eReturnStatusFailed);
3110 return nullptr;
3111 }
3112 }
3113 }
3114 if (scratch_command.empty())
3115 done = true;
3116 }
3117
3118 if (!scratch_command.empty())
3119 revised_command_line.Printf(" %s", scratch_command.c_str());
3120
3121 if (cmd_obj != NULL)
Zachary Turnerc1564272016-11-16 21:15:24 +00003122 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003123
3124 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003125}