blob: 6cc5da58363ec6281eb441dff09d23e13276255b [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Kate Stoneb9c1b512016-09-06 20:57:50 +000010#include <stdlib.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000011#include <string>
Caroline Tice4ab31c92010-10-12 21:57:09 +000012#include <vector>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013
Greg Clayton4a33d312011-06-23 17:59:56 +000014#include "CommandObjectScript.h"
Peter Collingbourne08405b62011-06-23 20:37:26 +000015#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000016
James Y Knight2ad48212018-05-22 22:53:50 +000017#include "Commands/CommandObjectApropos.h"
18#include "Commands/CommandObjectBreakpoint.h"
19#include "Commands/CommandObjectBugreport.h"
20#include "Commands/CommandObjectCommands.h"
21#include "Commands/CommandObjectDisassemble.h"
22#include "Commands/CommandObjectExpression.h"
23#include "Commands/CommandObjectFrame.h"
24#include "Commands/CommandObjectGUI.h"
25#include "Commands/CommandObjectHelp.h"
26#include "Commands/CommandObjectLanguage.h"
27#include "Commands/CommandObjectLog.h"
28#include "Commands/CommandObjectMemory.h"
29#include "Commands/CommandObjectPlatform.h"
30#include "Commands/CommandObjectPlugin.h"
31#include "Commands/CommandObjectProcess.h"
32#include "Commands/CommandObjectQuit.h"
33#include "Commands/CommandObjectRegister.h"
34#include "Commands/CommandObjectSettings.h"
35#include "Commands/CommandObjectSource.h"
36#include "Commands/CommandObjectStats.h"
37#include "Commands/CommandObjectTarget.h"
38#include "Commands/CommandObjectThread.h"
39#include "Commands/CommandObjectType.h"
40#include "Commands/CommandObjectVersion.h"
41#include "Commands/CommandObjectWatchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043#include "lldb/Core/Debugger.h"
Zachary Turner2c1f46d2015-07-30 20:28:07 +000044#include "lldb/Core/PluginManager.h"
Greg Clayton44d93782014-01-27 23:43:24 +000045#include "lldb/Core/StreamFile.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000046#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000047#include "lldb/Utility/State.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000048#include "lldb/Utility/Stream.h"
Pavel Labath38d06322017-06-29 14:32:17 +000049#include "lldb/Utility/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000050
Todd Fialacacde7d2014-09-27 16:54:22 +000051#ifndef LLDB_DISABLE_LIBEDIT
Greg Clayton44d93782014-01-27 23:43:24 +000052#include "lldb/Host/Editline.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000053#endif
Greg Clayton7fb56d02011-02-01 01:31:41 +000054#include "lldb/Host/Host.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000055#include "lldb/Host/HostInfo.h"
Enrico Granatab5887262012-10-29 21:18:03 +000056
Greg Clayton7d2ef162013-03-29 17:03:23 +000057#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000058#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000059#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000060#include "lldb/Interpreter/OptionValueProperties.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000061#include "lldb/Interpreter/Options.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000062#include "lldb/Interpreter/Property.h"
Pavel Labath145d95c2018-04-17 18:53:35 +000063#include "lldb/Utility/Args.h"
Enrico Granatab5887262012-10-29 21:18:03 +000064
Chris Lattner30fdc8d2010-06-08 16:52:24 +000065#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066#include "lldb/Target/TargetList.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000067#include "lldb/Target/Thread.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000068
Saleem Abdulrasool28606952014-06-27 05:17:41 +000069#include "llvm/ADT/STLExtras.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000070#include "llvm/ADT/SmallString.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000071#include "llvm/Support/Path.h"
Sean Callanan237c3ed2016-12-14 21:31:31 +000072#include "llvm/Support/PrettyStackTrace.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000073
Chris Lattner30fdc8d2010-06-08 16:52:24 +000074using namespace lldb;
75using namespace lldb_private;
76
Adrian McCarthy2304b6f2015-04-23 20:00:25 +000077static const char *k_white_space = " \t\v";
Greg Clayton754a9362012-08-23 00:22:02 +000078
Kate Stoneb9c1b512016-09-06 20:57:50 +000079static PropertyDefinition g_properties[] = {
80 {"expand-regex-aliases", OptionValue::eTypeBoolean, true, false, nullptr,
81 nullptr, "If true, regular expression alias commands will show the "
82 "expanded command that will be executed. This can be used to "
83 "debug new regular expression alias commands."},
84 {"prompt-on-quit", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
85 "If true, LLDB will prompt you before quitting if there are any live "
86 "processes being debugged. If false, LLDB will quit without asking in any "
87 "case."},
88 {"stop-command-source-on-error", OptionValue::eTypeBoolean, true, true,
89 nullptr, nullptr, "If true, LLDB will stop running a 'command source' "
90 "script upon encountering an error."},
91 {"space-repl-prompts", OptionValue::eTypeBoolean, true, false, nullptr,
92 nullptr,
93 "If true, blank lines will be printed between between REPL submissions."},
94 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
95
96enum {
97 ePropertyExpandRegexAliases = 0,
98 ePropertyPromptOnQuit = 1,
99 ePropertyStopCmdSourceOnError = 2,
100 eSpaceReplPrompts = 3
Greg Clayton754a9362012-08-23 00:22:02 +0000101};
102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103ConstString &CommandInterpreter::GetStaticBroadcasterClass() {
104 static ConstString class_name("lldb.commandInterpreter");
105 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000106}
107
Kate Stoneb9c1b512016-09-06 20:57:50 +0000108CommandInterpreter::CommandInterpreter(Debugger &debugger,
109 ScriptLanguage script_language,
110 bool synchronous_execution)
111 : Broadcaster(debugger.GetBroadcasterManager(),
112 CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
113 Properties(OptionValuePropertiesSP(
114 new OptionValueProperties(ConstString("interpreter")))),
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000115 IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 m_debugger(debugger), m_synchronous_execution(synchronous_execution),
117 m_skip_lldbinit_files(false), m_skip_app_init_files(false),
118 m_script_interpreter_sp(), m_command_io_handler_sp(), m_comment_char('#'),
119 m_batch_command_mode(false), m_truncation_warning(eNoTruncation),
120 m_command_source_depth(0), m_num_errors(0), m_quit_requested(false),
121 m_stopped_for_crash(false) {
122 debugger.SetScriptLanguage(script_language);
123 SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit");
124 SetEventName(eBroadcastBitResetPrompt, "reset-prompt");
125 SetEventName(eBroadcastBitQuitCommandReceived, "quit");
126 CheckInWithManager();
127 m_collection_sp->Initialize(g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000128}
129
Kate Stoneb9c1b512016-09-06 20:57:50 +0000130bool CommandInterpreter::GetExpandRegexAliases() const {
131 const uint32_t idx = ePropertyExpandRegexAliases;
132 return m_collection_sp->GetPropertyAtIndexAsBoolean(
133 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000134}
135
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136bool CommandInterpreter::GetPromptOnQuit() const {
137 const uint32_t idx = ePropertyPromptOnQuit;
138 return m_collection_sp->GetPropertyAtIndexAsBoolean(
139 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000140}
Greg Clayton754a9362012-08-23 00:22:02 +0000141
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142void CommandInterpreter::SetPromptOnQuit(bool b) {
143 const uint32_t idx = ePropertyPromptOnQuit;
144 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ilia Kacf28be2015-03-23 22:45:13 +0000145}
146
Raphael Isemannc094d232018-07-11 17:18:01 +0000147void CommandInterpreter::AllowExitCodeOnQuit(bool allow) {
148 m_allow_exit_code = allow;
149 if (!allow)
150 m_quit_exit_code.reset();
151}
152
153bool CommandInterpreter::SetQuitExitCode(int exit_code) {
154 if (!m_allow_exit_code)
155 return false;
156 m_quit_exit_code = exit_code;
157 return true;
158}
159
160int CommandInterpreter::GetQuitExitCode(bool &exited) const {
161 exited = m_quit_exit_code.hasValue();
162 if (exited)
163 return *m_quit_exit_code;
164 return 0;
165}
166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167void CommandInterpreter::ResolveCommand(const char *command_line,
168 CommandReturnObject &result) {
169 std::string command = command_line;
170 if (ResolveCommandImpl(command, result) != nullptr) {
171 result.AppendMessageWithFormat("%s", command.c_str());
172 result.SetStatus(eReturnStatusSuccessFinishResult);
173 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000174}
175
Kate Stoneb9c1b512016-09-06 20:57:50 +0000176bool CommandInterpreter::GetStopCmdSourceOnError() const {
177 const uint32_t idx = ePropertyStopCmdSourceOnError;
178 return m_collection_sp->GetPropertyAtIndexAsBoolean(
179 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000180}
181
Kate Stoneb9c1b512016-09-06 20:57:50 +0000182bool CommandInterpreter::GetSpaceReplPrompts() const {
183 const uint32_t idx = eSpaceReplPrompts;
184 return m_collection_sp->GetPropertyAtIndexAsBoolean(
185 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callanan66810412015-10-19 23:11:07 +0000186}
187
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188void CommandInterpreter::Initialize() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000189 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
190 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000191
Kate Stoneb9c1b512016-09-06 20:57:50 +0000192 CommandReturnObject result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000193
Kate Stoneb9c1b512016-09-06 20:57:50 +0000194 LoadCommandDictionary();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000195
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196 // An alias arguments vector to reuse - reset it before use...
197 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
198
199 // Set up some initial aliases.
200 CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
201 if (cmd_obj_sp) {
202 AddAlias("q", cmd_obj_sp);
203 AddAlias("exit", cmd_obj_sp);
204 }
205
206 cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
207 if (cmd_obj_sp)
208 AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
209
210 cmd_obj_sp = GetCommandSPExact("process detach", false);
211 if (cmd_obj_sp) {
212 AddAlias("detach", cmd_obj_sp);
213 }
214
215 cmd_obj_sp = GetCommandSPExact("process continue", false);
216 if (cmd_obj_sp) {
217 AddAlias("c", cmd_obj_sp);
218 AddAlias("continue", cmd_obj_sp);
219 }
220
221 cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
222 if (cmd_obj_sp)
223 AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
224
225 cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
226 if (cmd_obj_sp)
227 AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
228
229 cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
230 if (cmd_obj_sp) {
231 AddAlias("stepi", cmd_obj_sp);
232 AddAlias("si", cmd_obj_sp);
233 }
234
235 cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
236 if (cmd_obj_sp) {
237 AddAlias("nexti", cmd_obj_sp);
238 AddAlias("ni", cmd_obj_sp);
239 }
240
241 cmd_obj_sp = GetCommandSPExact("thread step-in", false);
242 if (cmd_obj_sp) {
243 AddAlias("s", cmd_obj_sp);
244 AddAlias("step", cmd_obj_sp);
245 CommandAlias *sif_alias = AddAlias(
246 "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
247 if (sif_alias) {
248 sif_alias->SetHelp("Step through the current block, stopping if you step "
249 "directly into a function whose name matches the "
250 "TargetFunctionName.");
251 sif_alias->SetSyntax("sif <TargetFunctionName>");
Caroline Ticeca90c472011-05-06 21:37:15 +0000252 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000254
Kate Stoneb9c1b512016-09-06 20:57:50 +0000255 cmd_obj_sp = GetCommandSPExact("thread step-over", false);
256 if (cmd_obj_sp) {
257 AddAlias("n", cmd_obj_sp);
258 AddAlias("next", cmd_obj_sp);
259 }
260
261 cmd_obj_sp = GetCommandSPExact("thread step-out", false);
262 if (cmd_obj_sp) {
263 AddAlias("finish", cmd_obj_sp);
264 }
265
266 cmd_obj_sp = GetCommandSPExact("frame select", false);
267 if (cmd_obj_sp) {
268 AddAlias("f", cmd_obj_sp);
269 }
270
271 cmd_obj_sp = GetCommandSPExact("thread select", false);
272 if (cmd_obj_sp) {
273 AddAlias("t", cmd_obj_sp);
274 }
275
276 cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
277 if (cmd_obj_sp) {
278 AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
279 AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
280 }
281
282 cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
283 if (cmd_obj_sp) {
284 AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
285 AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
286 }
287
288 cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
289 if (cmd_obj_sp)
290 AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
291
292 cmd_obj_sp = GetCommandSPExact("memory read", false);
293 if (cmd_obj_sp)
294 AddAlias("x", cmd_obj_sp);
295
296 cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
297 if (cmd_obj_sp)
298 AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
299
300 cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
301 if (cmd_obj_sp)
302 AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
303
304 cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
305 if (cmd_obj_sp)
306 AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
307
308 cmd_obj_sp = GetCommandSPExact("disassemble", false);
309 if (cmd_obj_sp)
310 AddAlias("dis", cmd_obj_sp);
311
312 cmd_obj_sp = GetCommandSPExact("disassemble", false);
313 if (cmd_obj_sp)
314 AddAlias("di", cmd_obj_sp);
315
316 cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
317 if (cmd_obj_sp)
318 AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
319
320 cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
321 if (cmd_obj_sp)
322 AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
323
324 cmd_obj_sp = GetCommandSPExact("target create", false);
325 if (cmd_obj_sp)
326 AddAlias("file", cmd_obj_sp);
327
328 cmd_obj_sp = GetCommandSPExact("target modules", false);
329 if (cmd_obj_sp)
330 AddAlias("image", cmd_obj_sp);
331
332 alias_arguments_vector_sp.reset(new OptionArgVector);
333
334 cmd_obj_sp = GetCommandSPExact("expression", false);
335 if (cmd_obj_sp) {
336 AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
337 AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
338 AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
339 if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
340 po->SetHelp("Evaluate an expression on the current thread. Displays any "
341 "returned value with formatting "
342 "controlled by the type's author.");
343 po->SetHelpLong("");
Johnny Chen6d675242012-08-24 18:15:45 +0000344 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345 AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
346 AddAlias("poarray", cmd_obj_sp,
347 "--object-description --element-count %1 --")
348 ->SetHelpLong("");
349 }
Johnny Chen6d675242012-08-24 18:15:45 +0000350
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 cmd_obj_sp = GetCommandSPExact("process kill", false);
352 if (cmd_obj_sp) {
353 AddAlias("kill", cmd_obj_sp);
354 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000355
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 cmd_obj_sp = GetCommandSPExact("process launch", false);
357 if (cmd_obj_sp) {
Chaoren Lin6fc5c7f2016-02-26 03:36:27 +0000358 alias_arguments_vector_sp.reset(new OptionArgVector);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
360 AddAlias("r", cmd_obj_sp, "--");
361 AddAlias("run", cmd_obj_sp, "--");
Jason Molenda85da3122012-07-06 02:46:23 +0000362#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363#if defined(__APPLE__)
364 std::string shell_option;
365 shell_option.append("--shell-expand-args");
366 shell_option.append(" true");
367 shell_option.append(" --");
368 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
369 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
370#else
371 StreamString defaultshell;
372 defaultshell.Printf("--shell=%s --",
373 HostInfo::GetDefaultShell().GetPath().c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +0000374 AddAlias("r", cmd_obj_sp, defaultshell.GetString());
375 AddAlias("run", cmd_obj_sp, defaultshell.GetString());
Jason Molenda85da3122012-07-06 02:46:23 +0000376#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377#endif
378 }
379
380 cmd_obj_sp = GetCommandSPExact("target symbols add", false);
381 if (cmd_obj_sp) {
382 AddAlias("add-dsym", cmd_obj_sp);
383 }
384
385 cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
386 if (cmd_obj_sp) {
387 AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
388 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000389}
390
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391void CommandInterpreter::Clear() {
392 m_command_io_handler_sp.reset();
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000393
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 if (m_script_interpreter_sp)
395 m_script_interpreter_sp->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000396}
397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
399 // This function has not yet been implemented.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 // Look for any embedded script command
402 // If found,
403 // get interpreter object from the command dictionary,
404 // call execute_one_command on it,
405 // get the results as a string,
406 // substitute that string for current stuff.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000407
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 return arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000409}
410
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411void CommandInterpreter::LoadCommandDictionary() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000412 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
413 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000414
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000416
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
418 m_command_dict["breakpoint"] =
419 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
420 m_command_dict["bugreport"] =
421 CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
422 m_command_dict["command"] =
423 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
424 m_command_dict["disassemble"] =
425 CommandObjectSP(new CommandObjectDisassemble(*this));
426 m_command_dict["expression"] =
427 CommandObjectSP(new CommandObjectExpression(*this));
428 m_command_dict["frame"] =
429 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
430 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
431 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
432 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
433 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
434 m_command_dict["platform"] =
435 CommandObjectSP(new CommandObjectPlatform(*this));
436 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
437 m_command_dict["process"] =
438 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
439 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
440 m_command_dict["register"] =
441 CommandObjectSP(new CommandObjectRegister(*this));
442 m_command_dict["script"] =
443 CommandObjectSP(new CommandObjectScript(*this, script_language));
444 m_command_dict["settings"] =
445 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
446 m_command_dict["source"] =
447 CommandObjectSP(new CommandObjectMultiwordSource(*this));
Davide Italiano24fff242018-04-13 18:02:39 +0000448 m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000449 m_command_dict["target"] =
450 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
451 m_command_dict["thread"] =
452 CommandObjectSP(new CommandObjectMultiwordThread(*this));
453 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
454 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
455 m_command_dict["watchpoint"] =
456 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
457 m_command_dict["language"] =
458 CommandObjectSP(new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000459
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 const char *break_regexes[][2] = {
461 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
462 "breakpoint set --file '%1' --line %2"},
463 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
464 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
465 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
466 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
467 "breakpoint set --name '%1'"},
468 {"^(-.*)$", "breakpoint set %1"},
469 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
470 "breakpoint set --name '%2' --shlib '%1'"},
471 {"^\\&(.*[^[:space:]])[[:space:]]*$",
472 "breakpoint set --name '%1' --skip-prologue=0"},
473 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
474 "breakpoint set --name '%1'"}};
Kate Stone7428a182016-07-14 22:03:10 +0000475
Kate Stoneb9c1b512016-09-06 20:57:50 +0000476 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000477
Kate Stoneb9c1b512016-09-06 20:57:50 +0000478 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap(
479 new CommandObjectRegexCommand(
480 *this, "_regexp-break",
Raphael Isemann129fe892018-07-30 21:41:13 +0000481 "Set a breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000482 "\n"
483 "_regexp-break <filename>:<linenum>\n"
484 " main.c:12 // Break at line 12 of "
485 "main.c\n\n"
486 "_regexp-break <linenum>\n"
487 " 12 // Break at line 12 of current "
488 "file\n\n"
489 "_regexp-break 0x<address>\n"
490 " 0x1234000 // Break at address "
491 "0x1234000\n\n"
492 "_regexp-break <name>\n"
493 " main // Break in 'main' after the "
494 "prologue\n\n"
495 "_regexp-break &<name>\n"
496 " &main // Break at first instruction "
497 "in 'main'\n\n"
498 "_regexp-break <module>`<name>\n"
499 " libc.so`malloc // Break in 'malloc' from "
500 "'libc.so'\n\n"
501 "_regexp-break /<source-regex>/\n"
502 " /break here/ // Break on source lines in "
503 "current file\n"
504 " // containing text 'break "
505 "here'.\n",
506 2, CommandCompletions::eSymbolCompletion |
507 CommandCompletions::eSourceFileCompletion,
508 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000509
Kate Stoneb9c1b512016-09-06 20:57:50 +0000510 if (break_regex_cmd_ap.get()) {
511 bool success = true;
512 for (size_t i = 0; i < num_regexes; i++) {
513 success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0],
514 break_regexes[i][1]);
515 if (!success)
516 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000517 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000518 success =
519 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Jim Inghamffba2292011-03-22 02:29:32 +0000520
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 if (success) {
522 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
523 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
Jim Inghamca36cd12012-10-05 19:16:31 +0000524 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 }
Jim Inghamca36cd12012-10-05 19:16:31 +0000526
Kate Stoneb9c1b512016-09-06 20:57:50 +0000527 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap(
528 new CommandObjectRegexCommand(
529 *this, "_regexp-tbreak",
Raphael Isemann129fe892018-07-30 21:41:13 +0000530 "Set a one-shot breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531 "\n"
532 "_regexp-break <filename>:<linenum>\n"
533 " main.c:12 // Break at line 12 of "
534 "main.c\n\n"
535 "_regexp-break <linenum>\n"
536 " 12 // Break at line 12 of current "
537 "file\n\n"
538 "_regexp-break 0x<address>\n"
539 " 0x1234000 // Break at address "
540 "0x1234000\n\n"
541 "_regexp-break <name>\n"
542 " main // Break in 'main' after the "
543 "prologue\n\n"
544 "_regexp-break &<name>\n"
545 " &main // Break at first instruction "
546 "in 'main'\n\n"
547 "_regexp-break <module>`<name>\n"
548 " libc.so`malloc // Break in 'malloc' from "
549 "'libc.so'\n\n"
550 "_regexp-break /<source-regex>/\n"
551 " /break here/ // Break on source lines in "
552 "current file\n"
553 " // containing text 'break "
554 "here'.\n",
555 2, CommandCompletions::eSymbolCompletion |
556 CommandCompletions::eSourceFileCompletion,
557 false));
558
559 if (tbreak_regex_cmd_ap.get()) {
560 bool success = true;
561 for (size_t i = 0; i < num_regexes; i++) {
562 // If you add a resultant command string longer than 1024 characters be
563 // sure to increase the size of this buffer.
564 char buffer[1024];
565 int num_printed =
Frederic Riss49c9d8b2018-06-18 04:34:33 +0000566 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1");
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000567 lldbassert(num_printed < 1024);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 UNUSED_IF_ASSERT_DISABLED(num_printed);
569 success =
570 tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer);
571 if (!success)
572 break;
Johnny Chen6d675242012-08-24 18:15:45 +0000573 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574 success =
575 tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Kate Stone7428a182016-07-14 22:03:10 +0000576
Kate Stoneb9c1b512016-09-06 20:57:50 +0000577 if (success) {
578 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
579 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
580 tbreak_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000581 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 }
Kate Stone7428a182016-07-14 22:03:10 +0000583
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap(
585 new CommandObjectRegexCommand(
586 *this, "_regexp-attach", "Attach to process by ID or name.",
587 "_regexp-attach <pid> | <process-name>", 2, 0, false));
588 if (attach_regex_cmd_ap.get()) {
589 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
590 "process attach --pid %1") &&
591 attach_regex_cmd_ap->AddRegexCommand(
592 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
593 // specified get passed to
594 // 'process attach'
595 attach_regex_cmd_ap->AddRegexCommand("^(.+)$",
596 "process attach --name '%1'") &&
597 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) {
598 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
599 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
600 attach_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000601 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000602 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000603
Kate Stoneb9c1b512016-09-06 20:57:50 +0000604 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap(
605 new CommandObjectRegexCommand(*this, "_regexp-down",
606 "Select a newer stack frame. Defaults to "
607 "moving one frame, a numeric argument can "
608 "specify an arbitrary number.",
609 "_regexp-down [<count>]", 2, 0, false));
610 if (down_regex_cmd_ap.get()) {
611 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
612 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
613 "frame select -r -%1")) {
614 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
615 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000616 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000617 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000618
Kate Stoneb9c1b512016-09-06 20:57:50 +0000619 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap(
620 new CommandObjectRegexCommand(
621 *this, "_regexp-up",
622 "Select an older stack frame. Defaults to moving one "
623 "frame, a numeric argument can specify an arbitrary number.",
624 "_regexp-up [<count>]", 2, 0, false));
625 if (up_regex_cmd_ap.get()) {
626 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
627 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
628 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
629 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000630 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000631 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000632
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap(
634 new CommandObjectRegexCommand(
635 *this, "_regexp-display",
636 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
637 "_regexp-display expression", 2, 0, false));
638 if (display_regex_cmd_ap.get()) {
639 if (display_regex_cmd_ap->AddRegexCommand(
640 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
641 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
642 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
643 display_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000644 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000645 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000646
Kate Stoneb9c1b512016-09-06 20:57:50 +0000647 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap(
648 new CommandObjectRegexCommand(
649 *this, "_regexp-undisplay", "Stop displaying expression at every "
650 "stop (specified by stop-hook index.)",
651 "_regexp-undisplay stop-hook-number", 2, 0, false));
652 if (undisplay_regex_cmd_ap.get()) {
653 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
654 "target stop-hook delete %1")) {
655 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
656 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
657 undisplay_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000658 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000660
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap(
662 new CommandObjectRegexCommand(
663 *this, "gdb-remote", "Connect to a process via remote GDB server. "
664 "If no host is specifed, localhost is assumed.",
665 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
666 if (connect_gdb_remote_cmd_ap.get()) {
667 if (connect_gdb_remote_cmd_ap->AddRegexCommand(
Chris Bieneman51978f52017-04-27 16:13:58 +0000668 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
669 "process connect --plugin gdb-remote connect://%1:%2") &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670 connect_gdb_remote_cmd_ap->AddRegexCommand(
671 "^([[:digit:]]+)$",
672 "process connect --plugin gdb-remote connect://localhost:%1")) {
673 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
674 m_command_dict[command_sp->GetCommandName()] = command_sp;
Jason Molenda4cddfed2012-10-05 05:29:32 +0000675 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000676 }
Jason Molenda4cddfed2012-10-05 05:29:32 +0000677
Kate Stoneb9c1b512016-09-06 20:57:50 +0000678 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap(
679 new CommandObjectRegexCommand(
680 *this, "kdp-remote", "Connect to a process via remote KDP server. "
681 "If no UDP port is specified, port 41139 is "
682 "assumed.",
683 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
684 if (connect_kdp_remote_cmd_ap.get()) {
685 if (connect_kdp_remote_cmd_ap->AddRegexCommand(
686 "^([^:]+:[[:digit:]]+)$",
687 "process connect --plugin kdp-remote udp://%1") &&
688 connect_kdp_remote_cmd_ap->AddRegexCommand(
689 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
690 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
691 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Clayton6bade322013-02-01 23:33:03 +0000692 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000693 }
Greg Clayton6bade322013-02-01 23:33:03 +0000694
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap(
696 new CommandObjectRegexCommand(
697 *this, "_regexp-bt",
698 "Show the current thread's call stack. Any numeric argument "
699 "displays at most that many "
700 "frames. The argument 'all' displays all threads.",
701 "bt [<digit> | all]", 2, 0, false));
702 if (bt_regex_cmd_ap.get()) {
703 // accept but don't document "bt -c <number>" -- before bt was a regex
Adrian Prantl05097242018-04-30 16:49:04 +0000704 // command if you wanted to backtrace three frames you would do "bt -c 3"
705 // but the intention is to have this emulate the gdb "bt" command and so
706 // now "bt 3" is the preferred form, in line with gdb.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$",
708 "thread backtrace -c %1") &&
709 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$",
710 "thread backtrace -c %1") &&
711 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
712 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) {
713 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
714 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Claytonef5651d2013-02-12 18:52:24 +0000715 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716 }
Greg Claytonef5651d2013-02-12 18:52:24 +0000717
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap(
719 new CommandObjectRegexCommand(
720 *this, "_regexp-list",
721 "List relevant source code using one of several shorthand formats.",
722 "\n"
723 "_regexp-list <file>:<line> // List around specific file/line\n"
724 "_regexp-list <line> // List current file around specified "
725 "line\n"
726 "_regexp-list <function-name> // List specified function\n"
727 "_regexp-list 0x<address> // List around specified address\n"
728 "_regexp-list -[<count>] // List previous <count> lines\n"
729 "_regexp-list // List subsequent lines",
730 2, CommandCompletions::eSourceFileCompletion, false));
731 if (list_regex_cmd_ap.get()) {
732 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
733 "source list --line %1") &&
734 list_regex_cmd_ap->AddRegexCommand(
735 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
736 "]*$",
737 "source list --file '%1' --line %2") &&
738 list_regex_cmd_ap->AddRegexCommand(
739 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
740 "source list --address %1") &&
741 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$",
742 "source list --reverse") &&
743 list_regex_cmd_ap->AddRegexCommand(
744 "^-([[:digit:]]+)[[:space:]]*$",
745 "source list --reverse --count %1") &&
746 list_regex_cmd_ap->AddRegexCommand("^(.+)$",
747 "source list --name \"%1\"") &&
748 list_regex_cmd_ap->AddRegexCommand("^$", "source list")) {
749 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
750 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
Richard Mittonf86248d2013-09-12 02:20:34 +0000751 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 }
Richard Mittonf86248d2013-09-12 02:20:34 +0000753
Kate Stoneb9c1b512016-09-06 20:57:50 +0000754 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap(
755 new CommandObjectRegexCommand(
756 *this, "_regexp-env",
757 "Shorthand for viewing and setting environment variables.",
758 "\n"
759 "_regexp-env // Show enrivonment\n"
760 "_regexp-env <name>=<value> // Set an environment variable",
761 2, 0, false));
762 if (env_regex_cmd_ap.get()) {
763 if (env_regex_cmd_ap->AddRegexCommand("^$",
764 "settings show target.env-vars") &&
765 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
766 "settings set target.env-vars %1")) {
767 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
768 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
769 }
770 }
771
772 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap(
773 new CommandObjectRegexCommand(
774 *this, "_regexp-jump", "Set the program counter to a new address.",
775 "\n"
776 "_regexp-jump <line>\n"
777 "_regexp-jump +<line-offset> | -<line-offset>\n"
778 "_regexp-jump <file>:<line>\n"
779 "_regexp-jump *<addr>\n",
780 2, 0, false));
781 if (jump_regex_cmd_ap.get()) {
782 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$",
783 "thread jump --addr %1") &&
784 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
785 "thread jump --line %1") &&
786 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$",
787 "thread jump --file %1 --line %2") &&
788 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$",
789 "thread jump --by %1")) {
790 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
791 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
792 }
793 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000794}
795
Kate Stoneb9c1b512016-09-06 20:57:50 +0000796int CommandInterpreter::GetCommandNamesMatchingPartialString(
Raphael Isemann7f888292018-09-13 21:26:00 +0000797 const char *cmd_str, bool include_aliases, StringList &matches,
798 StringList &descriptions) {
799 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches,
800 &descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000801
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802 if (include_aliases) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000803 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches,
804 &descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000805 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000806
Kate Stoneb9c1b512016-09-06 20:57:50 +0000807 return matches.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000808}
809
Raphael Isemann7f888292018-09-13 21:26:00 +0000810CommandObjectSP
811CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases,
812 bool exact, StringList *matches,
813 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000815
Zachary Turnera4496982016-10-05 21:14:38 +0000816 std::string cmd = cmd_str;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000817
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 if (HasCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000819 auto pos = m_command_dict.find(cmd);
Greg Claytonb5472782015-01-09 19:08:20 +0000820 if (pos != m_command_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000821 command_sp = pos->second;
822 }
823
824 if (include_aliases && HasAliases()) {
825 auto alias_pos = m_alias_dict.find(cmd);
826 if (alias_pos != m_alias_dict.end())
827 command_sp = alias_pos->second;
828 }
829
830 if (HasUserCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000831 auto pos = m_user_dict.find(cmd);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000832 if (pos != m_user_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000833 command_sp = pos->second;
834 }
835
836 if (!exact && !command_sp) {
837 // We will only get into here if we didn't find any exact matches.
838
839 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
840
841 StringList local_matches;
842 if (matches == nullptr)
843 matches = &local_matches;
844
845 unsigned int num_cmd_matches = 0;
846 unsigned int num_alias_matches = 0;
847 unsigned int num_user_matches = 0;
848
849 // Look through the command dictionaries one by one, and if we get only one
Adrian Prantl05097242018-04-30 16:49:04 +0000850 // match from any of them in toto, then return that, otherwise return an
851 // empty CommandObjectSP and the list of matches.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852
853 if (HasCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000854 num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str,
855 *matches, descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000856 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000857
858 if (num_cmd_matches == 1) {
859 cmd.assign(matches->GetStringAtIndex(0));
Zachary Turnera4496982016-10-05 21:14:38 +0000860 auto pos = m_command_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000861 if (pos != m_command_dict.end())
862 real_match_sp = pos->second;
863 }
864
865 if (include_aliases && HasAliases()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000866 num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str,
867 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868 }
869
870 if (num_alias_matches == 1) {
871 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
872 auto alias_pos = m_alias_dict.find(cmd);
873 if (alias_pos != m_alias_dict.end())
874 alias_match_sp = alias_pos->second;
875 }
876
877 if (HasUserCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000878 num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str,
879 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 }
881
882 if (num_user_matches == 1) {
883 cmd.assign(
884 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
885
Zachary Turnera4496982016-10-05 21:14:38 +0000886 auto pos = m_user_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887 if (pos != m_user_dict.end())
888 user_match_sp = pos->second;
889 }
890
891 // If we got exactly one match, return that, otherwise return the match
892 // list.
893
894 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
895 if (num_cmd_matches)
896 return real_match_sp;
897 else if (num_alias_matches)
898 return alias_match_sp;
899 else
900 return user_match_sp;
901 }
902 } else if (matches && command_sp) {
Zachary Turnera4496982016-10-05 21:14:38 +0000903 matches->AppendString(cmd_str);
Raphael Isemann7f888292018-09-13 21:26:00 +0000904 if (descriptions)
905 descriptions->AppendString(command_sp->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000906 }
907
908 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000909}
910
Zachary Turnera4496982016-10-05 21:14:38 +0000911bool CommandInterpreter::AddCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912 const lldb::CommandObjectSP &cmd_sp,
913 bool can_replace) {
914 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000915 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
916 "tried to add a CommandObject from a different interpreter");
Kate Stonea487aa42015-01-15 00:52:41 +0000917
Zachary Turnera4496982016-10-05 21:14:38 +0000918 if (name.empty())
919 return false;
920
921 std::string name_sstr(name);
922 auto name_iter = m_command_dict.find(name_sstr);
923 if (name_iter != m_command_dict.end()) {
924 if (!can_replace || !name_iter->second->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000925 return false;
Zachary Turnera4496982016-10-05 21:14:38 +0000926 name_iter->second = cmd_sp;
927 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000928 m_command_dict[name_sstr] = cmd_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000929 }
Zachary Turnera4496982016-10-05 21:14:38 +0000930 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000931}
932
Zachary Turnera483f572016-10-05 21:14:49 +0000933bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000934 const lldb::CommandObjectSP &cmd_sp,
935 bool can_replace) {
936 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000937 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
938 "tried to add a CommandObject from a different interpreter");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000939
Kate Stoneb9c1b512016-09-06 20:57:50 +0000940 if (!name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941 // do not allow replacement of internal commands
Zachary Turnera483f572016-10-05 21:14:49 +0000942 if (CommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000943 if (can_replace == false)
944 return false;
945 if (m_command_dict[name]->IsRemovable() == false)
Greg Clayton5a314712011-10-14 07:41:33 +0000946 return false;
947 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000948
Zachary Turnera483f572016-10-05 21:14:49 +0000949 if (UserCommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000950 if (can_replace == false)
951 return false;
952 if (m_user_dict[name]->IsRemovable() == false)
953 return false;
Caroline Tice844d2302010-12-09 22:52:49 +0000954 }
955
Kate Stoneb9c1b512016-09-06 20:57:50 +0000956 m_user_dict[name] = cmd_sp;
957 return true;
958 }
959 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000960}
961
Zachary Turnera4496982016-10-05 21:14:38 +0000962CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
963 bool include_aliases) const {
964 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +0000965 // it's a multi-word command.
966 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000967
Zachary Turnera4496982016-10-05 21:14:38 +0000968 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 return ret_val;
970
971 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +0000972 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000973 else {
974 // We have a multi-word command (seemingly), so we need to do more work.
975 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +0000976 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000977 include_aliases, true, nullptr);
978 if (cmd_obj_sp.get() != nullptr) {
Adrian Prantl05097242018-04-30 16:49:04 +0000979 // Loop through the rest of the words in the command (everything passed
980 // in was supposed to be part of a command name), and find the
981 // appropriate sub-command SP for each command word....
Kate Stoneb9c1b512016-09-06 20:57:50 +0000982 size_t end = cmd_words.GetArgumentCount();
983 for (size_t j = 1; j < end; ++j) {
984 if (cmd_obj_sp->IsMultiwordObject()) {
985 cmd_obj_sp =
986 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
987 if (cmd_obj_sp.get() == nullptr)
988 // The sub-command name was invalid. Fail and return the empty
989 // 'ret_val'.
990 return ret_val;
991 } else
992 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +0000993 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000994 return ret_val;
995 }
996 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +0000997 // command objects for them. Assign the last object retrieved to
998 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001000 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001001 }
1002 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001003}
1004
Raphael Isemann7f888292018-09-13 21:26:00 +00001005CommandObject *
1006CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
1007 StringList *matches,
1008 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009 CommandObject *command_obj =
Raphael Isemann7f888292018-09-13 21:26:00 +00001010 GetCommandSP(cmd_str, false, true, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001011
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 // If we didn't find an exact match to the command string in the commands,
Adrian Prantl05097242018-04-30 16:49:04 +00001013 // look in the aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001014
1015 if (command_obj)
1016 return command_obj;
1017
Raphael Isemann7f888292018-09-13 21:26:00 +00001018 command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001019
1020 if (command_obj)
1021 return command_obj;
1022
1023 // If there wasn't an exact match then look for an inexact one in just the
1024 // commands
Zachary Turnera4496982016-10-05 21:14:38 +00001025 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001026
1027 // Finally, if there wasn't an inexact match among the commands, look for an
Adrian Prantl05097242018-04-30 16:49:04 +00001028 // inexact match in both the commands and aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001029
1030 if (command_obj) {
1031 if (matches)
1032 matches->AppendString(command_obj->GetCommandName());
Raphael Isemann7f888292018-09-13 21:26:00 +00001033 if (descriptions)
1034 descriptions->AppendString(command_obj->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001035 return command_obj;
1036 }
1037
Raphael Isemann7f888292018-09-13 21:26:00 +00001038 return GetCommandSP(cmd_str, true, false, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001039}
1040
Zachary Turnera483f572016-10-05 21:14:49 +00001041bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001042 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001043}
1044
Zachary Turnera483f572016-10-05 21:14:49 +00001045bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1046 std::string &full_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001047 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1048 if (exact_match) {
1049 full_name.assign(cmd);
1050 return exact_match;
1051 } else {
1052 StringList matches;
1053 size_t num_alias_matches;
1054 num_alias_matches =
1055 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1056 if (num_alias_matches == 1) {
1057 // Make sure this isn't shadowing a command in the regular command space:
1058 StringList regular_matches;
1059 const bool include_aliases = false;
1060 const bool exact = false;
1061 CommandObjectSP cmd_obj_sp(
1062 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1063 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1064 return false;
1065 else {
1066 full_name.assign(matches.GetStringAtIndex(0));
1067 return true;
1068 }
1069 } else
1070 return false;
1071 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001072}
1073
Zachary Turnera483f572016-10-05 21:14:49 +00001074bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001076}
1077
Zachary Turnera483f572016-10-05 21:14:49 +00001078bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001079 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001080}
1081
Kate Stoneb9c1b512016-09-06 20:57:50 +00001082CommandAlias *
Zachary Turnera483f572016-10-05 21:14:49 +00001083CommandInterpreter::AddAlias(llvm::StringRef alias_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001084 lldb::CommandObjectSP &command_obj_sp,
Zachary Turnera483f572016-10-05 21:14:49 +00001085 llvm::StringRef args_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001086 if (command_obj_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001087 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1088 "tried to add a CommandObject from a different interpreter");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001089
1090 std::unique_ptr<CommandAlias> command_alias_up(
1091 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1092
1093 if (command_alias_up && command_alias_up->IsValid()) {
1094 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1095 return command_alias_up.release();
1096 }
1097
1098 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001099}
1100
Zachary Turnera483f572016-10-05 21:14:49 +00001101bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001102 auto pos = m_alias_dict.find(alias_name);
1103 if (pos != m_alias_dict.end()) {
1104 m_alias_dict.erase(pos);
1105 return true;
1106 }
1107 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001108}
1109
Zachary Turnera483f572016-10-05 21:14:49 +00001110bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001111 auto pos = m_command_dict.find(cmd);
1112 if (pos != m_command_dict.end()) {
1113 if (pos->second->IsRemovable()) {
1114 // Only regular expression objects or python commands are removable
1115 m_command_dict.erase(pos);
1116 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001117 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001118 }
1119 return false;
1120}
Zachary Turnera483f572016-10-05 21:14:49 +00001121bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1123 if (pos != m_user_dict.end()) {
1124 m_user_dict.erase(pos);
1125 return true;
1126 }
1127 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001128}
1129
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130void CommandInterpreter::GetHelp(CommandReturnObject &result,
1131 uint32_t cmd_types) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001132 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1133 if (!help_prologue.empty()) {
1134 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1135 help_prologue);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001136 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001137
Kate Stoneb9c1b512016-09-06 20:57:50 +00001138 CommandObject::CommandMap::const_iterator pos;
1139 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001140
Kate Stoneb9c1b512016-09-06 20:57:50 +00001141 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1142 result.AppendMessage("Debugger commands:");
1143 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001144
Kate Stoneb9c1b512016-09-06 20:57:50 +00001145 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1146 if (!(cmd_types & eCommandTypesHidden) &&
1147 (pos->first.compare(0, 1, "_") == 0))
1148 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001149
Zachary Turner0ac5f982016-11-08 04:12:42 +00001150 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1151 pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001152 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001153 result.AppendMessage("");
1154 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001155
Kate Stoneb9c1b512016-09-06 20:57:50 +00001156 if (!m_alias_dict.empty() &&
1157 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1158 result.AppendMessageWithFormat(
1159 "Current command abbreviations "
1160 "(type '%shelp command alias' for more info):\n",
1161 GetCommandPrefix());
1162 result.AppendMessage("");
1163 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001164
Kate Stoneb9c1b512016-09-06 20:57:50 +00001165 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1166 ++alias_pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001167 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001169 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001170 result.AppendMessage("");
1171 }
Greg Clayton14a35512011-09-11 00:01:44 +00001172
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173 if (!m_user_dict.empty() &&
1174 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1175 result.AppendMessage("Current user-defined commands:");
1176 result.AppendMessage("");
1177 max_len = FindLongestCommandWord(m_user_dict);
1178 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001179 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1180 pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001181 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001182 result.AppendMessage("");
1183 }
Greg Clayton14a35512011-09-11 00:01:44 +00001184
Kate Stoneb9c1b512016-09-06 20:57:50 +00001185 result.AppendMessageWithFormat(
1186 "For more information on any command, type '%shelp <command-name>'.\n",
1187 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001188}
1189
Zachary Turnera01bccd2016-10-05 21:14:56 +00001190CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1191 llvm::StringRef &command_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001192 // This function finds the final, lowest-level, alias-resolved command object
Adrian Prantl05097242018-04-30 16:49:04 +00001193 // whose 'Execute' function will eventually be invoked by the given command
1194 // line.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001195
1196 CommandObject *cmd_obj = nullptr;
1197 size_t start = command_string.find_first_not_of(k_white_space);
1198 size_t end = 0;
1199 bool done = false;
1200 while (!done) {
1201 if (start != std::string::npos) {
1202 // Get the next word from command_string.
1203 end = command_string.find_first_of(k_white_space, start);
1204 if (end == std::string::npos)
1205 end = command_string.size();
1206 std::string cmd_word = command_string.substr(start, end - start);
1207
1208 if (cmd_obj == nullptr)
1209 // Since cmd_obj is NULL we are on our first time through this loop.
Zachary Turnera01bccd2016-10-05 21:14:56 +00001210 // Check to see if cmd_word is a valid command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001211 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001212 else if (cmd_obj->IsMultiwordObject()) {
1213 // Our current object is a multi-word object; see if the cmd_word is a
1214 // valid sub-command for our object.
1215 CommandObject *sub_cmd_obj =
1216 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1217 if (sub_cmd_obj)
1218 cmd_obj = sub_cmd_obj;
1219 else // cmd_word was not a valid sub-command word, so we are done
1220 done = true;
1221 } else
1222 // We have a cmd_obj and it is not a multi-word object, so we are done.
1223 done = true;
1224
1225 // If we didn't find a valid command object, or our command object is not
Zachary Turnera01bccd2016-10-05 21:14:56 +00001226 // a multi-word object, or we are at the end of the command_string, then
1227 // we are done. Otherwise, find the start of the next word.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001228
1229 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1230 end >= command_string.size())
1231 done = true;
1232 else
1233 start = command_string.find_first_not_of(k_white_space, end);
1234 } else
1235 // Unable to find any more words.
1236 done = true;
1237 }
1238
Zachary Turnera01bccd2016-10-05 21:14:56 +00001239 command_string = command_string.substr(end);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001240 return cmd_obj;
1241}
1242
1243static const char *k_valid_command_chars =
1244 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1245static void StripLeadingSpaces(std::string &s) {
1246 if (!s.empty()) {
1247 size_t pos = s.find_first_not_of(k_white_space);
1248 if (pos == std::string::npos)
1249 s.clear();
1250 else if (pos == 0)
1251 return;
1252 s.erase(0, pos);
1253 }
1254}
1255
1256static size_t FindArgumentTerminator(const std::string &s) {
1257 const size_t s_len = s.size();
1258 size_t offset = 0;
1259 while (offset < s_len) {
1260 size_t pos = s.find("--", offset);
1261 if (pos == std::string::npos)
1262 break;
1263 if (pos > 0) {
1264 if (isspace(s[pos - 1])) {
Adrian Prantl05097242018-04-30 16:49:04 +00001265 // Check if the string ends "\s--" (where \s is a space character) or
1266 // if we have "\s--\s".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001267 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1268 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001269 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270 }
1271 }
1272 offset = pos + 2;
1273 }
1274 return std::string::npos;
1275}
1276
1277static bool ExtractCommand(std::string &command_string, std::string &command,
1278 std::string &suffix, char &quote_char) {
1279 command.clear();
1280 suffix.clear();
1281 StripLeadingSpaces(command_string);
1282
1283 bool result = false;
1284 quote_char = '\0';
1285
1286 if (!command_string.empty()) {
1287 const char first_char = command_string[0];
1288 if (first_char == '\'' || first_char == '"') {
1289 quote_char = first_char;
1290 const size_t end_quote_pos = command_string.find(quote_char, 1);
1291 if (end_quote_pos == std::string::npos) {
1292 command.swap(command_string);
1293 command_string.erase();
1294 } else {
1295 command.assign(command_string, 1, end_quote_pos - 1);
1296 if (end_quote_pos + 1 < command_string.size())
1297 command_string.erase(0, command_string.find_first_not_of(
1298 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001299 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001300 command_string.erase();
1301 }
1302 } else {
1303 const size_t first_space_pos =
1304 command_string.find_first_of(k_white_space);
1305 if (first_space_pos == std::string::npos) {
1306 command.swap(command_string);
1307 command_string.erase();
1308 } else {
1309 command.assign(command_string, 0, first_space_pos);
1310 command_string.erase(0, command_string.find_first_not_of(
1311 k_white_space, first_space_pos));
1312 }
1313 }
1314 result = true;
1315 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001316
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317 if (!command.empty()) {
1318 // actual commands can't start with '-' or '_'
1319 if (command[0] != '-' && command[0] != '_') {
1320 size_t pos = command.find_first_not_of(k_valid_command_chars);
1321 if (pos > 0 && pos != std::string::npos) {
1322 suffix.assign(command.begin() + pos, command.end());
1323 command.erase(pos);
1324 }
1325 }
1326 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001327
Kate Stoneb9c1b512016-09-06 20:57:50 +00001328 return result;
1329}
1330
1331CommandObject *CommandInterpreter::BuildAliasResult(
Zachary Turnera483f572016-10-05 21:14:49 +00001332 llvm::StringRef alias_name, std::string &raw_input_string,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001333 std::string &alias_result, CommandReturnObject &result) {
1334 CommandObject *alias_cmd_obj = nullptr;
1335 Args cmd_args(raw_input_string);
1336 alias_cmd_obj = GetCommandObject(alias_name);
1337 StreamString result_str;
1338
Zachary Turner5c28c662016-10-03 23:20:36 +00001339 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1340 alias_result.clear();
1341 return alias_cmd_obj;
1342 }
1343 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1344 ((CommandAlias *)alias_cmd_obj)->Desugar();
1345 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1346 alias_cmd_obj = desugared.first.get();
1347 std::string alias_name_str = alias_name;
1348 if ((cmd_args.GetArgumentCount() == 0) ||
1349 (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0))
1350 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001351
Zachary Turnera4496982016-10-05 21:14:38 +00001352 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001353
Zachary Turner5c28c662016-10-03 23:20:36 +00001354 if (!option_arg_vector_sp.get()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001355 alias_result = result_str.GetString();
Zachary Turner5c28c662016-10-03 23:20:36 +00001356 return alias_cmd_obj;
1357 }
1358 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001359
Zachary Turner5c28c662016-10-03 23:20:36 +00001360 int value_type;
1361 std::string option;
1362 std::string value;
1363 for (const auto &entry : *option_arg_vector) {
1364 std::tie(option, value_type, value) = entry;
1365 if (option == "<argument>") {
1366 result_str.Printf(" %s", value.c_str());
1367 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001368 }
1369
Zachary Turner5c28c662016-10-03 23:20:36 +00001370 result_str.Printf(" %s", option.c_str());
1371 if (value_type == OptionParser::eNoArgument)
1372 continue;
1373
1374 if (value_type != OptionParser::eOptionalArgument)
1375 result_str.Printf(" ");
1376 int index = GetOptionArgumentPosition(value.c_str());
1377 if (index == 0)
1378 result_str.Printf("%s", value.c_str());
1379 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1380
1381 result.AppendErrorWithFormat("Not enough arguments provided; you "
1382 "need at least %d arguments to use "
1383 "this alias.\n",
1384 index);
1385 result.SetStatus(eReturnStatusFailed);
1386 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001387 } else {
1388 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1389 if (strpos != std::string::npos)
1390 raw_input_string = raw_input_string.erase(
1391 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1392 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001393 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001394 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001395
Zachary Turnerc1564272016-11-16 21:15:24 +00001396 alias_result = result_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397 return alias_cmd_obj;
1398}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001399
Zachary Turner97206d52017-05-12 04:51:55 +00001400Status CommandInterpreter::PreprocessCommand(std::string &command) {
Adrian Prantl05097242018-04-30 16:49:04 +00001401 // The command preprocessor needs to do things to the command line before any
1402 // parsing of arguments or anything else is done. The only current stuff that
1403 // gets preprocessed is anything enclosed in backtick ('`') characters is
1404 // evaluated as an expression and the result of the expression must be a
1405 // scalar that can be substituted into the command. An example would be:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001406 // (lldb) memory read `$rsp + 20`
Zachary Turner97206d52017-05-12 04:51:55 +00001407 Status error; // Status for any expressions that might not evaluate
Kate Stoneb9c1b512016-09-06 20:57:50 +00001408 size_t start_backtick;
1409 size_t pos = 0;
1410 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1411 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
Adrian Prantl05097242018-04-30 16:49:04 +00001412 // The backtick was preceded by a '\' character, remove the slash and
1413 // don't treat the backtick as the start of an expression
Kate Stoneb9c1b512016-09-06 20:57:50 +00001414 command.erase(start_backtick - 1, 1);
1415 // No need to add one to start_backtick since we just deleted a char
1416 pos = start_backtick;
1417 } else {
1418 const size_t expr_content_start = start_backtick + 1;
1419 const size_t end_backtick = command.find('`', expr_content_start);
1420 if (end_backtick == std::string::npos)
1421 return error;
1422 else if (end_backtick == expr_content_start) {
1423 // Empty expression (two backticks in a row)
1424 command.erase(start_backtick, 2);
1425 } else {
1426 std::string expr_str(command, expr_content_start,
1427 end_backtick - expr_content_start);
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001428
Kate Stoneb9c1b512016-09-06 20:57:50 +00001429 ExecutionContext exe_ctx(GetExecutionContext());
1430 Target *target = exe_ctx.GetTargetPtr();
1431 // Get a dummy target to allow for calculator mode while processing
Adrian Prantl05097242018-04-30 16:49:04 +00001432 // backticks. This also helps break the infinite loop caused when
1433 // target is null.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001434 if (!target)
1435 target = m_debugger.GetDummyTarget();
1436 if (target) {
1437 ValueObjectSP expr_result_valobj_sp;
1438
1439 EvaluateExpressionOptions options;
1440 options.SetCoerceToId(false);
1441 options.SetUnwindOnError(true);
1442 options.SetIgnoreBreakpoints(true);
1443 options.SetKeepInMemory(false);
1444 options.SetTryAllThreads(true);
Pavel Labath43d35412016-12-06 11:24:51 +00001445 options.SetTimeout(llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001446
1447 ExpressionResults expr_result = target->EvaluateExpression(
1448 expr_str.c_str(), exe_ctx.GetFramePtr(), expr_result_valobj_sp,
1449 options);
1450
1451 if (expr_result == eExpressionCompleted) {
1452 Scalar scalar;
1453 if (expr_result_valobj_sp)
1454 expr_result_valobj_sp =
1455 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1456 expr_result_valobj_sp->GetDynamicValueType(), true);
1457 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1458 command.erase(start_backtick, end_backtick - start_backtick + 1);
1459 StreamString value_strm;
1460 const bool show_type = false;
1461 scalar.GetValue(&value_strm, show_type);
1462 size_t value_string_size = value_strm.GetSize();
1463 if (value_string_size) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001464 command.insert(start_backtick, value_strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001465 pos = start_backtick + value_string_size;
1466 continue;
1467 } else {
1468 error.SetErrorStringWithFormat("expression value didn't result "
1469 "in a scalar value for the "
1470 "expression '%s'",
1471 expr_str.c_str());
1472 }
1473 } else {
1474 error.SetErrorStringWithFormat("expression value didn't result "
1475 "in a scalar value for the "
1476 "expression '%s'",
1477 expr_str.c_str());
1478 }
1479 } else {
1480 if (expr_result_valobj_sp)
1481 error = expr_result_valobj_sp->GetError();
1482 if (error.Success()) {
1483
1484 switch (expr_result) {
1485 case eExpressionSetupError:
1486 error.SetErrorStringWithFormat(
1487 "expression setup error for the expression '%s'",
1488 expr_str.c_str());
1489 break;
1490 case eExpressionParseError:
1491 error.SetErrorStringWithFormat(
1492 "expression parse error for the expression '%s'",
1493 expr_str.c_str());
1494 break;
1495 case eExpressionResultUnavailable:
1496 error.SetErrorStringWithFormat(
1497 "expression error fetching result for the expression '%s'",
1498 expr_str.c_str());
1499 break;
1500 case eExpressionCompleted:
1501 break;
1502 case eExpressionDiscarded:
1503 error.SetErrorStringWithFormat(
1504 "expression discarded for the expression '%s'",
1505 expr_str.c_str());
1506 break;
1507 case eExpressionInterrupted:
1508 error.SetErrorStringWithFormat(
1509 "expression interrupted for the expression '%s'",
1510 expr_str.c_str());
1511 break;
1512 case eExpressionHitBreakpoint:
1513 error.SetErrorStringWithFormat(
1514 "expression hit breakpoint for the expression '%s'",
1515 expr_str.c_str());
1516 break;
1517 case eExpressionTimedOut:
1518 error.SetErrorStringWithFormat(
1519 "expression timed out for the expression '%s'",
1520 expr_str.c_str());
1521 break;
1522 case eExpressionStoppedForDebug:
1523 error.SetErrorStringWithFormat("expression stop at entry point "
1524 "for debugging for the "
1525 "expression '%s'",
1526 expr_str.c_str());
1527 break;
1528 }
1529 }
1530 }
1531 }
1532 }
1533 if (error.Fail())
1534 break;
1535 }
1536 }
1537 return error;
1538}
1539
1540bool CommandInterpreter::HandleCommand(const char *command_line,
1541 LazyBool lazy_add_to_history,
1542 CommandReturnObject &result,
1543 ExecutionContext *override_context,
1544 bool repeat_on_empty_command,
1545 bool no_context_switching)
1546
1547{
1548
1549 std::string command_string(command_line);
1550 std::string original_command_string(command_line);
1551
1552 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
Jim Ingham8f7db522016-12-15 00:30:30 +00001553 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
Sean Callanan237c3ed2016-12-14 21:31:31 +00001554 command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001555
1556 if (log)
1557 log->Printf("Processing command: %s", command_line);
1558
Pavel Labathf9d16472017-05-15 13:02:37 +00001559 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1560 Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001561
1562 if (!no_context_switching)
1563 UpdateExecutionContext(override_context);
1564
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001565 if (WasInterrupted()) {
1566 result.AppendError("interrupted");
1567 result.SetStatus(eReturnStatusFailed);
1568 return false;
1569 }
1570
Kate Stoneb9c1b512016-09-06 20:57:50 +00001571 bool add_to_history;
1572 if (lazy_add_to_history == eLazyBoolCalculate)
1573 add_to_history = (m_command_source_depth == 0);
1574 else
1575 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1576
1577 bool empty_command = false;
1578 bool comment_command = false;
1579 if (command_string.empty())
1580 empty_command = true;
1581 else {
1582 const char *k_space_characters = "\t\n\v\f\r ";
1583
1584 size_t non_space = command_string.find_first_not_of(k_space_characters);
Adrian Prantl05097242018-04-30 16:49:04 +00001585 // Check for empty line or comment line (lines whose first non-space
1586 // character is the comment character for this interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001587 if (non_space == std::string::npos)
1588 empty_command = true;
1589 else if (command_string[non_space] == m_comment_char)
1590 comment_command = true;
1591 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001592 llvm::StringRef search_str(command_string);
1593 search_str = search_str.drop_front(non_space);
1594 if (auto hist_str = m_command_history.FindString(search_str)) {
1595 add_to_history = false;
1596 command_string = *hist_str;
1597 original_command_string = *hist_str;
1598 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001599 result.AppendErrorWithFormat("Could not find entry: %s in history",
1600 command_string.c_str());
1601 result.SetStatus(eReturnStatusFailed);
1602 return false;
1603 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001604 }
1605 }
1606
1607 if (empty_command) {
1608 if (repeat_on_empty_command) {
1609 if (m_command_history.IsEmpty()) {
1610 result.AppendError("empty command");
1611 result.SetStatus(eReturnStatusFailed);
1612 return false;
1613 } else {
1614 command_line = m_repeat_command.c_str();
1615 command_string = command_line;
1616 original_command_string = command_line;
1617 if (m_repeat_command.empty()) {
1618 result.AppendErrorWithFormat("No auto repeat.\n");
1619 result.SetStatus(eReturnStatusFailed);
1620 return false;
1621 }
1622 }
1623 add_to_history = false;
1624 } else {
1625 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1626 return true;
1627 }
1628 } else if (comment_command) {
1629 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1630 return true;
1631 }
1632
Zachary Turner97206d52017-05-12 04:51:55 +00001633 Status error(PreprocessCommand(command_string));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001634
1635 if (error.Fail()) {
1636 result.AppendError(error.AsCString());
1637 result.SetStatus(eReturnStatusFailed);
1638 return false;
1639 }
1640
1641 // Phase 1.
1642
1643 // Before we do ANY kind of argument processing, we need to figure out what
1644 // the real/final command object is for the specified command. This gets
1645 // complicated by the fact that the user could have specified an alias, and,
1646 // in translating the alias, there may also be command options and/or even
1647 // data (including raw text strings) that need to be found and inserted into
1648 // the command line as part of the translation. So this first step is plain
1649 // look-up and replacement, resulting in:
1650 // 1. the command object whose Execute method will actually be called
1651 // 2. a revised command string, with all substitutions and replacements
1652 // taken care of
1653 // From 1 above, we can determine whether the Execute function wants raw
1654 // input or not.
1655
1656 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1657
1658 // Although the user may have abbreviated the command, the command_string now
Adrian Prantl05097242018-04-30 16:49:04 +00001659 // has the command expanded to the full name. For example, if the input was
1660 // "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001661 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001662 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1663 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001664 log->Printf("HandleCommand, (revised) command_string: '%s'",
1665 command_string.c_str());
1666 const bool wants_raw_input =
1667 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1668 log->Printf("HandleCommand, wants_raw_input:'%s'",
1669 wants_raw_input ? "True" : "False");
1670 }
1671
1672 // Phase 2.
1673 // Take care of things like setting up the history command & calling the
Adrian Prantl05097242018-04-30 16:49:04 +00001674 // appropriate Execute method on the CommandObject, with the appropriate
1675 // arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001676
1677 if (cmd_obj != nullptr) {
1678 if (add_to_history) {
1679 Args command_args(command_string);
1680 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1681 if (repeat_command != nullptr)
1682 m_repeat_command.assign(repeat_command);
1683 else
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001684 m_repeat_command.assign(original_command_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001685
1686 m_command_history.AppendString(original_command_string);
1687 }
1688
1689 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001690 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001691 if (actual_cmd_name_len < command_string.length())
1692 remainder = command_string.substr(actual_cmd_name_len);
1693
1694 // Remove any initial spaces
1695 size_t pos = remainder.find_first_not_of(k_white_space);
1696 if (pos != 0 && pos != std::string::npos)
1697 remainder.erase(0, pos);
1698
1699 if (log)
1700 log->Printf(
1701 "HandleCommand, command line after removing command name(s): '%s'",
1702 remainder.c_str());
1703
1704 cmd_obj->Execute(remainder.c_str(), result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001705 }
1706
1707 if (log)
1708 log->Printf("HandleCommand, command %s",
1709 (result.Succeeded() ? "succeeded" : "did not succeed"));
1710
1711 return result.Succeeded();
1712}
1713
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001714int CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001715 int num_command_matches = 0;
1716 bool look_for_subcommand = false;
1717
1718 // For any of the command completions a unique match will be a complete word.
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001719 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001720
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001721 if (request.GetCursorIndex() == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001722 // We got nothing on the command line, so return the list of commands
1723 bool include_aliases = true;
Raphael Isemann7f888292018-09-13 21:26:00 +00001724 StringList new_matches, descriptions;
1725 num_command_matches = GetCommandNamesMatchingPartialString(
1726 "", include_aliases, new_matches, descriptions);
1727 request.AddCompletions(new_matches, descriptions);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001728 } else if (request.GetCursorIndex() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001729 // The cursor is in the first argument, so just do a lookup in the
1730 // dictionary.
Raphael Isemann7f888292018-09-13 21:26:00 +00001731 StringList new_matches, new_descriptions;
1732 CommandObject *cmd_obj =
1733 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0),
1734 &new_matches, &new_descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001735
1736 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001737 new_matches.GetStringAtIndex(0) != nullptr &&
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001738 strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001739 new_matches.GetStringAtIndex(0)) == 0) {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001740 if (request.GetParsedLine().GetArgumentCount() == 1) {
1741 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001742 } else {
1743 look_for_subcommand = true;
1744 num_command_matches = 0;
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001745 new_matches.DeleteStringAtIndex(0);
Raphael Isemann7f888292018-09-13 21:26:00 +00001746 new_descriptions.DeleteStringAtIndex(0);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001747 request.GetParsedLine().AppendArgument(llvm::StringRef());
1748 request.SetCursorIndex(request.GetCursorIndex() + 1);
1749 request.SetCursorCharPosition(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001750 }
1751 }
Raphael Isemann7f888292018-09-13 21:26:00 +00001752 request.AddCompletions(new_matches, new_descriptions);
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001753 num_command_matches = request.GetNumberOfMatches();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001754 }
1755
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001756 if (request.GetCursorIndex() > 0 || look_for_subcommand) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001757 // We are completing further on into a commands arguments, so find the
Adrian Prantl05097242018-04-30 16:49:04 +00001758 // command and tell it to complete the command. First see if there is a
1759 // matching initial command:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001760 CommandObject *command_object =
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001761 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001762 if (command_object == nullptr) {
1763 return 0;
1764 } else {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001765 request.GetParsedLine().Shift();
1766 request.SetCursorIndex(request.GetCursorIndex() - 1);
1767 num_command_matches = command_object->HandleCompletion(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001768 }
1769 }
1770
1771 return num_command_matches;
1772}
1773
1774int CommandInterpreter::HandleCompletion(
1775 const char *current_line, const char *cursor, const char *last_char,
Raphael Isemann7f888292018-09-13 21:26:00 +00001776 int match_start_point, int max_return_elements, StringList &matches,
1777 StringList &descriptions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001778
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001779 llvm::StringRef command_line(current_line, last_char - current_line);
Raphael Isemann7f888292018-09-13 21:26:00 +00001780 CompletionResult result;
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001781 CompletionRequest request(command_line, cursor - current_line,
Raphael Isemann7f888292018-09-13 21:26:00 +00001782 match_start_point, max_return_elements, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001783 // Don't complete comments, and if the line we are completing is just the
Adrian Prantl05097242018-04-30 16:49:04 +00001784 // history repeat character, substitute the appropriate history line.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001785 const char *first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001786 if (first_arg) {
1787 if (first_arg[0] == m_comment_char)
1788 return 0;
1789 else if (first_arg[0] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001790 if (auto hist_str = m_command_history.FindString(first_arg)) {
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001791 matches.InsertStringAtIndex(0, *hist_str);
Raphael Isemann7f888292018-09-13 21:26:00 +00001792 descriptions.InsertStringAtIndex(0, "Previous command history event");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001793 return -2;
1794 } else
1795 return 0;
1796 }
1797 }
1798
Kate Stoneb9c1b512016-09-06 20:57:50 +00001799 // Only max_return_elements == -1 is supported at present:
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001800 lldbassert(max_return_elements == -1);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001801
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001802 int num_command_matches = HandleCompletionMatches(request);
Raphael Isemann7f888292018-09-13 21:26:00 +00001803 result.GetMatches(matches);
1804 result.GetDescriptions(descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001805
1806 if (num_command_matches <= 0)
1807 return num_command_matches;
1808
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001809 if (request.GetParsedLine().GetArgumentCount() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001810 // If we got an empty string, insert nothing.
1811 matches.InsertStringAtIndex(0, "");
Raphael Isemann7f888292018-09-13 21:26:00 +00001812 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001813 } else {
1814 // Now figure out if there is a common substring, and if so put that in
Adrian Prantl05097242018-04-30 16:49:04 +00001815 // element 0, otherwise put an empty string in element 0.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001816 std::string command_partial_str = request.GetCursorArgumentPrefix().str();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001817
1818 std::string common_prefix;
1819 matches.LongestCommonPrefix(common_prefix);
1820 const size_t partial_name_len = command_partial_str.size();
1821 common_prefix.erase(0, partial_name_len);
1822
Adrian Prantl05097242018-04-30 16:49:04 +00001823 // If we matched a unique single command, add a space... Only do this if
1824 // the completer told us this was a complete word, however...
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001825 if (num_command_matches == 1 && request.GetWordComplete()) {
1826 char quote_char = request.GetParsedLine()[request.GetCursorIndex()].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001827 common_prefix =
1828 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1829 if (quote_char != '\0')
1830 common_prefix.push_back(quote_char);
1831 common_prefix.push_back(' ');
1832 }
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001833 matches.InsertStringAtIndex(0, common_prefix.c_str());
Raphael Isemann7f888292018-09-13 21:26:00 +00001834 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001835 }
1836 return num_command_matches;
1837}
1838
1839CommandInterpreter::~CommandInterpreter() {}
1840
Zachary Turner514d8cd2016-09-23 18:06:53 +00001841void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001842 EventSP prompt_change_event_sp(
1843 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1844 ;
1845 BroadcastEvent(prompt_change_event_sp);
1846 if (m_command_io_handler_sp)
1847 m_command_io_handler_sp->SetPrompt(new_prompt);
1848}
1849
Zachary Turner7a120c82016-11-13 03:05:58 +00001850bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001851 // Check AutoConfirm first:
1852 if (m_debugger.GetAutoConfirm())
1853 return default_answer;
1854
1855 IOHandlerConfirm *confirm =
1856 new IOHandlerConfirm(m_debugger, message, default_answer);
1857 IOHandlerSP io_handler_sp(confirm);
1858 m_debugger.RunIOHandler(io_handler_sp);
1859 return confirm->GetResponse();
1860}
1861
Zachary Turnera483f572016-10-05 21:14:49 +00001862const CommandAlias *
1863CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001864 OptionArgVectorSP ret_val;
1865
Zachary Turnera483f572016-10-05 21:14:49 +00001866 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001867 if (pos != m_alias_dict.end())
1868 return (CommandAlias *)pos->second.get();
1869
1870 return nullptr;
1871}
1872
Zachary Turnera4496982016-10-05 21:14:38 +00001873bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001874
Zachary Turnera4496982016-10-05 21:14:38 +00001875bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001876
Zachary Turnera4496982016-10-05 21:14:38 +00001877bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001878
Zachary Turnera4496982016-10-05 21:14:38 +00001879bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001880
1881void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1882 const char *alias_name,
1883 Args &cmd_args,
1884 std::string &raw_input_string,
1885 CommandReturnObject &result) {
1886 OptionArgVectorSP option_arg_vector_sp =
1887 GetAlias(alias_name)->GetOptionArguments();
1888
1889 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1890
1891 // Make sure that the alias name is the 0th element in cmd_args
1892 std::string alias_name_str = alias_name;
1893 if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)
Zachary Turner5c725f32016-09-19 21:56:59 +00001894 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001895
1896 Args new_args(alias_cmd_obj->GetCommandName());
1897 if (new_args.GetArgumentCount() == 2)
1898 new_args.Shift();
1899
1900 if (option_arg_vector_sp.get()) {
1901 if (wants_raw_input) {
1902 // We have a command that both has command options and takes raw input.
Adrian Prantl05097242018-04-30 16:49:04 +00001903 // Make *sure* it has a " -- " in the right place in the
1904 // raw_input_string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001905 size_t pos = raw_input_string.find(" -- ");
1906 if (pos == std::string::npos) {
1907 // None found; assume it goes at the beginning of the raw input string
1908 raw_input_string.insert(0, " -- ");
1909 }
1910 }
1911
1912 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1913 const size_t old_size = cmd_args.GetArgumentCount();
1914 std::vector<bool> used(old_size + 1, false);
1915
1916 used[0] = true;
1917
Zachary Turner5c28c662016-10-03 23:20:36 +00001918 int value_type;
1919 std::string option;
1920 std::string value;
1921 for (const auto &option_entry : *option_arg_vector) {
1922 std::tie(option, value_type, value) = option_entry;
1923 if (option == "<argument>") {
1924 if (!wants_raw_input || (value != "--")) {
1925 // Since we inserted this above, make sure we don't insert it twice
1926 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001927 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001928 continue;
1929 }
1930
1931 if (value_type != OptionParser::eOptionalArgument)
1932 new_args.AppendArgument(option);
1933
1934 if (value == "<no-argument>")
1935 continue;
1936
1937 int index = GetOptionArgumentPosition(value.c_str());
1938 if (index == 0) {
1939 // value was NOT a positional argument; must be a real value
1940 if (value_type != OptionParser::eOptionalArgument)
1941 new_args.AppendArgument(value);
1942 else {
1943 char buffer[255];
1944 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1945 value.c_str());
1946 new_args.AppendArgument(llvm::StringRef(buffer));
1947 }
1948
1949 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1950 result.AppendErrorWithFormat("Not enough arguments provided; you "
1951 "need at least %d arguments to use "
1952 "this alias.\n",
1953 index);
1954 result.SetStatus(eReturnStatusFailed);
1955 return;
1956 } else {
1957 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1958 size_t strpos =
1959 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1960 if (strpos != std::string::npos) {
1961 raw_input_string = raw_input_string.erase(
1962 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1963 }
1964
1965 if (value_type != OptionParser::eOptionalArgument)
1966 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
1967 else {
1968 char buffer[255];
1969 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1970 cmd_args.GetArgumentAtIndex(index));
1971 new_args.AppendArgument(buffer);
1972 }
1973 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001974 }
1975 }
1976
Zachary Turner97d2c402016-10-05 23:40:23 +00001977 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00001978 if (!used[entry.index()] && !wants_raw_input)
1979 new_args.AppendArgument(entry.value().ref);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001980 }
1981
1982 cmd_args.Clear();
1983 cmd_args.SetArguments(new_args.GetArgumentCount(),
1984 new_args.GetConstArgumentVector());
1985 } else {
1986 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1987 // This alias was not created with any options; nothing further needs to be
Adrian Prantl05097242018-04-30 16:49:04 +00001988 // done, unless it is a command that wants raw input, in which case we need
1989 // to clear the rest of the data from cmd_args, since its in the raw input
1990 // string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001991 if (wants_raw_input) {
1992 cmd_args.Clear();
1993 cmd_args.SetArguments(new_args.GetArgumentCount(),
1994 new_args.GetConstArgumentVector());
1995 }
1996 return;
1997 }
1998
1999 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2000 return;
2001}
2002
2003int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2004 int position = 0; // Any string that isn't an argument position, i.e. '%'
2005 // followed by an integer, gets a position
2006 // of zero.
2007
2008 const char *cptr = in_string;
2009
2010 // Does it start with '%'
2011 if (cptr[0] == '%') {
2012 ++cptr;
2013
2014 // Is the rest of it entirely digits?
2015 if (isdigit(cptr[0])) {
2016 const char *start = cptr;
2017 while (isdigit(cptr[0]))
2018 ++cptr;
2019
Adrian Prantl05097242018-04-30 16:49:04 +00002020 // We've gotten to the end of the digits; are we at the end of the
2021 // string?
Kate Stoneb9c1b512016-09-06 20:57:50 +00002022 if (cptr[0] == '\0')
2023 position = atoi(start);
2024 }
2025 }
2026
2027 return position;
2028}
2029
2030void CommandInterpreter::SourceInitFile(bool in_cwd,
2031 CommandReturnObject &result) {
2032 FileSpec init_file;
2033 if (in_cwd) {
2034 ExecutionContext exe_ctx(GetExecutionContext());
2035 Target *target = exe_ctx.GetTargetPtr();
2036 if (target) {
2037 // In the current working directory we don't load any program specific
2038 // .lldbinit files, we only look for a ".lldbinit" file.
2039 if (m_skip_lldbinit_files)
2040 return;
2041
2042 LoadCWDlldbinitFile should_load =
2043 target->TargetProperties::GetLoadCWDlldbinitFile();
2044 if (should_load == eLoadCWDlldbinitWarn) {
2045 FileSpec dot_lldb(".lldbinit", true);
2046 llvm::SmallString<64> home_dir_path;
2047 llvm::sys::path::home_directory(home_dir_path);
2048 FileSpec homedir_dot_lldb(home_dir_path.c_str(), false);
2049 homedir_dot_lldb.AppendPathComponent(".lldbinit");
2050 homedir_dot_lldb.ResolvePath();
2051 if (dot_lldb.Exists() &&
2052 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2053 result.AppendErrorWithFormat(
2054 "There is a .lldbinit file in the current directory which is not "
2055 "being read.\n"
2056 "To silence this warning without sourcing in the local "
2057 ".lldbinit,\n"
2058 "add the following to the lldbinit file in your home directory:\n"
2059 " settings set target.load-cwd-lldbinit false\n"
2060 "To allow lldb to source .lldbinit files in the current working "
2061 "directory,\n"
2062 "set the value of this variable to true. Only do so if you "
2063 "understand and\n"
2064 "accept the security risk.");
2065 result.SetStatus(eReturnStatusFailed);
2066 return;
2067 }
2068 } else if (should_load == eLoadCWDlldbinitTrue) {
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002069 init_file.SetFile("./.lldbinit", true, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002070 }
2071 }
2072 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002073 // If we aren't looking in the current working directory we are looking in
2074 // the home directory. We will first see if there is an application
2075 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a "-"
2076 // and the name of the program. If this file doesn't exist, we fall back to
2077 // just the "~/.lldbinit" file. We also obey any requests to not load the
2078 // init files.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002079 llvm::SmallString<64> home_dir_path;
2080 llvm::sys::path::home_directory(home_dir_path);
2081 FileSpec profilePath(home_dir_path.c_str(), false);
2082 profilePath.AppendPathComponent(".lldbinit");
2083 std::string init_file_path = profilePath.GetPath();
2084
2085 if (m_skip_app_init_files == false) {
2086 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2087 const char *program_name = program_file_spec.GetFilename().AsCString();
2088
2089 if (program_name) {
2090 char program_init_file_name[PATH_MAX];
2091 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2092 "%s-%s", init_file_path.c_str(), program_name);
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002093 init_file.SetFile(program_init_file_name, true,
2094 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002095 if (!init_file.Exists())
2096 init_file.Clear();
2097 }
2098 }
2099
2100 if (!init_file && !m_skip_lldbinit_files)
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002101 init_file.SetFile(init_file_path, false, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002102 }
2103
2104 // If the file exists, tell HandleCommand to 'source' it; this will do the
Adrian Prantl05097242018-04-30 16:49:04 +00002105 // actual broadcasting of the commands back to any appropriate listener (see
Kate Stoneb9c1b512016-09-06 20:57:50 +00002106 // CommandObjectSource::Execute for more details).
2107
2108 if (init_file.Exists()) {
2109 const bool saved_batch = SetBatchCommandMode(true);
2110 CommandInterpreterRunOptions options;
2111 options.SetSilent(true);
2112 options.SetStopOnError(false);
2113 options.SetStopOnContinue(true);
2114
2115 HandleCommandsFromFile(init_file,
2116 nullptr, // Execution context
2117 options, result);
2118 SetBatchCommandMode(saved_batch);
2119 } else {
2120 // nothing to be done if the file doesn't exist
2121 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2122 }
2123}
2124
2125const char *CommandInterpreter::GetCommandPrefix() {
2126 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2127 return prefix == NULL ? "" : prefix;
2128}
2129
2130PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2131 PlatformSP platform_sp;
2132 if (prefer_target_platform) {
2133 ExecutionContext exe_ctx(GetExecutionContext());
2134 Target *target = exe_ctx.GetTargetPtr();
2135 if (target)
2136 platform_sp = target->GetPlatform();
2137 }
2138
2139 if (!platform_sp)
2140 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2141 return platform_sp;
2142}
2143
2144void CommandInterpreter::HandleCommands(const StringList &commands,
2145 ExecutionContext *override_context,
2146 CommandInterpreterRunOptions &options,
2147 CommandReturnObject &result) {
2148 size_t num_lines = commands.GetSize();
2149
2150 // If we are going to continue past a "continue" then we need to run the
Adrian Prantl05097242018-04-30 16:49:04 +00002151 // commands synchronously. Make sure you reset this value anywhere you return
2152 // from the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002153
2154 bool old_async_execution = m_debugger.GetAsyncExecution();
2155
2156 // If we've been given an execution context, set it at the start, but don't
Adrian Prantl05097242018-04-30 16:49:04 +00002157 // keep resetting it or we will cause series of commands that change the
2158 // context, then do an operation that relies on that context to fail.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002159
2160 if (override_context != nullptr)
2161 UpdateExecutionContext(override_context);
2162
2163 if (!options.GetStopOnContinue()) {
2164 m_debugger.SetAsyncExecution(false);
2165 }
2166
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002167 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002168 const char *cmd = commands.GetStringAtIndex(idx);
2169 if (cmd[0] == '\0')
2170 continue;
2171
2172 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002173 // TODO: Add Stream support.
2174 result.AppendMessageWithFormat("%s %s\n",
2175 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002176 }
2177
2178 CommandReturnObject tmp_result;
2179 // If override_context is not NULL, pass no_context_switching = true for
2180 // HandleCommand() since we updated our context already.
2181
2182 // We might call into a regex or alias command, in which case the
Adrian Prantl05097242018-04-30 16:49:04 +00002183 // add_to_history will get lost. This m_command_source_depth dingus is the
2184 // way we turn off adding to the history in that case, so set it up here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002185 if (!options.GetAddToHistory())
2186 m_command_source_depth++;
2187 bool success =
2188 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2189 nullptr, /* override_context */
2190 true, /* repeat_on_empty_command */
2191 override_context != nullptr /* no_context_switching */);
2192 if (!options.GetAddToHistory())
2193 m_command_source_depth--;
2194
2195 if (options.GetPrintResults()) {
2196 if (tmp_result.Succeeded())
Zachary Turner03c9f362016-11-14 23:23:31 +00002197 result.AppendMessage(tmp_result.GetOutputData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002198 }
2199
2200 if (!success || !tmp_result.Succeeded()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002201 llvm::StringRef error_msg = tmp_result.GetErrorData();
2202 if (error_msg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002203 error_msg = "<unknown error>.\n";
2204 if (options.GetStopOnError()) {
2205 result.AppendErrorWithFormat(
2206 "Aborting reading of commands after command #%" PRIu64
2207 ": '%s' failed with %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00002208 (uint64_t)idx, cmd, error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002209 result.SetStatus(eReturnStatusFailed);
2210 m_debugger.SetAsyncExecution(old_async_execution);
2211 return;
2212 } else if (options.GetPrintResults()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002213 result.AppendMessageWithFormat(
2214 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2215 error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002216 }
2217 }
2218
2219 if (result.GetImmediateOutputStream())
2220 result.GetImmediateOutputStream()->Flush();
2221
2222 if (result.GetImmediateErrorStream())
2223 result.GetImmediateErrorStream()->Flush();
2224
Adrian Prantl05097242018-04-30 16:49:04 +00002225 // N.B. Can't depend on DidChangeProcessState, because the state coming
2226 // into the command execution could be running (for instance in Breakpoint
2227 // Commands. So we check the return value to see if it is has running in
2228 // it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002229 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2230 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2231 if (options.GetStopOnContinue()) {
2232 // If we caused the target to proceed, and we're going to stop in that
Adrian Prantl05097242018-04-30 16:49:04 +00002233 // case, set the status in our real result before returning. This is
2234 // an error if the continue was not the last command in the set of
2235 // commands to be run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002236 if (idx != num_lines - 1)
2237 result.AppendErrorWithFormat(
2238 "Aborting reading of commands after command #%" PRIu64
2239 ": '%s' continued the target.\n",
2240 (uint64_t)idx + 1, cmd);
2241 else
2242 result.AppendMessageWithFormat("Command #%" PRIu64
2243 " '%s' continued the target.\n",
2244 (uint64_t)idx + 1, cmd);
2245
2246 result.SetStatus(tmp_result.GetStatus());
2247 m_debugger.SetAsyncExecution(old_async_execution);
2248
2249 return;
2250 }
2251 }
2252
2253 // Also check for "stop on crash here:
2254 bool should_stop = false;
2255 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2256 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2257 if (target_sp) {
2258 ProcessSP process_sp(target_sp->GetProcessSP());
2259 if (process_sp) {
2260 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2261 StopReason reason = thread_sp->GetStopReason();
2262 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2263 reason == eStopReasonInstrumentation) {
2264 should_stop = true;
2265 break;
2266 }
2267 }
2268 }
2269 }
2270 if (should_stop) {
2271 if (idx != num_lines - 1)
2272 result.AppendErrorWithFormat(
2273 "Aborting reading of commands after command #%" PRIu64
2274 ": '%s' stopped with a signal or exception.\n",
2275 (uint64_t)idx + 1, cmd);
2276 else
2277 result.AppendMessageWithFormat(
2278 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\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
2289 result.SetStatus(eReturnStatusSuccessFinishResult);
2290 m_debugger.SetAsyncExecution(old_async_execution);
2291
2292 return;
2293}
2294
2295// Make flags that we can pass into the IOHandler so our delegates can do the
2296// right thing
2297enum {
2298 eHandleCommandFlagStopOnContinue = (1u << 0),
2299 eHandleCommandFlagStopOnError = (1u << 1),
2300 eHandleCommandFlagEchoCommand = (1u << 2),
2301 eHandleCommandFlagPrintResult = (1u << 3),
2302 eHandleCommandFlagStopOnCrash = (1u << 4)
2303};
2304
2305void CommandInterpreter::HandleCommandsFromFile(
2306 FileSpec &cmd_file, ExecutionContext *context,
2307 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2308 if (cmd_file.Exists()) {
2309 StreamFileSP input_file_sp(new StreamFile());
2310
2311 std::string cmd_file_path = cmd_file.GetPath();
Zachary Turner97206d52017-05-12 04:51:55 +00002312 Status error = input_file_sp->GetFile().Open(cmd_file_path.c_str(),
2313 File::eOpenOptionRead);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002314
2315 if (error.Success()) {
2316 Debugger &debugger = GetDebugger();
2317
2318 uint32_t flags = 0;
2319
2320 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2321 if (m_command_source_flags.empty()) {
2322 // Stop on continue by default
2323 flags |= eHandleCommandFlagStopOnContinue;
2324 } else if (m_command_source_flags.back() &
2325 eHandleCommandFlagStopOnContinue) {
2326 flags |= eHandleCommandFlagStopOnContinue;
2327 }
2328 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2329 flags |= eHandleCommandFlagStopOnContinue;
2330 }
2331
2332 if (options.m_stop_on_error == eLazyBoolCalculate) {
2333 if (m_command_source_flags.empty()) {
2334 if (GetStopCmdSourceOnError())
2335 flags |= eHandleCommandFlagStopOnError;
2336 } else if (m_command_source_flags.back() &
2337 eHandleCommandFlagStopOnError) {
2338 flags |= eHandleCommandFlagStopOnError;
2339 }
2340 } else if (options.m_stop_on_error == eLazyBoolYes) {
2341 flags |= eHandleCommandFlagStopOnError;
2342 }
2343
2344 if (options.GetStopOnCrash()) {
2345 if (m_command_source_flags.empty()) {
2346 // Echo command by default
2347 flags |= eHandleCommandFlagStopOnCrash;
2348 } else if (m_command_source_flags.back() &
2349 eHandleCommandFlagStopOnCrash) {
2350 flags |= eHandleCommandFlagStopOnCrash;
2351 }
2352 }
2353
2354 if (options.m_echo_commands == eLazyBoolCalculate) {
2355 if (m_command_source_flags.empty()) {
2356 // Echo command by default
2357 flags |= eHandleCommandFlagEchoCommand;
2358 } else if (m_command_source_flags.back() &
2359 eHandleCommandFlagEchoCommand) {
2360 flags |= eHandleCommandFlagEchoCommand;
2361 }
2362 } else if (options.m_echo_commands == eLazyBoolYes) {
2363 flags |= eHandleCommandFlagEchoCommand;
2364 }
2365
2366 if (options.m_print_results == eLazyBoolCalculate) {
2367 if (m_command_source_flags.empty()) {
2368 // Print output by default
2369 flags |= eHandleCommandFlagPrintResult;
2370 } else if (m_command_source_flags.back() &
2371 eHandleCommandFlagPrintResult) {
2372 flags |= eHandleCommandFlagPrintResult;
2373 }
2374 } else if (options.m_print_results == eLazyBoolYes) {
2375 flags |= eHandleCommandFlagPrintResult;
2376 }
2377
2378 if (flags & eHandleCommandFlagPrintResult) {
2379 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2380 cmd_file_path.c_str());
2381 }
2382
Adrian Prantl05097242018-04-30 16:49:04 +00002383 // Used for inheriting the right settings when "command source" might
2384 // have nested "command source" commands
Kate Stoneb9c1b512016-09-06 20:57:50 +00002385 lldb::StreamFileSP empty_stream_sp;
2386 m_command_source_flags.push_back(flags);
2387 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2388 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2389 empty_stream_sp, // Pass in an empty stream so we inherit the top
2390 // input reader output stream
2391 empty_stream_sp, // Pass in an empty stream so we inherit the top
2392 // input reader error stream
2393 flags,
2394 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2395 // or written
Zachary Turner514d8cd2016-09-23 18:06:53 +00002396 debugger.GetPrompt(), llvm::StringRef(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00002397 false, // Not multi-line
2398 debugger.GetUseColor(), 0, *this));
2399 const bool old_async_execution = debugger.GetAsyncExecution();
2400
2401 // Set synchronous execution if we are not stopping on continue
2402 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2403 debugger.SetAsyncExecution(false);
2404
2405 m_command_source_depth++;
2406
2407 debugger.RunIOHandler(io_handler_sp);
2408 if (!m_command_source_flags.empty())
2409 m_command_source_flags.pop_back();
2410 m_command_source_depth--;
2411 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2412 debugger.SetAsyncExecution(old_async_execution);
2413 } else {
2414 result.AppendErrorWithFormat(
2415 "error: an error occurred read file '%s': %s\n",
2416 cmd_file_path.c_str(), error.AsCString());
2417 result.SetStatus(eReturnStatusFailed);
2418 }
2419
2420 } else {
2421 result.AppendErrorWithFormat(
2422 "Error reading commands from file %s - file not found.\n",
2423 cmd_file.GetFilename().AsCString("<Unknown>"));
2424 result.SetStatus(eReturnStatusFailed);
2425 return;
2426 }
2427}
2428
2429ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
Jim Ingham30bac792017-07-13 19:45:54 +00002430 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
Greg Clayton79040462016-12-09 01:21:14 +00002431 if (!m_script_interpreter_sp) {
2432 if (!can_create)
2433 return nullptr;
2434 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2435 m_script_interpreter_sp =
2436 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2437 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002438 return m_script_interpreter_sp.get();
2439}
2440
2441bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2442
2443void CommandInterpreter::SetSynchronous(bool value) {
2444 m_synchronous_execution = value;
2445}
2446
2447void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002448 llvm::StringRef prefix,
2449 llvm::StringRef help_text) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002450 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002451
Zachary Turner0ac5f982016-11-08 04:12:42 +00002452 size_t line_width_max = max_columns - prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002453 if (line_width_max < 16)
Zachary Turner0ac5f982016-11-08 04:12:42 +00002454 line_width_max = help_text.size() + prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002455
Zachary Turner0ac5f982016-11-08 04:12:42 +00002456 strm.IndentMore(prefix.size());
2457 bool prefixed_yet = false;
2458 while (!help_text.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002459 // Prefix the first line, indent subsequent lines to line up
Zachary Turner0ac5f982016-11-08 04:12:42 +00002460 if (!prefixed_yet) {
2461 strm << prefix;
2462 prefixed_yet = true;
2463 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002464 strm.Indent();
Zachary Turner0ac5f982016-11-08 04:12:42 +00002465
2466 // Never print more than the maximum on one line.
2467 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2468
2469 // Always break on an explicit newline.
2470 std::size_t first_newline = this_line.find_first_of("\n");
2471
2472 // Don't break on space/tab unless the text is too long to fit on one line.
2473 std::size_t last_space = llvm::StringRef::npos;
2474 if (this_line.size() != help_text.size())
2475 last_space = this_line.find_last_of(" \t");
2476
2477 // Break at whichever condition triggered first.
2478 this_line = this_line.substr(0, std::min(first_newline, last_space));
2479 strm.PutCString(this_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002480 strm.EOL();
2481
Zachary Turner0ac5f982016-11-08 04:12:42 +00002482 // Remove whitespace / newlines after breaking.
2483 help_text = help_text.drop_front(this_line.size()).ltrim();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002484 }
Zachary Turner0ac5f982016-11-08 04:12:42 +00002485 strm.IndentLess(prefix.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002486}
2487
2488void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002489 llvm::StringRef word_text,
2490 llvm::StringRef separator,
2491 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002492 size_t max_word_len) {
2493 StreamString prefix_stream;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002494 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2495 (int)separator.size(), separator.data());
Zachary Turnerc1564272016-11-16 21:15:24 +00002496 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2497}
2498
Zachary Turner0ac5f982016-11-08 04:12:42 +00002499void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2500 llvm::StringRef separator,
2501 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002502 uint32_t max_word_len) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00002503 int indent_size = max_word_len + separator.size() + 2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002504
2505 strm.IndentMore(indent_size);
2506
2507 StreamString text_strm;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002508 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2509 text_strm << separator << " " << help_text;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002510
2511 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2512
Zachary Turnerc1564272016-11-16 21:15:24 +00002513 llvm::StringRef text = text_strm.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002514
2515 uint32_t chars_left = max_columns;
2516
Davide Italianocf8a8292017-04-14 22:36:08 +00002517 auto nextWordLength = [](llvm::StringRef S) {
2518 size_t pos = S.find_first_of(' ');
2519 return pos == llvm::StringRef::npos ? S.size() : pos;
2520 };
2521
Zachary Turnerc1564272016-11-16 21:15:24 +00002522 while (!text.empty()) {
2523 if (text.front() == '\n' ||
Jim Inghama81bd7f2017-07-27 00:18:18 +00002524 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002525 strm.EOL();
2526 strm.Indent();
Zachary Turnerc1564272016-11-16 21:15:24 +00002527 chars_left = max_columns - indent_size;
2528 if (text.front() == '\n')
2529 text = text.drop_front();
2530 else
2531 text = text.ltrim(' ');
Kate Stoneb9c1b512016-09-06 20:57:50 +00002532 } else {
Zachary Turnerc1564272016-11-16 21:15:24 +00002533 strm.PutChar(text.front());
2534 --chars_left;
2535 text = text.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002536 }
2537 }
2538
2539 strm.EOL();
2540 strm.IndentLess(indent_size);
2541}
2542
2543void CommandInterpreter::FindCommandsForApropos(
Zachary Turner067d1db2016-11-16 21:45:04 +00002544 llvm::StringRef search_word, StringList &commands_found,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002545 StringList &commands_help, CommandObject::CommandMap &command_map) {
2546 CommandObject::CommandMap::const_iterator pos;
2547
2548 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
Zachary Turner067d1db2016-11-16 21:45:04 +00002549 llvm::StringRef command_name = pos->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002550 CommandObject *cmd_obj = pos->second.get();
2551
2552 const bool search_short_help = true;
2553 const bool search_long_help = false;
2554 const bool search_syntax = false;
2555 const bool search_options = false;
Zachary Turner067d1db2016-11-16 21:45:04 +00002556 if (command_name.contains_lower(search_word) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002557 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2558 search_long_help, search_syntax,
2559 search_options)) {
2560 commands_found.AppendString(cmd_obj->GetCommandName());
2561 commands_help.AppendString(cmd_obj->GetHelp());
2562 }
2563
2564 if (cmd_obj->IsMultiwordObject()) {
2565 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2566 FindCommandsForApropos(search_word, commands_found, commands_help,
2567 cmd_multiword->GetSubcommandDictionary());
2568 }
2569 }
2570}
2571
Zachary Turner067d1db2016-11-16 21:45:04 +00002572void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002573 StringList &commands_found,
2574 StringList &commands_help,
2575 bool search_builtin_commands,
2576 bool search_user_commands,
2577 bool search_alias_commands) {
2578 CommandObject::CommandMap::const_iterator pos;
2579
2580 if (search_builtin_commands)
2581 FindCommandsForApropos(search_word, commands_found, commands_help,
2582 m_command_dict);
2583
2584 if (search_user_commands)
2585 FindCommandsForApropos(search_word, commands_found, commands_help,
2586 m_user_dict);
2587
2588 if (search_alias_commands)
2589 FindCommandsForApropos(search_word, commands_found, commands_help,
2590 m_alias_dict);
2591}
2592
2593void CommandInterpreter::UpdateExecutionContext(
2594 ExecutionContext *override_context) {
2595 if (override_context != nullptr) {
2596 m_exe_ctx_ref = *override_context;
2597 } else {
2598 const bool adopt_selected = true;
2599 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2600 adopt_selected);
2601 }
2602}
2603
2604size_t CommandInterpreter::GetProcessOutput() {
2605 // The process has stuff waiting for stderr; get it and write it out to the
2606 // appropriate place.
2607 char stdio_buffer[1024];
2608 size_t len;
2609 size_t total_bytes = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002610 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002611 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2612 if (target_sp) {
2613 ProcessSP process_sp(target_sp->GetProcessSP());
2614 if (process_sp) {
2615 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2616 error)) > 0) {
2617 size_t bytes_written = len;
2618 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2619 total_bytes += len;
2620 }
2621 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2622 error)) > 0) {
2623 size_t bytes_written = len;
2624 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2625 total_bytes += len;
2626 }
2627 }
2628 }
2629 return total_bytes;
2630}
2631
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002632void CommandInterpreter::StartHandlingCommand() {
2633 auto idle_state = CommandHandlingState::eIdle;
2634 if (m_command_state.compare_exchange_strong(
2635 idle_state, CommandHandlingState::eInProgress))
2636 lldbassert(m_iohandler_nesting_level == 0);
2637 else
2638 lldbassert(m_iohandler_nesting_level > 0);
2639 ++m_iohandler_nesting_level;
2640}
2641
2642void CommandInterpreter::FinishHandlingCommand() {
2643 lldbassert(m_iohandler_nesting_level > 0);
2644 if (--m_iohandler_nesting_level == 0) {
2645 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2646 lldbassert(prev_state != CommandHandlingState::eIdle);
2647 }
2648}
2649
2650bool CommandInterpreter::InterruptCommand() {
2651 auto in_progress = CommandHandlingState::eInProgress;
2652 return m_command_state.compare_exchange_strong(
2653 in_progress, CommandHandlingState::eInterrupted);
2654}
2655
2656bool CommandInterpreter::WasInterrupted() const {
2657 bool was_interrupted =
2658 (m_command_state == CommandHandlingState::eInterrupted);
2659 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2660 return was_interrupted;
2661}
2662
2663void CommandInterpreter::PrintCommandOutput(Stream &stream,
2664 llvm::StringRef str) {
2665 // Split the output into lines and poll for interrupt requests
2666 const char *data = str.data();
2667 size_t size = str.size();
2668 while (size > 0 && !WasInterrupted()) {
2669 size_t chunk_size = 0;
2670 for (; chunk_size < size; ++chunk_size) {
2671 lldbassert(data[chunk_size] != '\0');
2672 if (data[chunk_size] == '\n') {
2673 ++chunk_size;
2674 break;
2675 }
2676 }
2677 chunk_size = stream.Write(data, chunk_size);
2678 lldbassert(size >= chunk_size);
2679 data += chunk_size;
2680 size -= chunk_size;
2681 }
2682 if (size > 0) {
2683 stream.Printf("\n... Interrupted.\n");
2684 }
2685}
2686
Kate Stoneb9c1b512016-09-06 20:57:50 +00002687void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2688 std::string &line) {
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002689 // If we were interrupted, bail out...
2690 if (WasInterrupted())
2691 return;
2692
Kate Stoneb9c1b512016-09-06 20:57:50 +00002693 const bool is_interactive = io_handler.GetIsInteractive();
2694 if (is_interactive == false) {
2695 // When we are not interactive, don't execute blank lines. This will happen
2696 // sourcing a commands file. We don't want blank lines to repeat the
Adrian Prantl05097242018-04-30 16:49:04 +00002697 // previous command and cause any errors to occur (like redefining an
2698 // alias, get an error and stop parsing the commands file).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002699 if (line.empty())
2700 return;
2701
2702 // When using a non-interactive file handle (like when sourcing commands
Adrian Prantl05097242018-04-30 16:49:04 +00002703 // from a file) we need to echo the command out so we don't just see the
2704 // command output and no command...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002705 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2706 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2707 line.c_str());
2708 }
2709
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002710 StartHandlingCommand();
2711
Kate Stoneb9c1b512016-09-06 20:57:50 +00002712 lldb_private::CommandReturnObject result;
2713 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2714
2715 // Now emit the command output text from the command we just executed
2716 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2717 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2718 GetProcessOutput();
2719
2720 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002721 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002722 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002723 }
2724
2725 // Now emit the command error text from the command we just executed
2726 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002727 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002728 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002729 }
2730 }
2731
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002732 FinishHandlingCommand();
2733
Kate Stoneb9c1b512016-09-06 20:57:50 +00002734 switch (result.GetStatus()) {
2735 case eReturnStatusInvalid:
2736 case eReturnStatusSuccessFinishNoResult:
2737 case eReturnStatusSuccessFinishResult:
2738 case eReturnStatusStarted:
2739 break;
2740
2741 case eReturnStatusSuccessContinuingNoResult:
2742 case eReturnStatusSuccessContinuingResult:
2743 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2744 io_handler.SetIsDone(true);
2745 break;
2746
2747 case eReturnStatusFailed:
2748 m_num_errors++;
2749 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2750 io_handler.SetIsDone(true);
2751 break;
2752
2753 case eReturnStatusQuit:
2754 m_quit_requested = true;
2755 io_handler.SetIsDone(true);
2756 break;
2757 }
2758
2759 // Finally, if we're going to stop on crash, check that here:
2760 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2761 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2762 bool should_stop = false;
2763 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2764 if (target_sp) {
2765 ProcessSP process_sp(target_sp->GetProcessSP());
2766 if (process_sp) {
2767 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2768 StopReason reason = thread_sp->GetStopReason();
2769 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2770 reason == eStopReasonInstrumentation) &&
2771 !result.GetAbnormalStopWasExpected()) {
2772 should_stop = true;
2773 break;
2774 }
2775 }
2776 }
2777 }
2778 if (should_stop) {
2779 io_handler.SetIsDone(true);
2780 m_stopped_for_crash = true;
2781 }
2782 }
2783}
2784
2785bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2786 ExecutionContext exe_ctx(GetExecutionContext());
2787 Process *process = exe_ctx.GetProcessPtr();
2788
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002789 if (InterruptCommand())
2790 return true;
2791
Kate Stoneb9c1b512016-09-06 20:57:50 +00002792 if (process) {
2793 StateType state = process->GetState();
2794 if (StateIsRunningState(state)) {
2795 process->Halt();
2796 return true; // Don't do any updating when we are running
2797 }
2798 }
2799
2800 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2801 if (script_interpreter) {
2802 if (script_interpreter->Interrupt())
2803 return true;
2804 }
2805 return false;
2806}
2807
2808void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2809 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2810 void *baton) {
2811 Debugger &debugger = GetDebugger();
2812 IOHandlerSP io_handler_sp(
2813 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2814 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002815 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2816 llvm::StringRef(), // Continuation prompt
2817 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002818 debugger.GetUseColor(),
2819 0, // Don't show line numbers
2820 delegate)); // IOHandlerDelegate
2821
2822 if (io_handler_sp) {
2823 io_handler_sp->SetUserData(baton);
2824 if (asynchronously)
2825 debugger.PushIOHandler(io_handler_sp);
2826 else
2827 debugger.RunIOHandler(io_handler_sp);
2828 }
2829}
2830
2831void CommandInterpreter::GetPythonCommandsFromIOHandler(
2832 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2833 void *baton) {
2834 Debugger &debugger = GetDebugger();
2835 IOHandlerSP io_handler_sp(
2836 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2837 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002838 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2839 llvm::StringRef(), // Continuation prompt
2840 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002841 debugger.GetUseColor(),
2842 0, // Don't show line numbers
2843 delegate)); // IOHandlerDelegate
2844
2845 if (io_handler_sp) {
2846 io_handler_sp->SetUserData(baton);
2847 if (asynchronously)
2848 debugger.PushIOHandler(io_handler_sp);
2849 else
2850 debugger.RunIOHandler(io_handler_sp);
2851 }
2852}
2853
2854bool CommandInterpreter::IsActive() {
2855 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2856}
2857
2858lldb::IOHandlerSP
2859CommandInterpreter::GetIOHandler(bool force_create,
2860 CommandInterpreterRunOptions *options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002861 // Always re-create the IOHandlerEditline in case the input changed. The old
2862 // instance might have had a non-interactive input and now it does or vice
2863 // versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002864 if (force_create || !m_command_io_handler_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002865 // Always re-create the IOHandlerEditline in case the input changed. The
2866 // old instance might have had a non-interactive input and now it does or
2867 // vice versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002868 uint32_t flags = 0;
2869
2870 if (options) {
2871 if (options->m_stop_on_continue == eLazyBoolYes)
2872 flags |= eHandleCommandFlagStopOnContinue;
2873 if (options->m_stop_on_error == eLazyBoolYes)
2874 flags |= eHandleCommandFlagStopOnError;
2875 if (options->m_stop_on_crash == eLazyBoolYes)
2876 flags |= eHandleCommandFlagStopOnCrash;
2877 if (options->m_echo_commands != eLazyBoolNo)
2878 flags |= eHandleCommandFlagEchoCommand;
2879 if (options->m_print_results != eLazyBoolNo)
2880 flags |= eHandleCommandFlagPrintResult;
2881 } else {
2882 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2883 }
2884
2885 m_command_io_handler_sp.reset(new IOHandlerEditline(
2886 m_debugger, IOHandler::Type::CommandInterpreter,
2887 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2888 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002889 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002890 false, // Don't enable multiple line input, just single line commands
2891 m_debugger.GetUseColor(),
2892 0, // Don't show line numbers
2893 *this));
2894 }
2895 return m_command_io_handler_sp;
2896}
2897
2898void CommandInterpreter::RunCommandInterpreter(
2899 bool auto_handle_events, bool spawn_thread,
2900 CommandInterpreterRunOptions &options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002901 // Always re-create the command interpreter when we run it in case any file
2902 // handles have changed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002903 bool force_create = true;
2904 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2905 m_stopped_for_crash = false;
2906
2907 if (auto_handle_events)
2908 m_debugger.StartEventHandlerThread();
2909
2910 if (spawn_thread) {
2911 m_debugger.StartIOHandlerThread();
2912 } else {
2913 m_debugger.ExecuteIOHandlers();
2914
2915 if (auto_handle_events)
2916 m_debugger.StopEventHandlerThread();
2917 }
2918}
2919
2920CommandObject *
2921CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2922 CommandReturnObject &result) {
2923 std::string scratch_command(command_line); // working copy so we don't modify
2924 // command_line unless we succeed
2925 CommandObject *cmd_obj = nullptr;
2926 StreamString revised_command_line;
2927 bool wants_raw_input = false;
2928 size_t actual_cmd_name_len = 0;
2929 std::string next_word;
2930 StringList matches;
2931 bool done = false;
2932 while (!done) {
2933 char quote_char = '\0';
2934 std::string suffix;
2935 ExtractCommand(scratch_command, next_word, suffix, quote_char);
2936 if (cmd_obj == nullptr) {
2937 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002938 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00002939 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002940 bool is_real_command =
2941 (is_alias == false) ||
2942 (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
2943 if (!is_real_command) {
2944 matches.Clear();
2945 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002946 cmd_obj =
2947 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002948 revised_command_line.Printf("%s", alias_result.c_str());
2949 if (cmd_obj) {
2950 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00002951 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002952 }
2953 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002954 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00002955 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
2956 actual_cmd_name_len += cmd_name.size();
2957 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002958 wants_raw_input = cmd_obj->WantsRawCommandString();
2959 } else {
2960 revised_command_line.Printf("%s", next_word.c_str());
2961 }
2962 }
2963 } else {
2964 if (cmd_obj->IsMultiwordObject()) {
2965 CommandObject *sub_cmd_obj =
2966 cmd_obj->GetSubcommandObject(next_word.c_str());
2967 if (sub_cmd_obj) {
Adrian Prantl05097242018-04-30 16:49:04 +00002968 // The subcommand's name includes the parent command's name, so
2969 // restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00002970 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
2971 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002972 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00002973 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002974 cmd_obj = sub_cmd_obj;
2975 wants_raw_input = cmd_obj->WantsRawCommandString();
2976 } else {
2977 if (quote_char)
2978 revised_command_line.Printf(" %c%s%s%c", quote_char,
2979 next_word.c_str(), suffix.c_str(),
2980 quote_char);
2981 else
2982 revised_command_line.Printf(" %s%s", next_word.c_str(),
2983 suffix.c_str());
2984 done = true;
2985 }
2986 } else {
2987 if (quote_char)
2988 revised_command_line.Printf(" %c%s%s%c", quote_char,
2989 next_word.c_str(), suffix.c_str(),
2990 quote_char);
2991 else
2992 revised_command_line.Printf(" %s%s", next_word.c_str(),
2993 suffix.c_str());
2994 done = true;
2995 }
2996 }
2997
2998 if (cmd_obj == nullptr) {
2999 const size_t num_matches = matches.GetSize();
3000 if (matches.GetSize() > 1) {
3001 StreamString error_msg;
3002 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3003 next_word.c_str());
3004
3005 for (uint32_t i = 0; i < num_matches; ++i) {
3006 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3007 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003008 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003009 } else {
3010 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003011 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003012 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3013 next_word.c_str());
3014 }
3015 result.SetStatus(eReturnStatusFailed);
3016 return nullptr;
3017 }
3018
3019 if (cmd_obj->IsMultiwordObject()) {
3020 if (!suffix.empty()) {
3021 result.AppendErrorWithFormat(
3022 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3023 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003024 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003025 next_word.empty() ? "" : next_word.c_str(),
3026 next_word.empty() ? " -- " : " ", suffix.c_str());
3027 result.SetStatus(eReturnStatusFailed);
3028 return nullptr;
3029 }
3030 } else {
3031 // If we found a normal command, we are done
3032 done = true;
3033 if (!suffix.empty()) {
3034 switch (suffix[0]) {
3035 case '/':
3036 // GDB format suffixes
3037 {
3038 Options *command_options = cmd_obj->GetOptions();
3039 if (command_options &&
3040 command_options->SupportsLongOption("gdb-format")) {
3041 std::string gdb_format_option("--gdb-format=");
3042 gdb_format_option += (suffix.c_str() + 1);
3043
Zachary Turnerc1564272016-11-16 21:15:24 +00003044 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003045 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3046 if (arg_terminator_idx != std::string::npos) {
3047 // Insert the gdb format option before the "--" that terminates
3048 // options
3049 gdb_format_option.append(1, ' ');
3050 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003051 revised_command_line.Clear();
3052 revised_command_line.PutCString(cmd);
3053 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003054 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3055
3056 if (wants_raw_input &&
3057 FindArgumentTerminator(cmd) == std::string::npos)
3058 revised_command_line.PutCString(" --");
3059 } else {
3060 result.AppendErrorWithFormat(
3061 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003062 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003063 result.SetStatus(eReturnStatusFailed);
3064 return nullptr;
3065 }
3066 }
3067 break;
3068
3069 default:
3070 result.AppendErrorWithFormat(
3071 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3072 result.SetStatus(eReturnStatusFailed);
3073 return nullptr;
3074 }
3075 }
3076 }
3077 if (scratch_command.empty())
3078 done = true;
3079 }
3080
3081 if (!scratch_command.empty())
3082 revised_command_line.Printf(" %s", scratch_command.c_str());
3083
3084 if (cmd_obj != NULL)
Zachary Turnerc1564272016-11-16 21:15:24 +00003085 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003086
3087 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003088}