blob: cb793f75bddbeebb7b89ef134904dca9c6f615e3 [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
Eli Friedman3afb70c2010-06-13 02:17:17 +000017#include "../Commands/CommandObjectApropos.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000018#include "../Commands/CommandObjectBreakpoint.h"
Tamas Berghammer3937bc62015-07-02 10:03:37 +000019#include "../Commands/CommandObjectBugreport.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000020#include "../Commands/CommandObjectCommands.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000021#include "../Commands/CommandObjectDisassemble.h"
22#include "../Commands/CommandObjectExpression.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000023#include "../Commands/CommandObjectFrame.h"
Greg Clayton44d93782014-01-27 23:43:24 +000024#include "../Commands/CommandObjectGUI.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000025#include "../Commands/CommandObjectHelp.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000026#include "../Commands/CommandObjectLanguage.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000027#include "../Commands/CommandObjectLog.h"
28#include "../Commands/CommandObjectMemory.h"
Greg Claytonded470d2011-03-19 01:12:21 +000029#include "../Commands/CommandObjectPlatform.h"
Enrico Granata21dfcd92012-09-28 23:57:51 +000030#include "../Commands/CommandObjectPlugin.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000031#include "../Commands/CommandObjectProcess.h"
32#include "../Commands/CommandObjectQuit.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectRegister.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectSettings.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSource.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000036#include "../Commands/CommandObjectTarget.h"
37#include "../Commands/CommandObjectThread.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000038#include "../Commands/CommandObjectType.h"
Johnny Chen31c39da2010-12-23 20:21:44 +000039#include "../Commands/CommandObjectVersion.h"
Johnny Chenf04ee932011-09-22 18:04:58 +000040#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042#include "lldb/Core/Debugger.h"
Zachary Turner2c1f46d2015-07-30 20:28:07 +000043#include "lldb/Core/PluginManager.h"
Greg Claytonf0066ad2014-05-02 00:45:31 +000044#include "lldb/Core/State.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"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000047#include "lldb/Utility/Stream.h"
Pavel Labath38d06322017-06-29 14:32:17 +000048#include "lldb/Utility/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000049
Todd Fialacacde7d2014-09-27 16:54:22 +000050#ifndef LLDB_DISABLE_LIBEDIT
Greg Clayton44d93782014-01-27 23:43:24 +000051#include "lldb/Host/Editline.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000052#endif
Greg Clayton7fb56d02011-02-01 01:31:41 +000053#include "lldb/Host/Host.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000054#include "lldb/Host/HostInfo.h"
Enrico Granatab5887262012-10-29 21:18:03 +000055
56#include "lldb/Interpreter/Args.h"
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"
Enrico Granatab5887262012-10-29 21:18:03 +000063
Chris Lattner30fdc8d2010-06-08 16:52:24 +000064#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000065#include "lldb/Target/TargetList.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000066#include "lldb/Target/Thread.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000067
Saleem Abdulrasool28606952014-06-27 05:17:41 +000068#include "llvm/ADT/STLExtras.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000069#include "llvm/ADT/SmallString.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000070#include "llvm/Support/Path.h"
Sean Callanan237c3ed2016-12-14 21:31:31 +000071#include "llvm/Support/PrettyStackTrace.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000072
Chris Lattner30fdc8d2010-06-08 16:52:24 +000073using namespace lldb;
74using namespace lldb_private;
75
Adrian McCarthy2304b6f2015-04-23 20:00:25 +000076static const char *k_white_space = " \t\v";
Greg Clayton754a9362012-08-23 00:22:02 +000077
Kate Stoneb9c1b512016-09-06 20:57:50 +000078static PropertyDefinition g_properties[] = {
79 {"expand-regex-aliases", OptionValue::eTypeBoolean, true, false, nullptr,
80 nullptr, "If true, regular expression alias commands will show the "
81 "expanded command that will be executed. This can be used to "
82 "debug new regular expression alias commands."},
83 {"prompt-on-quit", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
84 "If true, LLDB will prompt you before quitting if there are any live "
85 "processes being debugged. If false, LLDB will quit without asking in any "
86 "case."},
87 {"stop-command-source-on-error", OptionValue::eTypeBoolean, true, true,
88 nullptr, nullptr, "If true, LLDB will stop running a 'command source' "
89 "script upon encountering an error."},
90 {"space-repl-prompts", OptionValue::eTypeBoolean, true, false, nullptr,
91 nullptr,
92 "If true, blank lines will be printed between between REPL submissions."},
93 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
94
95enum {
96 ePropertyExpandRegexAliases = 0,
97 ePropertyPromptOnQuit = 1,
98 ePropertyStopCmdSourceOnError = 2,
99 eSpaceReplPrompts = 3
Greg Clayton754a9362012-08-23 00:22:02 +0000100};
101
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102ConstString &CommandInterpreter::GetStaticBroadcasterClass() {
103 static ConstString class_name("lldb.commandInterpreter");
104 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000105}
106
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107CommandInterpreter::CommandInterpreter(Debugger &debugger,
108 ScriptLanguage script_language,
109 bool synchronous_execution)
110 : Broadcaster(debugger.GetBroadcasterManager(),
111 CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
112 Properties(OptionValuePropertiesSP(
113 new OptionValueProperties(ConstString("interpreter")))),
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000114 IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000115 m_debugger(debugger), m_synchronous_execution(synchronous_execution),
116 m_skip_lldbinit_files(false), m_skip_app_init_files(false),
117 m_script_interpreter_sp(), m_command_io_handler_sp(), m_comment_char('#'),
118 m_batch_command_mode(false), m_truncation_warning(eNoTruncation),
119 m_command_source_depth(0), m_num_errors(0), m_quit_requested(false),
120 m_stopped_for_crash(false) {
121 debugger.SetScriptLanguage(script_language);
122 SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit");
123 SetEventName(eBroadcastBitResetPrompt, "reset-prompt");
124 SetEventName(eBroadcastBitQuitCommandReceived, "quit");
125 CheckInWithManager();
126 m_collection_sp->Initialize(g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000127}
128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129bool CommandInterpreter::GetExpandRegexAliases() const {
130 const uint32_t idx = ePropertyExpandRegexAliases;
131 return m_collection_sp->GetPropertyAtIndexAsBoolean(
132 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000133}
134
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135bool CommandInterpreter::GetPromptOnQuit() const {
136 const uint32_t idx = ePropertyPromptOnQuit;
137 return m_collection_sp->GetPropertyAtIndexAsBoolean(
138 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000139}
Greg Clayton754a9362012-08-23 00:22:02 +0000140
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141void CommandInterpreter::SetPromptOnQuit(bool b) {
142 const uint32_t idx = ePropertyPromptOnQuit;
143 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ilia Kacf28be2015-03-23 22:45:13 +0000144}
145
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146void CommandInterpreter::ResolveCommand(const char *command_line,
147 CommandReturnObject &result) {
148 std::string command = command_line;
149 if (ResolveCommandImpl(command, result) != nullptr) {
150 result.AppendMessageWithFormat("%s", command.c_str());
151 result.SetStatus(eReturnStatusSuccessFinishResult);
152 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000153}
154
Kate Stoneb9c1b512016-09-06 20:57:50 +0000155bool CommandInterpreter::GetStopCmdSourceOnError() const {
156 const uint32_t idx = ePropertyStopCmdSourceOnError;
157 return m_collection_sp->GetPropertyAtIndexAsBoolean(
158 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000159}
160
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161bool CommandInterpreter::GetSpaceReplPrompts() const {
162 const uint32_t idx = eSpaceReplPrompts;
163 return m_collection_sp->GetPropertyAtIndexAsBoolean(
164 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callanan66810412015-10-19 23:11:07 +0000165}
166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167void CommandInterpreter::Initialize() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000168 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
169 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000170
Kate Stoneb9c1b512016-09-06 20:57:50 +0000171 CommandReturnObject result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000172
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173 LoadCommandDictionary();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000174
Kate Stoneb9c1b512016-09-06 20:57:50 +0000175 // An alias arguments vector to reuse - reset it before use...
176 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
177
178 // Set up some initial aliases.
179 CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
180 if (cmd_obj_sp) {
181 AddAlias("q", cmd_obj_sp);
182 AddAlias("exit", cmd_obj_sp);
183 }
184
185 cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
186 if (cmd_obj_sp)
187 AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
188
189 cmd_obj_sp = GetCommandSPExact("process detach", false);
190 if (cmd_obj_sp) {
191 AddAlias("detach", cmd_obj_sp);
192 }
193
194 cmd_obj_sp = GetCommandSPExact("process continue", false);
195 if (cmd_obj_sp) {
196 AddAlias("c", cmd_obj_sp);
197 AddAlias("continue", cmd_obj_sp);
198 }
199
200 cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
201 if (cmd_obj_sp)
202 AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
203
204 cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
205 if (cmd_obj_sp)
206 AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
207
208 cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
209 if (cmd_obj_sp) {
210 AddAlias("stepi", cmd_obj_sp);
211 AddAlias("si", cmd_obj_sp);
212 }
213
214 cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
215 if (cmd_obj_sp) {
216 AddAlias("nexti", cmd_obj_sp);
217 AddAlias("ni", cmd_obj_sp);
218 }
219
220 cmd_obj_sp = GetCommandSPExact("thread step-in", false);
221 if (cmd_obj_sp) {
222 AddAlias("s", cmd_obj_sp);
223 AddAlias("step", cmd_obj_sp);
224 CommandAlias *sif_alias = AddAlias(
225 "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
226 if (sif_alias) {
227 sif_alias->SetHelp("Step through the current block, stopping if you step "
228 "directly into a function whose name matches the "
229 "TargetFunctionName.");
230 sif_alias->SetSyntax("sif <TargetFunctionName>");
Caroline Ticeca90c472011-05-06 21:37:15 +0000231 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000233
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234 cmd_obj_sp = GetCommandSPExact("thread step-over", false);
235 if (cmd_obj_sp) {
236 AddAlias("n", cmd_obj_sp);
237 AddAlias("next", cmd_obj_sp);
238 }
239
240 cmd_obj_sp = GetCommandSPExact("thread step-out", false);
241 if (cmd_obj_sp) {
242 AddAlias("finish", cmd_obj_sp);
243 }
244
245 cmd_obj_sp = GetCommandSPExact("frame select", false);
246 if (cmd_obj_sp) {
247 AddAlias("f", cmd_obj_sp);
248 }
249
250 cmd_obj_sp = GetCommandSPExact("thread select", false);
251 if (cmd_obj_sp) {
252 AddAlias("t", cmd_obj_sp);
253 }
254
255 cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
256 if (cmd_obj_sp) {
257 AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
258 AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
259 }
260
261 cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
262 if (cmd_obj_sp) {
263 AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
264 AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
265 }
266
267 cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
268 if (cmd_obj_sp)
269 AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
270
271 cmd_obj_sp = GetCommandSPExact("memory read", false);
272 if (cmd_obj_sp)
273 AddAlias("x", cmd_obj_sp);
274
275 cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
276 if (cmd_obj_sp)
277 AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
278
279 cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
280 if (cmd_obj_sp)
281 AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
282
283 cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
284 if (cmd_obj_sp)
285 AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
286
287 cmd_obj_sp = GetCommandSPExact("disassemble", false);
288 if (cmd_obj_sp)
289 AddAlias("dis", cmd_obj_sp);
290
291 cmd_obj_sp = GetCommandSPExact("disassemble", false);
292 if (cmd_obj_sp)
293 AddAlias("di", cmd_obj_sp);
294
295 cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
296 if (cmd_obj_sp)
297 AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
298
299 cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
300 if (cmd_obj_sp)
301 AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
302
303 cmd_obj_sp = GetCommandSPExact("target create", false);
304 if (cmd_obj_sp)
305 AddAlias("file", cmd_obj_sp);
306
307 cmd_obj_sp = GetCommandSPExact("target modules", false);
308 if (cmd_obj_sp)
309 AddAlias("image", cmd_obj_sp);
310
311 alias_arguments_vector_sp.reset(new OptionArgVector);
312
313 cmd_obj_sp = GetCommandSPExact("expression", false);
314 if (cmd_obj_sp) {
315 AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
316 AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
317 AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
318 if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
319 po->SetHelp("Evaluate an expression on the current thread. Displays any "
320 "returned value with formatting "
321 "controlled by the type's author.");
322 po->SetHelpLong("");
Johnny Chen6d675242012-08-24 18:15:45 +0000323 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000324 AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
325 AddAlias("poarray", cmd_obj_sp,
326 "--object-description --element-count %1 --")
327 ->SetHelpLong("");
328 }
Johnny Chen6d675242012-08-24 18:15:45 +0000329
Kate Stoneb9c1b512016-09-06 20:57:50 +0000330 cmd_obj_sp = GetCommandSPExact("process kill", false);
331 if (cmd_obj_sp) {
332 AddAlias("kill", cmd_obj_sp);
333 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000334
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 cmd_obj_sp = GetCommandSPExact("process launch", false);
336 if (cmd_obj_sp) {
Chaoren Lin6fc5c7f2016-02-26 03:36:27 +0000337 alias_arguments_vector_sp.reset(new OptionArgVector);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
339 AddAlias("r", cmd_obj_sp, "--");
340 AddAlias("run", cmd_obj_sp, "--");
Jason Molenda85da3122012-07-06 02:46:23 +0000341#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000342#if defined(__APPLE__)
343 std::string shell_option;
344 shell_option.append("--shell-expand-args");
345 shell_option.append(" true");
346 shell_option.append(" --");
347 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
348 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
349#else
350 StreamString defaultshell;
351 defaultshell.Printf("--shell=%s --",
352 HostInfo::GetDefaultShell().GetPath().c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +0000353 AddAlias("r", cmd_obj_sp, defaultshell.GetString());
354 AddAlias("run", cmd_obj_sp, defaultshell.GetString());
Jason Molenda85da3122012-07-06 02:46:23 +0000355#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356#endif
357 }
358
359 cmd_obj_sp = GetCommandSPExact("target symbols add", false);
360 if (cmd_obj_sp) {
361 AddAlias("add-dsym", cmd_obj_sp);
362 }
363
364 cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
365 if (cmd_obj_sp) {
366 AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
367 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000368}
369
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370void CommandInterpreter::Clear() {
371 m_command_io_handler_sp.reset();
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000372
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 if (m_script_interpreter_sp)
374 m_script_interpreter_sp->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000375}
376
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
378 // This function has not yet been implemented.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000379
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380 // Look for any embedded script command
381 // If found,
382 // get interpreter object from the command dictionary,
383 // call execute_one_command on it,
384 // get the results as a string,
385 // substitute that string for current stuff.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000386
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 return arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000388}
389
Kate Stoneb9c1b512016-09-06 20:57:50 +0000390void CommandInterpreter::LoadCommandDictionary() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000391 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
392 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000393
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000395
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
397 m_command_dict["breakpoint"] =
398 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
399 m_command_dict["bugreport"] =
400 CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
401 m_command_dict["command"] =
402 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
403 m_command_dict["disassemble"] =
404 CommandObjectSP(new CommandObjectDisassemble(*this));
405 m_command_dict["expression"] =
406 CommandObjectSP(new CommandObjectExpression(*this));
407 m_command_dict["frame"] =
408 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
409 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
410 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
411 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
412 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
413 m_command_dict["platform"] =
414 CommandObjectSP(new CommandObjectPlatform(*this));
415 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
416 m_command_dict["process"] =
417 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
418 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
419 m_command_dict["register"] =
420 CommandObjectSP(new CommandObjectRegister(*this));
421 m_command_dict["script"] =
422 CommandObjectSP(new CommandObjectScript(*this, script_language));
423 m_command_dict["settings"] =
424 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
425 m_command_dict["source"] =
426 CommandObjectSP(new CommandObjectMultiwordSource(*this));
427 m_command_dict["target"] =
428 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
429 m_command_dict["thread"] =
430 CommandObjectSP(new CommandObjectMultiwordThread(*this));
431 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
432 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
433 m_command_dict["watchpoint"] =
434 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
435 m_command_dict["language"] =
436 CommandObjectSP(new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000437
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438 const char *break_regexes[][2] = {
439 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
440 "breakpoint set --file '%1' --line %2"},
441 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
442 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
443 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
444 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
445 "breakpoint set --name '%1'"},
446 {"^(-.*)$", "breakpoint set %1"},
447 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
448 "breakpoint set --name '%2' --shlib '%1'"},
449 {"^\\&(.*[^[:space:]])[[:space:]]*$",
450 "breakpoint set --name '%1' --skip-prologue=0"},
451 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
452 "breakpoint set --name '%1'"}};
Kate Stone7428a182016-07-14 22:03:10 +0000453
Kate Stoneb9c1b512016-09-06 20:57:50 +0000454 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000455
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap(
457 new CommandObjectRegexCommand(
458 *this, "_regexp-break",
459 "Set a breakpoint using one of several shorthand formats.\n",
460 "\n"
461 "_regexp-break <filename>:<linenum>\n"
462 " main.c:12 // Break at line 12 of "
463 "main.c\n\n"
464 "_regexp-break <linenum>\n"
465 " 12 // Break at line 12 of current "
466 "file\n\n"
467 "_regexp-break 0x<address>\n"
468 " 0x1234000 // Break at address "
469 "0x1234000\n\n"
470 "_regexp-break <name>\n"
471 " main // Break in 'main' after the "
472 "prologue\n\n"
473 "_regexp-break &<name>\n"
474 " &main // Break at first instruction "
475 "in 'main'\n\n"
476 "_regexp-break <module>`<name>\n"
477 " libc.so`malloc // Break in 'malloc' from "
478 "'libc.so'\n\n"
479 "_regexp-break /<source-regex>/\n"
480 " /break here/ // Break on source lines in "
481 "current file\n"
482 " // containing text 'break "
483 "here'.\n",
484 2, CommandCompletions::eSymbolCompletion |
485 CommandCompletions::eSourceFileCompletion,
486 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000487
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488 if (break_regex_cmd_ap.get()) {
489 bool success = true;
490 for (size_t i = 0; i < num_regexes; i++) {
491 success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0],
492 break_regexes[i][1]);
493 if (!success)
494 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000495 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000496 success =
497 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Jim Inghamffba2292011-03-22 02:29:32 +0000498
Kate Stoneb9c1b512016-09-06 20:57:50 +0000499 if (success) {
500 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
501 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
Jim Inghamca36cd12012-10-05 19:16:31 +0000502 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503 }
Jim Inghamca36cd12012-10-05 19:16:31 +0000504
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap(
506 new CommandObjectRegexCommand(
507 *this, "_regexp-tbreak",
508 "Set a one-shot breakpoint using one of several shorthand formats.\n",
509 "\n"
510 "_regexp-break <filename>:<linenum>\n"
511 " main.c:12 // Break at line 12 of "
512 "main.c\n\n"
513 "_regexp-break <linenum>\n"
514 " 12 // Break at line 12 of current "
515 "file\n\n"
516 "_regexp-break 0x<address>\n"
517 " 0x1234000 // Break at address "
518 "0x1234000\n\n"
519 "_regexp-break <name>\n"
520 " main // Break in 'main' after the "
521 "prologue\n\n"
522 "_regexp-break &<name>\n"
523 " &main // Break at first instruction "
524 "in 'main'\n\n"
525 "_regexp-break <module>`<name>\n"
526 " libc.so`malloc // Break in 'malloc' from "
527 "'libc.so'\n\n"
528 "_regexp-break /<source-regex>/\n"
529 " /break here/ // Break on source lines in "
530 "current file\n"
531 " // containing text 'break "
532 "here'.\n",
533 2, CommandCompletions::eSymbolCompletion |
534 CommandCompletions::eSourceFileCompletion,
535 false));
536
537 if (tbreak_regex_cmd_ap.get()) {
538 bool success = true;
539 for (size_t i = 0; i < num_regexes; i++) {
540 // If you add a resultant command string longer than 1024 characters be
541 // sure to increase the size of this buffer.
542 char buffer[1024];
543 int num_printed =
544 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000545 lldbassert(num_printed < 1024);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546 UNUSED_IF_ASSERT_DISABLED(num_printed);
547 success =
548 tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer);
549 if (!success)
550 break;
Johnny Chen6d675242012-08-24 18:15:45 +0000551 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 success =
553 tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Kate Stone7428a182016-07-14 22:03:10 +0000554
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 if (success) {
556 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
557 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
558 tbreak_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000559 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 }
Kate Stone7428a182016-07-14 22:03:10 +0000561
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap(
563 new CommandObjectRegexCommand(
564 *this, "_regexp-attach", "Attach to process by ID or name.",
565 "_regexp-attach <pid> | <process-name>", 2, 0, false));
566 if (attach_regex_cmd_ap.get()) {
567 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
568 "process attach --pid %1") &&
569 attach_regex_cmd_ap->AddRegexCommand(
570 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
571 // specified get passed to
572 // 'process attach'
573 attach_regex_cmd_ap->AddRegexCommand("^(.+)$",
574 "process attach --name '%1'") &&
575 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) {
576 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
577 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
578 attach_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000579 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000580 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000581
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap(
583 new CommandObjectRegexCommand(*this, "_regexp-down",
584 "Select a newer stack frame. Defaults to "
585 "moving one frame, a numeric argument can "
586 "specify an arbitrary number.",
587 "_regexp-down [<count>]", 2, 0, false));
588 if (down_regex_cmd_ap.get()) {
589 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
590 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
591 "frame select -r -%1")) {
592 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
593 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000594 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000596
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap(
598 new CommandObjectRegexCommand(
599 *this, "_regexp-up",
600 "Select an older stack frame. Defaults to moving one "
601 "frame, a numeric argument can specify an arbitrary number.",
602 "_regexp-up [<count>]", 2, 0, false));
603 if (up_regex_cmd_ap.get()) {
604 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
605 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
606 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
607 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000608 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000610
Kate Stoneb9c1b512016-09-06 20:57:50 +0000611 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap(
612 new CommandObjectRegexCommand(
613 *this, "_regexp-display",
614 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
615 "_regexp-display expression", 2, 0, false));
616 if (display_regex_cmd_ap.get()) {
617 if (display_regex_cmd_ap->AddRegexCommand(
618 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
619 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
620 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
621 display_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000622 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000624
Kate Stoneb9c1b512016-09-06 20:57:50 +0000625 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap(
626 new CommandObjectRegexCommand(
627 *this, "_regexp-undisplay", "Stop displaying expression at every "
628 "stop (specified by stop-hook index.)",
629 "_regexp-undisplay stop-hook-number", 2, 0, false));
630 if (undisplay_regex_cmd_ap.get()) {
631 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
632 "target stop-hook delete %1")) {
633 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
634 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
635 undisplay_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000636 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000637 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000638
Kate Stoneb9c1b512016-09-06 20:57:50 +0000639 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap(
640 new CommandObjectRegexCommand(
641 *this, "gdb-remote", "Connect to a process via remote GDB server. "
642 "If no host is specifed, localhost is assumed.",
643 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
644 if (connect_gdb_remote_cmd_ap.get()) {
645 if (connect_gdb_remote_cmd_ap->AddRegexCommand(
Chris Bieneman51978f52017-04-27 16:13:58 +0000646 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
647 "process connect --plugin gdb-remote connect://%1:%2") &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648 connect_gdb_remote_cmd_ap->AddRegexCommand(
649 "^([[:digit:]]+)$",
650 "process connect --plugin gdb-remote connect://localhost:%1")) {
651 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
652 m_command_dict[command_sp->GetCommandName()] = command_sp;
Jason Molenda4cddfed2012-10-05 05:29:32 +0000653 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000654 }
Jason Molenda4cddfed2012-10-05 05:29:32 +0000655
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap(
657 new CommandObjectRegexCommand(
658 *this, "kdp-remote", "Connect to a process via remote KDP server. "
659 "If no UDP port is specified, port 41139 is "
660 "assumed.",
661 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
662 if (connect_kdp_remote_cmd_ap.get()) {
663 if (connect_kdp_remote_cmd_ap->AddRegexCommand(
664 "^([^:]+:[[:digit:]]+)$",
665 "process connect --plugin kdp-remote udp://%1") &&
666 connect_kdp_remote_cmd_ap->AddRegexCommand(
667 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
668 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
669 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Clayton6bade322013-02-01 23:33:03 +0000670 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000671 }
Greg Clayton6bade322013-02-01 23:33:03 +0000672
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap(
674 new CommandObjectRegexCommand(
675 *this, "_regexp-bt",
676 "Show the current thread's call stack. Any numeric argument "
677 "displays at most that many "
678 "frames. The argument 'all' displays all threads.",
679 "bt [<digit> | all]", 2, 0, false));
680 if (bt_regex_cmd_ap.get()) {
681 // accept but don't document "bt -c <number>" -- before bt was a regex
682 // command if you wanted to backtrace
683 // three frames you would do "bt -c 3" but the intention is to have this
684 // emulate the gdb "bt" command and
685 // so now "bt 3" is the preferred form, in line with gdb.
686 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$",
687 "thread backtrace -c %1") &&
688 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$",
689 "thread backtrace -c %1") &&
690 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
691 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) {
692 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
693 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Claytonef5651d2013-02-12 18:52:24 +0000694 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 }
Greg Claytonef5651d2013-02-12 18:52:24 +0000696
Kate Stoneb9c1b512016-09-06 20:57:50 +0000697 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap(
698 new CommandObjectRegexCommand(
699 *this, "_regexp-list",
700 "List relevant source code using one of several shorthand formats.",
701 "\n"
702 "_regexp-list <file>:<line> // List around specific file/line\n"
703 "_regexp-list <line> // List current file around specified "
704 "line\n"
705 "_regexp-list <function-name> // List specified function\n"
706 "_regexp-list 0x<address> // List around specified address\n"
707 "_regexp-list -[<count>] // List previous <count> lines\n"
708 "_regexp-list // List subsequent lines",
709 2, CommandCompletions::eSourceFileCompletion, false));
710 if (list_regex_cmd_ap.get()) {
711 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
712 "source list --line %1") &&
713 list_regex_cmd_ap->AddRegexCommand(
714 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
715 "]*$",
716 "source list --file '%1' --line %2") &&
717 list_regex_cmd_ap->AddRegexCommand(
718 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
719 "source list --address %1") &&
720 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$",
721 "source list --reverse") &&
722 list_regex_cmd_ap->AddRegexCommand(
723 "^-([[:digit:]]+)[[:space:]]*$",
724 "source list --reverse --count %1") &&
725 list_regex_cmd_ap->AddRegexCommand("^(.+)$",
726 "source list --name \"%1\"") &&
727 list_regex_cmd_ap->AddRegexCommand("^$", "source list")) {
728 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
729 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
Richard Mittonf86248d2013-09-12 02:20:34 +0000730 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000731 }
Richard Mittonf86248d2013-09-12 02:20:34 +0000732
Kate Stoneb9c1b512016-09-06 20:57:50 +0000733 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap(
734 new CommandObjectRegexCommand(
735 *this, "_regexp-env",
736 "Shorthand for viewing and setting environment variables.",
737 "\n"
738 "_regexp-env // Show enrivonment\n"
739 "_regexp-env <name>=<value> // Set an environment variable",
740 2, 0, false));
741 if (env_regex_cmd_ap.get()) {
742 if (env_regex_cmd_ap->AddRegexCommand("^$",
743 "settings show target.env-vars") &&
744 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
745 "settings set target.env-vars %1")) {
746 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
747 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
748 }
749 }
750
751 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap(
752 new CommandObjectRegexCommand(
753 *this, "_regexp-jump", "Set the program counter to a new address.",
754 "\n"
755 "_regexp-jump <line>\n"
756 "_regexp-jump +<line-offset> | -<line-offset>\n"
757 "_regexp-jump <file>:<line>\n"
758 "_regexp-jump *<addr>\n",
759 2, 0, false));
760 if (jump_regex_cmd_ap.get()) {
761 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$",
762 "thread jump --addr %1") &&
763 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
764 "thread jump --line %1") &&
765 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$",
766 "thread jump --file %1 --line %2") &&
767 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$",
768 "thread jump --by %1")) {
769 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
770 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
771 }
772 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000773}
774
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775int CommandInterpreter::GetCommandNamesMatchingPartialString(
776 const char *cmd_str, bool include_aliases, StringList &matches) {
777 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000778
Kate Stoneb9c1b512016-09-06 20:57:50 +0000779 if (include_aliases) {
780 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches);
781 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000782
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783 return matches.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000784}
785
Zachary Turnera4496982016-10-05 21:14:38 +0000786CommandObjectSP CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787 bool include_aliases,
788 bool exact,
Zachary Turnera4496982016-10-05 21:14:38 +0000789 StringList *matches) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000790 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000791
Zachary Turnera4496982016-10-05 21:14:38 +0000792 std::string cmd = cmd_str;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000793
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794 if (HasCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000795 auto pos = m_command_dict.find(cmd);
Greg Claytonb5472782015-01-09 19:08:20 +0000796 if (pos != m_command_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 command_sp = pos->second;
798 }
799
800 if (include_aliases && HasAliases()) {
801 auto alias_pos = m_alias_dict.find(cmd);
802 if (alias_pos != m_alias_dict.end())
803 command_sp = alias_pos->second;
804 }
805
806 if (HasUserCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000807 auto pos = m_user_dict.find(cmd);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000808 if (pos != m_user_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000809 command_sp = pos->second;
810 }
811
812 if (!exact && !command_sp) {
813 // We will only get into here if we didn't find any exact matches.
814
815 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
816
817 StringList local_matches;
818 if (matches == nullptr)
819 matches = &local_matches;
820
821 unsigned int num_cmd_matches = 0;
822 unsigned int num_alias_matches = 0;
823 unsigned int num_user_matches = 0;
824
825 // Look through the command dictionaries one by one, and if we get only one
826 // match from any of
827 // them in toto, then return that, otherwise return an empty CommandObjectSP
828 // and the list of matches.
829
830 if (HasCommands()) {
831 num_cmd_matches =
Zachary Turnera4496982016-10-05 21:14:38 +0000832 AddNamesMatchingPartialString(m_command_dict, cmd_str, *matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000833 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834
835 if (num_cmd_matches == 1) {
836 cmd.assign(matches->GetStringAtIndex(0));
Zachary Turnera4496982016-10-05 21:14:38 +0000837 auto pos = m_command_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000838 if (pos != m_command_dict.end())
839 real_match_sp = pos->second;
840 }
841
842 if (include_aliases && HasAliases()) {
843 num_alias_matches =
Zachary Turnera4496982016-10-05 21:14:38 +0000844 AddNamesMatchingPartialString(m_alias_dict, cmd_str, *matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000845 }
846
847 if (num_alias_matches == 1) {
848 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
849 auto alias_pos = m_alias_dict.find(cmd);
850 if (alias_pos != m_alias_dict.end())
851 alias_match_sp = alias_pos->second;
852 }
853
854 if (HasUserCommands()) {
855 num_user_matches =
Zachary Turnera4496982016-10-05 21:14:38 +0000856 AddNamesMatchingPartialString(m_user_dict, cmd_str, *matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000857 }
858
859 if (num_user_matches == 1) {
860 cmd.assign(
861 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
862
Zachary Turnera4496982016-10-05 21:14:38 +0000863 auto pos = m_user_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000864 if (pos != m_user_dict.end())
865 user_match_sp = pos->second;
866 }
867
868 // If we got exactly one match, return that, otherwise return the match
869 // list.
870
871 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
872 if (num_cmd_matches)
873 return real_match_sp;
874 else if (num_alias_matches)
875 return alias_match_sp;
876 else
877 return user_match_sp;
878 }
879 } else if (matches && command_sp) {
Zachary Turnera4496982016-10-05 21:14:38 +0000880 matches->AppendString(cmd_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 }
882
883 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000884}
885
Zachary Turnera4496982016-10-05 21:14:38 +0000886bool CommandInterpreter::AddCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887 const lldb::CommandObjectSP &cmd_sp,
888 bool can_replace) {
889 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000890 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
891 "tried to add a CommandObject from a different interpreter");
Kate Stonea487aa42015-01-15 00:52:41 +0000892
Zachary Turnera4496982016-10-05 21:14:38 +0000893 if (name.empty())
894 return false;
895
896 std::string name_sstr(name);
897 auto name_iter = m_command_dict.find(name_sstr);
898 if (name_iter != m_command_dict.end()) {
899 if (!can_replace || !name_iter->second->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000900 return false;
Zachary Turnera4496982016-10-05 21:14:38 +0000901 name_iter->second = cmd_sp;
902 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000903 m_command_dict[name_sstr] = cmd_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904 }
Zachary Turnera4496982016-10-05 21:14:38 +0000905 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000906}
907
Zachary Turnera483f572016-10-05 21:14:49 +0000908bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000909 const lldb::CommandObjectSP &cmd_sp,
910 bool can_replace) {
911 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000912 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
913 "tried to add a CommandObject from a different interpreter");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000914
Kate Stoneb9c1b512016-09-06 20:57:50 +0000915 if (!name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000916 // do not allow replacement of internal commands
Zachary Turnera483f572016-10-05 21:14:49 +0000917 if (CommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000918 if (can_replace == false)
919 return false;
920 if (m_command_dict[name]->IsRemovable() == false)
Greg Clayton5a314712011-10-14 07:41:33 +0000921 return false;
922 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000923
Zachary Turnera483f572016-10-05 21:14:49 +0000924 if (UserCommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000925 if (can_replace == false)
926 return false;
927 if (m_user_dict[name]->IsRemovable() == false)
928 return false;
Caroline Tice844d2302010-12-09 22:52:49 +0000929 }
930
Kate Stoneb9c1b512016-09-06 20:57:50 +0000931 m_user_dict[name] = cmd_sp;
932 return true;
933 }
934 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000935}
936
Zachary Turnera4496982016-10-05 21:14:38 +0000937CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
938 bool include_aliases) const {
939 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +0000940 // it's a multi-word command.
941 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000942
Zachary Turnera4496982016-10-05 21:14:38 +0000943 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000944 return ret_val;
945
946 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +0000947 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948 else {
949 // We have a multi-word command (seemingly), so we need to do more work.
950 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +0000951 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 include_aliases, true, nullptr);
953 if (cmd_obj_sp.get() != nullptr) {
954 // Loop through the rest of the words in the command (everything passed in
955 // was supposed to be part of a
956 // command name), and find the appropriate sub-command SP for each command
957 // word....
958 size_t end = cmd_words.GetArgumentCount();
959 for (size_t j = 1; j < end; ++j) {
960 if (cmd_obj_sp->IsMultiwordObject()) {
961 cmd_obj_sp =
962 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
963 if (cmd_obj_sp.get() == nullptr)
964 // The sub-command name was invalid. Fail and return the empty
965 // 'ret_val'.
966 return ret_val;
967 } else
968 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +0000969 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000970 return ret_val;
971 }
972 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +0000973 // command objects for them. Assign the last object retrieved to
974 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000975 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000976 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000977 }
978 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000979}
980
Zachary Turnera4496982016-10-05 21:14:38 +0000981CommandObject *CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
982 StringList *matches) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000983 CommandObject *command_obj =
Zachary Turnera4496982016-10-05 21:14:38 +0000984 GetCommandSP(cmd_str, false, true, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000985
Kate Stoneb9c1b512016-09-06 20:57:50 +0000986 // If we didn't find an exact match to the command string in the commands,
987 // look in
988 // the aliases.
989
990 if (command_obj)
991 return command_obj;
992
Zachary Turnera4496982016-10-05 21:14:38 +0000993 command_obj = GetCommandSP(cmd_str, true, true, matches).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000994
995 if (command_obj)
996 return command_obj;
997
998 // If there wasn't an exact match then look for an inexact one in just the
999 // commands
Zachary Turnera4496982016-10-05 21:14:38 +00001000 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001001
1002 // Finally, if there wasn't an inexact match among the commands, look for an
1003 // inexact
1004 // match in both the commands and aliases.
1005
1006 if (command_obj) {
1007 if (matches)
1008 matches->AppendString(command_obj->GetCommandName());
1009 return command_obj;
1010 }
1011
Zachary Turnera4496982016-10-05 21:14:38 +00001012 return GetCommandSP(cmd_str, true, false, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001013}
1014
Zachary Turnera483f572016-10-05 21:14:49 +00001015bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001016 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001017}
1018
Zachary Turnera483f572016-10-05 21:14:49 +00001019bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1020 std::string &full_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001021 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1022 if (exact_match) {
1023 full_name.assign(cmd);
1024 return exact_match;
1025 } else {
1026 StringList matches;
1027 size_t num_alias_matches;
1028 num_alias_matches =
1029 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1030 if (num_alias_matches == 1) {
1031 // Make sure this isn't shadowing a command in the regular command space:
1032 StringList regular_matches;
1033 const bool include_aliases = false;
1034 const bool exact = false;
1035 CommandObjectSP cmd_obj_sp(
1036 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1037 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1038 return false;
1039 else {
1040 full_name.assign(matches.GetStringAtIndex(0));
1041 return true;
1042 }
1043 } else
1044 return false;
1045 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001046}
1047
Zachary Turnera483f572016-10-05 21:14:49 +00001048bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001049 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001050}
1051
Zachary Turnera483f572016-10-05 21:14:49 +00001052bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001053 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001054}
1055
Kate Stoneb9c1b512016-09-06 20:57:50 +00001056CommandAlias *
Zachary Turnera483f572016-10-05 21:14:49 +00001057CommandInterpreter::AddAlias(llvm::StringRef alias_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001058 lldb::CommandObjectSP &command_obj_sp,
Zachary Turnera483f572016-10-05 21:14:49 +00001059 llvm::StringRef args_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001060 if (command_obj_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001061 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1062 "tried to add a CommandObject from a different interpreter");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063
1064 std::unique_ptr<CommandAlias> command_alias_up(
1065 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1066
1067 if (command_alias_up && command_alias_up->IsValid()) {
1068 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1069 return command_alias_up.release();
1070 }
1071
1072 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001073}
1074
Zachary Turnera483f572016-10-05 21:14:49 +00001075bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076 auto pos = m_alias_dict.find(alias_name);
1077 if (pos != m_alias_dict.end()) {
1078 m_alias_dict.erase(pos);
1079 return true;
1080 }
1081 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001082}
1083
Zachary Turnera483f572016-10-05 21:14:49 +00001084bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001085 auto pos = m_command_dict.find(cmd);
1086 if (pos != m_command_dict.end()) {
1087 if (pos->second->IsRemovable()) {
1088 // Only regular expression objects or python commands are removable
1089 m_command_dict.erase(pos);
1090 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001091 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001092 }
1093 return false;
1094}
Zachary Turnera483f572016-10-05 21:14:49 +00001095bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001096 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1097 if (pos != m_user_dict.end()) {
1098 m_user_dict.erase(pos);
1099 return true;
1100 }
1101 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001102}
1103
Kate Stoneb9c1b512016-09-06 20:57:50 +00001104void CommandInterpreter::GetHelp(CommandReturnObject &result,
1105 uint32_t cmd_types) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001106 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1107 if (!help_prologue.empty()) {
1108 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1109 help_prologue);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001110 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001111
Kate Stoneb9c1b512016-09-06 20:57:50 +00001112 CommandObject::CommandMap::const_iterator pos;
1113 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001114
Kate Stoneb9c1b512016-09-06 20:57:50 +00001115 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1116 result.AppendMessage("Debugger commands:");
1117 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001118
Kate Stoneb9c1b512016-09-06 20:57:50 +00001119 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1120 if (!(cmd_types & eCommandTypesHidden) &&
1121 (pos->first.compare(0, 1, "_") == 0))
1122 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001123
Zachary Turner0ac5f982016-11-08 04:12:42 +00001124 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1125 pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001126 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127 result.AppendMessage("");
1128 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001129
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130 if (!m_alias_dict.empty() &&
1131 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1132 result.AppendMessageWithFormat(
1133 "Current command abbreviations "
1134 "(type '%shelp command alias' for more info):\n",
1135 GetCommandPrefix());
1136 result.AppendMessage("");
1137 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001138
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1140 ++alias_pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001141 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
Kate Stoneb9c1b512016-09-06 20:57:50 +00001142 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001143 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001144 result.AppendMessage("");
1145 }
Greg Clayton14a35512011-09-11 00:01:44 +00001146
Kate Stoneb9c1b512016-09-06 20:57:50 +00001147 if (!m_user_dict.empty() &&
1148 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1149 result.AppendMessage("Current user-defined commands:");
1150 result.AppendMessage("");
1151 max_len = FindLongestCommandWord(m_user_dict);
1152 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001153 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1154 pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001155 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001156 result.AppendMessage("");
1157 }
Greg Clayton14a35512011-09-11 00:01:44 +00001158
Kate Stoneb9c1b512016-09-06 20:57:50 +00001159 result.AppendMessageWithFormat(
1160 "For more information on any command, type '%shelp <command-name>'.\n",
1161 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001162}
1163
Zachary Turnera01bccd2016-10-05 21:14:56 +00001164CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1165 llvm::StringRef &command_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001166 // This function finds the final, lowest-level, alias-resolved command object
1167 // whose 'Execute' function will
1168 // eventually be invoked by the given command line.
1169
1170 CommandObject *cmd_obj = nullptr;
1171 size_t start = command_string.find_first_not_of(k_white_space);
1172 size_t end = 0;
1173 bool done = false;
1174 while (!done) {
1175 if (start != std::string::npos) {
1176 // Get the next word from command_string.
1177 end = command_string.find_first_of(k_white_space, start);
1178 if (end == std::string::npos)
1179 end = command_string.size();
1180 std::string cmd_word = command_string.substr(start, end - start);
1181
1182 if (cmd_obj == nullptr)
1183 // Since cmd_obj is NULL we are on our first time through this loop.
Zachary Turnera01bccd2016-10-05 21:14:56 +00001184 // Check to see if cmd_word is a valid command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001185 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001186 else if (cmd_obj->IsMultiwordObject()) {
1187 // Our current object is a multi-word object; see if the cmd_word is a
1188 // valid sub-command for our object.
1189 CommandObject *sub_cmd_obj =
1190 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1191 if (sub_cmd_obj)
1192 cmd_obj = sub_cmd_obj;
1193 else // cmd_word was not a valid sub-command word, so we are done
1194 done = true;
1195 } else
1196 // We have a cmd_obj and it is not a multi-word object, so we are done.
1197 done = true;
1198
1199 // If we didn't find a valid command object, or our command object is not
Zachary Turnera01bccd2016-10-05 21:14:56 +00001200 // a multi-word object, or we are at the end of the command_string, then
1201 // we are done. Otherwise, find the start of the next word.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001202
1203 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1204 end >= command_string.size())
1205 done = true;
1206 else
1207 start = command_string.find_first_not_of(k_white_space, end);
1208 } else
1209 // Unable to find any more words.
1210 done = true;
1211 }
1212
Zachary Turnera01bccd2016-10-05 21:14:56 +00001213 command_string = command_string.substr(end);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214 return cmd_obj;
1215}
1216
1217static const char *k_valid_command_chars =
1218 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1219static void StripLeadingSpaces(std::string &s) {
1220 if (!s.empty()) {
1221 size_t pos = s.find_first_not_of(k_white_space);
1222 if (pos == std::string::npos)
1223 s.clear();
1224 else if (pos == 0)
1225 return;
1226 s.erase(0, pos);
1227 }
1228}
1229
1230static size_t FindArgumentTerminator(const std::string &s) {
1231 const size_t s_len = s.size();
1232 size_t offset = 0;
1233 while (offset < s_len) {
1234 size_t pos = s.find("--", offset);
1235 if (pos == std::string::npos)
1236 break;
1237 if (pos > 0) {
1238 if (isspace(s[pos - 1])) {
1239 // Check if the string ends "\s--" (where \s is a space character)
1240 // or if we have "\s--\s".
1241 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1242 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001243 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001244 }
1245 }
1246 offset = pos + 2;
1247 }
1248 return std::string::npos;
1249}
1250
1251static bool ExtractCommand(std::string &command_string, std::string &command,
1252 std::string &suffix, char &quote_char) {
1253 command.clear();
1254 suffix.clear();
1255 StripLeadingSpaces(command_string);
1256
1257 bool result = false;
1258 quote_char = '\0';
1259
1260 if (!command_string.empty()) {
1261 const char first_char = command_string[0];
1262 if (first_char == '\'' || first_char == '"') {
1263 quote_char = first_char;
1264 const size_t end_quote_pos = command_string.find(quote_char, 1);
1265 if (end_quote_pos == std::string::npos) {
1266 command.swap(command_string);
1267 command_string.erase();
1268 } else {
1269 command.assign(command_string, 1, end_quote_pos - 1);
1270 if (end_quote_pos + 1 < command_string.size())
1271 command_string.erase(0, command_string.find_first_not_of(
1272 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001273 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274 command_string.erase();
1275 }
1276 } else {
1277 const size_t first_space_pos =
1278 command_string.find_first_of(k_white_space);
1279 if (first_space_pos == std::string::npos) {
1280 command.swap(command_string);
1281 command_string.erase();
1282 } else {
1283 command.assign(command_string, 0, first_space_pos);
1284 command_string.erase(0, command_string.find_first_not_of(
1285 k_white_space, first_space_pos));
1286 }
1287 }
1288 result = true;
1289 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001290
Kate Stoneb9c1b512016-09-06 20:57:50 +00001291 if (!command.empty()) {
1292 // actual commands can't start with '-' or '_'
1293 if (command[0] != '-' && command[0] != '_') {
1294 size_t pos = command.find_first_not_of(k_valid_command_chars);
1295 if (pos > 0 && pos != std::string::npos) {
1296 suffix.assign(command.begin() + pos, command.end());
1297 command.erase(pos);
1298 }
1299 }
1300 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001301
Kate Stoneb9c1b512016-09-06 20:57:50 +00001302 return result;
1303}
1304
1305CommandObject *CommandInterpreter::BuildAliasResult(
Zachary Turnera483f572016-10-05 21:14:49 +00001306 llvm::StringRef alias_name, std::string &raw_input_string,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001307 std::string &alias_result, CommandReturnObject &result) {
1308 CommandObject *alias_cmd_obj = nullptr;
1309 Args cmd_args(raw_input_string);
1310 alias_cmd_obj = GetCommandObject(alias_name);
1311 StreamString result_str;
1312
Zachary Turner5c28c662016-10-03 23:20:36 +00001313 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1314 alias_result.clear();
1315 return alias_cmd_obj;
1316 }
1317 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1318 ((CommandAlias *)alias_cmd_obj)->Desugar();
1319 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1320 alias_cmd_obj = desugared.first.get();
1321 std::string alias_name_str = alias_name;
1322 if ((cmd_args.GetArgumentCount() == 0) ||
1323 (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0))
1324 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001325
Zachary Turnera4496982016-10-05 21:14:38 +00001326 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001327
Zachary Turner5c28c662016-10-03 23:20:36 +00001328 if (!option_arg_vector_sp.get()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001329 alias_result = result_str.GetString();
Zachary Turner5c28c662016-10-03 23:20:36 +00001330 return alias_cmd_obj;
1331 }
1332 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001333
Zachary Turner5c28c662016-10-03 23:20:36 +00001334 int value_type;
1335 std::string option;
1336 std::string value;
1337 for (const auto &entry : *option_arg_vector) {
1338 std::tie(option, value_type, value) = entry;
1339 if (option == "<argument>") {
1340 result_str.Printf(" %s", value.c_str());
1341 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001342 }
1343
Zachary Turner5c28c662016-10-03 23:20:36 +00001344 result_str.Printf(" %s", option.c_str());
1345 if (value_type == OptionParser::eNoArgument)
1346 continue;
1347
1348 if (value_type != OptionParser::eOptionalArgument)
1349 result_str.Printf(" ");
1350 int index = GetOptionArgumentPosition(value.c_str());
1351 if (index == 0)
1352 result_str.Printf("%s", value.c_str());
1353 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1354
1355 result.AppendErrorWithFormat("Not enough arguments provided; you "
1356 "need at least %d arguments to use "
1357 "this alias.\n",
1358 index);
1359 result.SetStatus(eReturnStatusFailed);
1360 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001361 } else {
1362 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1363 if (strpos != std::string::npos)
1364 raw_input_string = raw_input_string.erase(
1365 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1366 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001367 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001368 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001369
Zachary Turnerc1564272016-11-16 21:15:24 +00001370 alias_result = result_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001371 return alias_cmd_obj;
1372}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001373
Zachary Turner97206d52017-05-12 04:51:55 +00001374Status CommandInterpreter::PreprocessCommand(std::string &command) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001375 // The command preprocessor needs to do things to the command
1376 // line before any parsing of arguments or anything else is done.
1377 // The only current stuff that gets preprocessed is anything enclosed
1378 // in backtick ('`') characters is evaluated as an expression and
1379 // the result of the expression must be a scalar that can be substituted
1380 // into the command. An example would be:
1381 // (lldb) memory read `$rsp + 20`
Zachary Turner97206d52017-05-12 04:51:55 +00001382 Status error; // Status for any expressions that might not evaluate
Kate Stoneb9c1b512016-09-06 20:57:50 +00001383 size_t start_backtick;
1384 size_t pos = 0;
1385 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1386 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
1387 // The backtick was preceded by a '\' character, remove the slash
1388 // and don't treat the backtick as the start of an expression
1389 command.erase(start_backtick - 1, 1);
1390 // No need to add one to start_backtick since we just deleted a char
1391 pos = start_backtick;
1392 } else {
1393 const size_t expr_content_start = start_backtick + 1;
1394 const size_t end_backtick = command.find('`', expr_content_start);
1395 if (end_backtick == std::string::npos)
1396 return error;
1397 else if (end_backtick == expr_content_start) {
1398 // Empty expression (two backticks in a row)
1399 command.erase(start_backtick, 2);
1400 } else {
1401 std::string expr_str(command, expr_content_start,
1402 end_backtick - expr_content_start);
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001403
Kate Stoneb9c1b512016-09-06 20:57:50 +00001404 ExecutionContext exe_ctx(GetExecutionContext());
1405 Target *target = exe_ctx.GetTargetPtr();
1406 // Get a dummy target to allow for calculator mode while processing
1407 // backticks.
1408 // This also helps break the infinite loop caused when target is null.
1409 if (!target)
1410 target = m_debugger.GetDummyTarget();
1411 if (target) {
1412 ValueObjectSP expr_result_valobj_sp;
1413
1414 EvaluateExpressionOptions options;
1415 options.SetCoerceToId(false);
1416 options.SetUnwindOnError(true);
1417 options.SetIgnoreBreakpoints(true);
1418 options.SetKeepInMemory(false);
1419 options.SetTryAllThreads(true);
Pavel Labath43d35412016-12-06 11:24:51 +00001420 options.SetTimeout(llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001421
1422 ExpressionResults expr_result = target->EvaluateExpression(
1423 expr_str.c_str(), exe_ctx.GetFramePtr(), expr_result_valobj_sp,
1424 options);
1425
1426 if (expr_result == eExpressionCompleted) {
1427 Scalar scalar;
1428 if (expr_result_valobj_sp)
1429 expr_result_valobj_sp =
1430 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1431 expr_result_valobj_sp->GetDynamicValueType(), true);
1432 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1433 command.erase(start_backtick, end_backtick - start_backtick + 1);
1434 StreamString value_strm;
1435 const bool show_type = false;
1436 scalar.GetValue(&value_strm, show_type);
1437 size_t value_string_size = value_strm.GetSize();
1438 if (value_string_size) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001439 command.insert(start_backtick, value_strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 pos = start_backtick + value_string_size;
1441 continue;
1442 } else {
1443 error.SetErrorStringWithFormat("expression value didn't result "
1444 "in a scalar value for the "
1445 "expression '%s'",
1446 expr_str.c_str());
1447 }
1448 } else {
1449 error.SetErrorStringWithFormat("expression value didn't result "
1450 "in a scalar value for the "
1451 "expression '%s'",
1452 expr_str.c_str());
1453 }
1454 } else {
1455 if (expr_result_valobj_sp)
1456 error = expr_result_valobj_sp->GetError();
1457 if (error.Success()) {
1458
1459 switch (expr_result) {
1460 case eExpressionSetupError:
1461 error.SetErrorStringWithFormat(
1462 "expression setup error for the expression '%s'",
1463 expr_str.c_str());
1464 break;
1465 case eExpressionParseError:
1466 error.SetErrorStringWithFormat(
1467 "expression parse error for the expression '%s'",
1468 expr_str.c_str());
1469 break;
1470 case eExpressionResultUnavailable:
1471 error.SetErrorStringWithFormat(
1472 "expression error fetching result for the expression '%s'",
1473 expr_str.c_str());
1474 break;
1475 case eExpressionCompleted:
1476 break;
1477 case eExpressionDiscarded:
1478 error.SetErrorStringWithFormat(
1479 "expression discarded for the expression '%s'",
1480 expr_str.c_str());
1481 break;
1482 case eExpressionInterrupted:
1483 error.SetErrorStringWithFormat(
1484 "expression interrupted for the expression '%s'",
1485 expr_str.c_str());
1486 break;
1487 case eExpressionHitBreakpoint:
1488 error.SetErrorStringWithFormat(
1489 "expression hit breakpoint for the expression '%s'",
1490 expr_str.c_str());
1491 break;
1492 case eExpressionTimedOut:
1493 error.SetErrorStringWithFormat(
1494 "expression timed out for the expression '%s'",
1495 expr_str.c_str());
1496 break;
1497 case eExpressionStoppedForDebug:
1498 error.SetErrorStringWithFormat("expression stop at entry point "
1499 "for debugging for the "
1500 "expression '%s'",
1501 expr_str.c_str());
1502 break;
1503 }
1504 }
1505 }
1506 }
1507 }
1508 if (error.Fail())
1509 break;
1510 }
1511 }
1512 return error;
1513}
1514
1515bool CommandInterpreter::HandleCommand(const char *command_line,
1516 LazyBool lazy_add_to_history,
1517 CommandReturnObject &result,
1518 ExecutionContext *override_context,
1519 bool repeat_on_empty_command,
1520 bool no_context_switching)
1521
1522{
1523
1524 std::string command_string(command_line);
1525 std::string original_command_string(command_line);
1526
1527 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
Jim Ingham8f7db522016-12-15 00:30:30 +00001528 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
Sean Callanan237c3ed2016-12-14 21:31:31 +00001529 command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001530
1531 if (log)
1532 log->Printf("Processing command: %s", command_line);
1533
Pavel Labathf9d16472017-05-15 13:02:37 +00001534 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1535 Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001536
1537 if (!no_context_switching)
1538 UpdateExecutionContext(override_context);
1539
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001540 if (WasInterrupted()) {
1541 result.AppendError("interrupted");
1542 result.SetStatus(eReturnStatusFailed);
1543 return false;
1544 }
1545
Kate Stoneb9c1b512016-09-06 20:57:50 +00001546 bool add_to_history;
1547 if (lazy_add_to_history == eLazyBoolCalculate)
1548 add_to_history = (m_command_source_depth == 0);
1549 else
1550 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1551
1552 bool empty_command = false;
1553 bool comment_command = false;
1554 if (command_string.empty())
1555 empty_command = true;
1556 else {
1557 const char *k_space_characters = "\t\n\v\f\r ";
1558
1559 size_t non_space = command_string.find_first_not_of(k_space_characters);
1560 // Check for empty line or comment line (lines whose first
1561 // non-space character is the comment character for this interpreter)
1562 if (non_space == std::string::npos)
1563 empty_command = true;
1564 else if (command_string[non_space] == m_comment_char)
1565 comment_command = true;
1566 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001567 llvm::StringRef search_str(command_string);
1568 search_str = search_str.drop_front(non_space);
1569 if (auto hist_str = m_command_history.FindString(search_str)) {
1570 add_to_history = false;
1571 command_string = *hist_str;
1572 original_command_string = *hist_str;
1573 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001574 result.AppendErrorWithFormat("Could not find entry: %s in history",
1575 command_string.c_str());
1576 result.SetStatus(eReturnStatusFailed);
1577 return false;
1578 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001579 }
1580 }
1581
1582 if (empty_command) {
1583 if (repeat_on_empty_command) {
1584 if (m_command_history.IsEmpty()) {
1585 result.AppendError("empty command");
1586 result.SetStatus(eReturnStatusFailed);
1587 return false;
1588 } else {
1589 command_line = m_repeat_command.c_str();
1590 command_string = command_line;
1591 original_command_string = command_line;
1592 if (m_repeat_command.empty()) {
1593 result.AppendErrorWithFormat("No auto repeat.\n");
1594 result.SetStatus(eReturnStatusFailed);
1595 return false;
1596 }
1597 }
1598 add_to_history = false;
1599 } else {
1600 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1601 return true;
1602 }
1603 } else if (comment_command) {
1604 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1605 return true;
1606 }
1607
Zachary Turner97206d52017-05-12 04:51:55 +00001608 Status error(PreprocessCommand(command_string));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001609
1610 if (error.Fail()) {
1611 result.AppendError(error.AsCString());
1612 result.SetStatus(eReturnStatusFailed);
1613 return false;
1614 }
1615
1616 // Phase 1.
1617
1618 // Before we do ANY kind of argument processing, we need to figure out what
1619 // the real/final command object is for the specified command. This gets
1620 // complicated by the fact that the user could have specified an alias, and,
1621 // in translating the alias, there may also be command options and/or even
1622 // data (including raw text strings) that need to be found and inserted into
1623 // the command line as part of the translation. So this first step is plain
1624 // look-up and replacement, resulting in:
1625 // 1. the command object whose Execute method will actually be called
1626 // 2. a revised command string, with all substitutions and replacements
1627 // taken care of
1628 // From 1 above, we can determine whether the Execute function wants raw
1629 // input or not.
1630
1631 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1632
1633 // Although the user may have abbreviated the command, the command_string now
1634 // has the command expanded to the full name. For example, if the input
1635 // was "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001636 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001637 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1638 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001639 log->Printf("HandleCommand, (revised) command_string: '%s'",
1640 command_string.c_str());
1641 const bool wants_raw_input =
1642 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1643 log->Printf("HandleCommand, wants_raw_input:'%s'",
1644 wants_raw_input ? "True" : "False");
1645 }
1646
1647 // Phase 2.
1648 // Take care of things like setting up the history command & calling the
1649 // appropriate Execute method on the
1650 // CommandObject, with the appropriate arguments.
1651
1652 if (cmd_obj != nullptr) {
1653 if (add_to_history) {
1654 Args command_args(command_string);
1655 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1656 if (repeat_command != nullptr)
1657 m_repeat_command.assign(repeat_command);
1658 else
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001659 m_repeat_command.assign(original_command_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001660
1661 m_command_history.AppendString(original_command_string);
1662 }
1663
1664 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001665 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001666 if (actual_cmd_name_len < command_string.length())
1667 remainder = command_string.substr(actual_cmd_name_len);
1668
1669 // Remove any initial spaces
1670 size_t pos = remainder.find_first_not_of(k_white_space);
1671 if (pos != 0 && pos != std::string::npos)
1672 remainder.erase(0, pos);
1673
1674 if (log)
1675 log->Printf(
1676 "HandleCommand, command line after removing command name(s): '%s'",
1677 remainder.c_str());
1678
1679 cmd_obj->Execute(remainder.c_str(), result);
1680 } else {
1681 // We didn't find the first command object, so complete the first argument.
1682 Args command_args(command_string);
1683 StringList matches;
1684 int num_matches;
1685 int cursor_index = 0;
1686 int cursor_char_position = strlen(command_args.GetArgumentAtIndex(0));
1687 bool word_complete;
1688 num_matches = HandleCompletionMatches(command_args, cursor_index,
1689 cursor_char_position, 0, -1,
1690 word_complete, matches);
1691
1692 if (num_matches > 0) {
1693 std::string error_msg;
1694 error_msg.assign("ambiguous command '");
1695 error_msg.append(command_args.GetArgumentAtIndex(0));
1696 error_msg.append("'.");
1697
1698 error_msg.append(" Possible completions:");
1699 for (int i = 0; i < num_matches; i++) {
1700 error_msg.append("\n\t");
1701 error_msg.append(matches.GetStringAtIndex(i));
1702 }
1703 error_msg.append("\n");
1704 result.AppendRawError(error_msg.c_str());
1705 } else
1706 result.AppendErrorWithFormat("Unrecognized command '%s'.\n",
1707 command_args.GetArgumentAtIndex(0));
1708
1709 result.SetStatus(eReturnStatusFailed);
1710 }
1711
1712 if (log)
1713 log->Printf("HandleCommand, command %s",
1714 (result.Succeeded() ? "succeeded" : "did not succeed"));
1715
1716 return result.Succeeded();
1717}
1718
1719int CommandInterpreter::HandleCompletionMatches(
1720 Args &parsed_line, int &cursor_index, int &cursor_char_position,
1721 int match_start_point, int max_return_elements, bool &word_complete,
1722 StringList &matches) {
1723 int num_command_matches = 0;
1724 bool look_for_subcommand = false;
1725
1726 // For any of the command completions a unique match will be a complete word.
1727 word_complete = true;
1728
1729 if (cursor_index == -1) {
1730 // We got nothing on the command line, so return the list of commands
1731 bool include_aliases = true;
1732 num_command_matches =
1733 GetCommandNamesMatchingPartialString("", include_aliases, matches);
1734 } else if (cursor_index == 0) {
1735 // The cursor is in the first argument, so just do a lookup in the
1736 // dictionary.
1737 CommandObject *cmd_obj =
1738 GetCommandObject(parsed_line.GetArgumentAtIndex(0), &matches);
1739 num_command_matches = matches.GetSize();
1740
1741 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
1742 matches.GetStringAtIndex(0) != nullptr &&
1743 strcmp(parsed_line.GetArgumentAtIndex(0),
1744 matches.GetStringAtIndex(0)) == 0) {
1745 if (parsed_line.GetArgumentCount() == 1) {
1746 word_complete = true;
1747 } else {
1748 look_for_subcommand = true;
1749 num_command_matches = 0;
1750 matches.DeleteStringAtIndex(0);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001751 parsed_line.AppendArgument(llvm::StringRef());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001752 cursor_index++;
1753 cursor_char_position = 0;
1754 }
1755 }
1756 }
1757
1758 if (cursor_index > 0 || look_for_subcommand) {
1759 // We are completing further on into a commands arguments, so find the
1760 // command and tell it
1761 // to complete the command.
1762 // First see if there is a matching initial command:
1763 CommandObject *command_object =
1764 GetCommandObject(parsed_line.GetArgumentAtIndex(0));
1765 if (command_object == nullptr) {
1766 return 0;
1767 } else {
1768 parsed_line.Shift();
1769 cursor_index--;
1770 num_command_matches = command_object->HandleCompletion(
1771 parsed_line, cursor_index, cursor_char_position, match_start_point,
1772 max_return_elements, word_complete, matches);
1773 }
1774 }
1775
1776 return num_command_matches;
1777}
1778
1779int CommandInterpreter::HandleCompletion(
1780 const char *current_line, const char *cursor, const char *last_char,
1781 int match_start_point, int max_return_elements, StringList &matches) {
1782 // We parse the argument up to the cursor, so the last argument in parsed_line
1783 // is
1784 // the one containing the cursor, and the cursor is after the last character.
1785
1786 Args parsed_line(llvm::StringRef(current_line, last_char - current_line));
1787 Args partial_parsed_line(
1788 llvm::StringRef(current_line, cursor - current_line));
1789
1790 // Don't complete comments, and if the line we are completing is just the
1791 // history repeat character,
1792 // substitute the appropriate history line.
1793 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1794 if (first_arg) {
1795 if (first_arg[0] == m_comment_char)
1796 return 0;
1797 else if (first_arg[0] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001798 if (auto hist_str = m_command_history.FindString(first_arg)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001799 matches.Clear();
Zachary Turner53877af2016-11-18 23:22:42 +00001800 matches.InsertStringAtIndex(0, *hist_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001801 return -2;
1802 } else
1803 return 0;
1804 }
1805 }
1806
1807 int num_args = partial_parsed_line.GetArgumentCount();
1808 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1809 int cursor_char_position;
1810
1811 if (cursor_index == -1)
1812 cursor_char_position = 0;
1813 else
1814 cursor_char_position =
1815 strlen(partial_parsed_line.GetArgumentAtIndex(cursor_index));
1816
1817 if (cursor > current_line && cursor[-1] == ' ') {
1818 // We are just after a space. If we are in an argument, then we will
1819 // continue
1820 // parsing, but if we are between arguments, then we have to complete
1821 // whatever the next
1822 // element would be.
1823 // We can distinguish the two cases because if we are in an argument (e.g.
1824 // because the space is
1825 // protected by a quote) then the space will also be in the parsed
1826 // argument...
1827
1828 const char *current_elem =
1829 partial_parsed_line.GetArgumentAtIndex(cursor_index);
1830 if (cursor_char_position == 0 ||
1831 current_elem[cursor_char_position - 1] != ' ') {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001832 parsed_line.InsertArgumentAtIndex(cursor_index + 1, llvm::StringRef(),
1833 '\0');
Kate Stoneb9c1b512016-09-06 20:57:50 +00001834 cursor_index++;
1835 cursor_char_position = 0;
1836 }
1837 }
1838
1839 int num_command_matches;
1840
1841 matches.Clear();
1842
1843 // Only max_return_elements == -1 is supported at present:
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001844 lldbassert(max_return_elements == -1);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001845 bool word_complete;
1846 num_command_matches = HandleCompletionMatches(
1847 parsed_line, cursor_index, cursor_char_position, match_start_point,
1848 max_return_elements, word_complete, matches);
1849
1850 if (num_command_matches <= 0)
1851 return num_command_matches;
1852
1853 if (num_args == 0) {
1854 // If we got an empty string, insert nothing.
1855 matches.InsertStringAtIndex(0, "");
1856 } else {
1857 // Now figure out if there is a common substring, and if so put that in
1858 // element 0, otherwise
1859 // put an empty string in element 0.
1860 std::string command_partial_str;
1861 if (cursor_index >= 0)
Zachary Turnerd6a24752016-11-22 17:10:15 +00001862 command_partial_str =
1863 parsed_line[cursor_index].ref.take_front(cursor_char_position);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001864
1865 std::string common_prefix;
1866 matches.LongestCommonPrefix(common_prefix);
1867 const size_t partial_name_len = command_partial_str.size();
1868 common_prefix.erase(0, partial_name_len);
1869
1870 // If we matched a unique single command, add a space...
1871 // Only do this if the completer told us this was a complete word,
1872 // however...
1873 if (num_command_matches == 1 && word_complete) {
Zachary Turnerd6a24752016-11-22 17:10:15 +00001874 char quote_char = parsed_line[cursor_index].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001875 common_prefix =
1876 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1877 if (quote_char != '\0')
1878 common_prefix.push_back(quote_char);
1879 common_prefix.push_back(' ');
1880 }
1881 matches.InsertStringAtIndex(0, common_prefix.c_str());
1882 }
1883 return num_command_matches;
1884}
1885
1886CommandInterpreter::~CommandInterpreter() {}
1887
Zachary Turner514d8cd2016-09-23 18:06:53 +00001888void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001889 EventSP prompt_change_event_sp(
1890 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1891 ;
1892 BroadcastEvent(prompt_change_event_sp);
1893 if (m_command_io_handler_sp)
1894 m_command_io_handler_sp->SetPrompt(new_prompt);
1895}
1896
Zachary Turner7a120c82016-11-13 03:05:58 +00001897bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001898 // Check AutoConfirm first:
1899 if (m_debugger.GetAutoConfirm())
1900 return default_answer;
1901
1902 IOHandlerConfirm *confirm =
1903 new IOHandlerConfirm(m_debugger, message, default_answer);
1904 IOHandlerSP io_handler_sp(confirm);
1905 m_debugger.RunIOHandler(io_handler_sp);
1906 return confirm->GetResponse();
1907}
1908
Zachary Turnera483f572016-10-05 21:14:49 +00001909const CommandAlias *
1910CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001911 OptionArgVectorSP ret_val;
1912
Zachary Turnera483f572016-10-05 21:14:49 +00001913 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001914 if (pos != m_alias_dict.end())
1915 return (CommandAlias *)pos->second.get();
1916
1917 return nullptr;
1918}
1919
Zachary Turnera4496982016-10-05 21:14:38 +00001920bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001921
Zachary Turnera4496982016-10-05 21:14:38 +00001922bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001923
Zachary Turnera4496982016-10-05 21:14:38 +00001924bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001925
Zachary Turnera4496982016-10-05 21:14:38 +00001926bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001927
1928void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1929 const char *alias_name,
1930 Args &cmd_args,
1931 std::string &raw_input_string,
1932 CommandReturnObject &result) {
1933 OptionArgVectorSP option_arg_vector_sp =
1934 GetAlias(alias_name)->GetOptionArguments();
1935
1936 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1937
1938 // Make sure that the alias name is the 0th element in cmd_args
1939 std::string alias_name_str = alias_name;
1940 if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)
Zachary Turner5c725f32016-09-19 21:56:59 +00001941 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001942
1943 Args new_args(alias_cmd_obj->GetCommandName());
1944 if (new_args.GetArgumentCount() == 2)
1945 new_args.Shift();
1946
1947 if (option_arg_vector_sp.get()) {
1948 if (wants_raw_input) {
1949 // We have a command that both has command options and takes raw input.
1950 // Make *sure* it has a
1951 // " -- " in the right place in the raw_input_string.
1952 size_t pos = raw_input_string.find(" -- ");
1953 if (pos == std::string::npos) {
1954 // None found; assume it goes at the beginning of the raw input string
1955 raw_input_string.insert(0, " -- ");
1956 }
1957 }
1958
1959 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1960 const size_t old_size = cmd_args.GetArgumentCount();
1961 std::vector<bool> used(old_size + 1, false);
1962
1963 used[0] = true;
1964
Zachary Turner5c28c662016-10-03 23:20:36 +00001965 int value_type;
1966 std::string option;
1967 std::string value;
1968 for (const auto &option_entry : *option_arg_vector) {
1969 std::tie(option, value_type, value) = option_entry;
1970 if (option == "<argument>") {
1971 if (!wants_raw_input || (value != "--")) {
1972 // Since we inserted this above, make sure we don't insert it twice
1973 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001974 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001975 continue;
1976 }
1977
1978 if (value_type != OptionParser::eOptionalArgument)
1979 new_args.AppendArgument(option);
1980
1981 if (value == "<no-argument>")
1982 continue;
1983
1984 int index = GetOptionArgumentPosition(value.c_str());
1985 if (index == 0) {
1986 // value was NOT a positional argument; must be a real value
1987 if (value_type != OptionParser::eOptionalArgument)
1988 new_args.AppendArgument(value);
1989 else {
1990 char buffer[255];
1991 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1992 value.c_str());
1993 new_args.AppendArgument(llvm::StringRef(buffer));
1994 }
1995
1996 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1997 result.AppendErrorWithFormat("Not enough arguments provided; you "
1998 "need at least %d arguments to use "
1999 "this alias.\n",
2000 index);
2001 result.SetStatus(eReturnStatusFailed);
2002 return;
2003 } else {
2004 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2005 size_t strpos =
2006 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
2007 if (strpos != std::string::npos) {
2008 raw_input_string = raw_input_string.erase(
2009 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2010 }
2011
2012 if (value_type != OptionParser::eOptionalArgument)
2013 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2014 else {
2015 char buffer[255];
2016 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2017 cmd_args.GetArgumentAtIndex(index));
2018 new_args.AppendArgument(buffer);
2019 }
2020 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002021 }
2022 }
2023
Zachary Turner97d2c402016-10-05 23:40:23 +00002024 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00002025 if (!used[entry.index()] && !wants_raw_input)
2026 new_args.AppendArgument(entry.value().ref);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002027 }
2028
2029 cmd_args.Clear();
2030 cmd_args.SetArguments(new_args.GetArgumentCount(),
2031 new_args.GetConstArgumentVector());
2032 } else {
2033 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2034 // This alias was not created with any options; nothing further needs to be
2035 // done, unless it is a command that
2036 // wants raw input, in which case we need to clear the rest of the data from
2037 // cmd_args, since its in the raw
2038 // input string.
2039 if (wants_raw_input) {
2040 cmd_args.Clear();
2041 cmd_args.SetArguments(new_args.GetArgumentCount(),
2042 new_args.GetConstArgumentVector());
2043 }
2044 return;
2045 }
2046
2047 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2048 return;
2049}
2050
2051int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2052 int position = 0; // Any string that isn't an argument position, i.e. '%'
2053 // followed by an integer, gets a position
2054 // of zero.
2055
2056 const char *cptr = in_string;
2057
2058 // Does it start with '%'
2059 if (cptr[0] == '%') {
2060 ++cptr;
2061
2062 // Is the rest of it entirely digits?
2063 if (isdigit(cptr[0])) {
2064 const char *start = cptr;
2065 while (isdigit(cptr[0]))
2066 ++cptr;
2067
2068 // We've gotten to the end of the digits; are we at the end of the string?
2069 if (cptr[0] == '\0')
2070 position = atoi(start);
2071 }
2072 }
2073
2074 return position;
2075}
2076
2077void CommandInterpreter::SourceInitFile(bool in_cwd,
2078 CommandReturnObject &result) {
2079 FileSpec init_file;
2080 if (in_cwd) {
2081 ExecutionContext exe_ctx(GetExecutionContext());
2082 Target *target = exe_ctx.GetTargetPtr();
2083 if (target) {
2084 // In the current working directory we don't load any program specific
2085 // .lldbinit files, we only look for a ".lldbinit" file.
2086 if (m_skip_lldbinit_files)
2087 return;
2088
2089 LoadCWDlldbinitFile should_load =
2090 target->TargetProperties::GetLoadCWDlldbinitFile();
2091 if (should_load == eLoadCWDlldbinitWarn) {
2092 FileSpec dot_lldb(".lldbinit", true);
2093 llvm::SmallString<64> home_dir_path;
2094 llvm::sys::path::home_directory(home_dir_path);
2095 FileSpec homedir_dot_lldb(home_dir_path.c_str(), false);
2096 homedir_dot_lldb.AppendPathComponent(".lldbinit");
2097 homedir_dot_lldb.ResolvePath();
2098 if (dot_lldb.Exists() &&
2099 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2100 result.AppendErrorWithFormat(
2101 "There is a .lldbinit file in the current directory which is not "
2102 "being read.\n"
2103 "To silence this warning without sourcing in the local "
2104 ".lldbinit,\n"
2105 "add the following to the lldbinit file in your home directory:\n"
2106 " settings set target.load-cwd-lldbinit false\n"
2107 "To allow lldb to source .lldbinit files in the current working "
2108 "directory,\n"
2109 "set the value of this variable to true. Only do so if you "
2110 "understand and\n"
2111 "accept the security risk.");
2112 result.SetStatus(eReturnStatusFailed);
2113 return;
2114 }
2115 } else if (should_load == eLoadCWDlldbinitTrue) {
2116 init_file.SetFile("./.lldbinit", true);
2117 }
2118 }
2119 } else {
2120 // If we aren't looking in the current working directory we are looking
2121 // in the home directory. We will first see if there is an application
2122 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2123 // "-" and the name of the program. If this file doesn't exist, we fall
2124 // back to just the "~/.lldbinit" file. We also obey any requests to not
2125 // load the init files.
2126 llvm::SmallString<64> home_dir_path;
2127 llvm::sys::path::home_directory(home_dir_path);
2128 FileSpec profilePath(home_dir_path.c_str(), false);
2129 profilePath.AppendPathComponent(".lldbinit");
2130 std::string init_file_path = profilePath.GetPath();
2131
2132 if (m_skip_app_init_files == false) {
2133 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2134 const char *program_name = program_file_spec.GetFilename().AsCString();
2135
2136 if (program_name) {
2137 char program_init_file_name[PATH_MAX];
2138 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2139 "%s-%s", init_file_path.c_str(), program_name);
2140 init_file.SetFile(program_init_file_name, true);
2141 if (!init_file.Exists())
2142 init_file.Clear();
2143 }
2144 }
2145
2146 if (!init_file && !m_skip_lldbinit_files)
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002147 init_file.SetFile(init_file_path, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002148 }
2149
2150 // If the file exists, tell HandleCommand to 'source' it; this will do the
2151 // actual broadcasting
2152 // of the commands back to any appropriate listener (see
2153 // CommandObjectSource::Execute for more details).
2154
2155 if (init_file.Exists()) {
2156 const bool saved_batch = SetBatchCommandMode(true);
2157 CommandInterpreterRunOptions options;
2158 options.SetSilent(true);
2159 options.SetStopOnError(false);
2160 options.SetStopOnContinue(true);
2161
2162 HandleCommandsFromFile(init_file,
2163 nullptr, // Execution context
2164 options, result);
2165 SetBatchCommandMode(saved_batch);
2166 } else {
2167 // nothing to be done if the file doesn't exist
2168 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2169 }
2170}
2171
2172const char *CommandInterpreter::GetCommandPrefix() {
2173 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2174 return prefix == NULL ? "" : prefix;
2175}
2176
2177PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2178 PlatformSP platform_sp;
2179 if (prefer_target_platform) {
2180 ExecutionContext exe_ctx(GetExecutionContext());
2181 Target *target = exe_ctx.GetTargetPtr();
2182 if (target)
2183 platform_sp = target->GetPlatform();
2184 }
2185
2186 if (!platform_sp)
2187 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2188 return platform_sp;
2189}
2190
2191void CommandInterpreter::HandleCommands(const StringList &commands,
2192 ExecutionContext *override_context,
2193 CommandInterpreterRunOptions &options,
2194 CommandReturnObject &result) {
2195 size_t num_lines = commands.GetSize();
2196
2197 // If we are going to continue past a "continue" then we need to run the
2198 // commands synchronously.
2199 // Make sure you reset this value anywhere you return from the function.
2200
2201 bool old_async_execution = m_debugger.GetAsyncExecution();
2202
2203 // If we've been given an execution context, set it at the start, but don't
2204 // keep resetting it or we will
2205 // cause series of commands that change the context, then do an operation that
2206 // relies on that context to fail.
2207
2208 if (override_context != nullptr)
2209 UpdateExecutionContext(override_context);
2210
2211 if (!options.GetStopOnContinue()) {
2212 m_debugger.SetAsyncExecution(false);
2213 }
2214
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002215 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002216 const char *cmd = commands.GetStringAtIndex(idx);
2217 if (cmd[0] == '\0')
2218 continue;
2219
2220 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002221 // TODO: Add Stream support.
2222 result.AppendMessageWithFormat("%s %s\n",
2223 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002224 }
2225
2226 CommandReturnObject tmp_result;
2227 // If override_context is not NULL, pass no_context_switching = true for
2228 // HandleCommand() since we updated our context already.
2229
2230 // We might call into a regex or alias command, in which case the
2231 // add_to_history will get lost. This
2232 // m_command_source_depth dingus is the way we turn off adding to the
2233 // history in that case, so set it up here.
2234 if (!options.GetAddToHistory())
2235 m_command_source_depth++;
2236 bool success =
2237 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2238 nullptr, /* override_context */
2239 true, /* repeat_on_empty_command */
2240 override_context != nullptr /* no_context_switching */);
2241 if (!options.GetAddToHistory())
2242 m_command_source_depth--;
2243
2244 if (options.GetPrintResults()) {
2245 if (tmp_result.Succeeded())
Zachary Turner03c9f362016-11-14 23:23:31 +00002246 result.AppendMessage(tmp_result.GetOutputData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002247 }
2248
2249 if (!success || !tmp_result.Succeeded()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002250 llvm::StringRef error_msg = tmp_result.GetErrorData();
2251 if (error_msg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002252 error_msg = "<unknown error>.\n";
2253 if (options.GetStopOnError()) {
2254 result.AppendErrorWithFormat(
2255 "Aborting reading of commands after command #%" PRIu64
2256 ": '%s' failed with %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00002257 (uint64_t)idx, cmd, error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002258 result.SetStatus(eReturnStatusFailed);
2259 m_debugger.SetAsyncExecution(old_async_execution);
2260 return;
2261 } else if (options.GetPrintResults()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002262 result.AppendMessageWithFormat(
2263 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2264 error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002265 }
2266 }
2267
2268 if (result.GetImmediateOutputStream())
2269 result.GetImmediateOutputStream()->Flush();
2270
2271 if (result.GetImmediateErrorStream())
2272 result.GetImmediateErrorStream()->Flush();
2273
2274 // N.B. Can't depend on DidChangeProcessState, because the state coming into
2275 // the command execution
2276 // could be running (for instance in Breakpoint Commands.
2277 // So we check the return value to see if it is has running in it.
2278 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2279 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2280 if (options.GetStopOnContinue()) {
2281 // If we caused the target to proceed, and we're going to stop in that
2282 // case, set the
2283 // status in our real result before returning. This is an error if the
2284 // continue was not the
2285 // last command in the set of commands to be run.
2286 if (idx != num_lines - 1)
2287 result.AppendErrorWithFormat(
2288 "Aborting reading of commands after command #%" PRIu64
2289 ": '%s' continued the target.\n",
2290 (uint64_t)idx + 1, cmd);
2291 else
2292 result.AppendMessageWithFormat("Command #%" PRIu64
2293 " '%s' continued the target.\n",
2294 (uint64_t)idx + 1, cmd);
2295
2296 result.SetStatus(tmp_result.GetStatus());
2297 m_debugger.SetAsyncExecution(old_async_execution);
2298
2299 return;
2300 }
2301 }
2302
2303 // Also check for "stop on crash here:
2304 bool should_stop = false;
2305 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2306 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2307 if (target_sp) {
2308 ProcessSP process_sp(target_sp->GetProcessSP());
2309 if (process_sp) {
2310 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2311 StopReason reason = thread_sp->GetStopReason();
2312 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2313 reason == eStopReasonInstrumentation) {
2314 should_stop = true;
2315 break;
2316 }
2317 }
2318 }
2319 }
2320 if (should_stop) {
2321 if (idx != num_lines - 1)
2322 result.AppendErrorWithFormat(
2323 "Aborting reading of commands after command #%" PRIu64
2324 ": '%s' stopped with a signal or exception.\n",
2325 (uint64_t)idx + 1, cmd);
2326 else
2327 result.AppendMessageWithFormat(
2328 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2329 (uint64_t)idx + 1, cmd);
2330
2331 result.SetStatus(tmp_result.GetStatus());
2332 m_debugger.SetAsyncExecution(old_async_execution);
2333
2334 return;
2335 }
2336 }
2337 }
2338
2339 result.SetStatus(eReturnStatusSuccessFinishResult);
2340 m_debugger.SetAsyncExecution(old_async_execution);
2341
2342 return;
2343}
2344
2345// Make flags that we can pass into the IOHandler so our delegates can do the
2346// right thing
2347enum {
2348 eHandleCommandFlagStopOnContinue = (1u << 0),
2349 eHandleCommandFlagStopOnError = (1u << 1),
2350 eHandleCommandFlagEchoCommand = (1u << 2),
2351 eHandleCommandFlagPrintResult = (1u << 3),
2352 eHandleCommandFlagStopOnCrash = (1u << 4)
2353};
2354
2355void CommandInterpreter::HandleCommandsFromFile(
2356 FileSpec &cmd_file, ExecutionContext *context,
2357 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2358 if (cmd_file.Exists()) {
2359 StreamFileSP input_file_sp(new StreamFile());
2360
2361 std::string cmd_file_path = cmd_file.GetPath();
Zachary Turner97206d52017-05-12 04:51:55 +00002362 Status error = input_file_sp->GetFile().Open(cmd_file_path.c_str(),
2363 File::eOpenOptionRead);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002364
2365 if (error.Success()) {
2366 Debugger &debugger = GetDebugger();
2367
2368 uint32_t flags = 0;
2369
2370 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2371 if (m_command_source_flags.empty()) {
2372 // Stop on continue by default
2373 flags |= eHandleCommandFlagStopOnContinue;
2374 } else if (m_command_source_flags.back() &
2375 eHandleCommandFlagStopOnContinue) {
2376 flags |= eHandleCommandFlagStopOnContinue;
2377 }
2378 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2379 flags |= eHandleCommandFlagStopOnContinue;
2380 }
2381
2382 if (options.m_stop_on_error == eLazyBoolCalculate) {
2383 if (m_command_source_flags.empty()) {
2384 if (GetStopCmdSourceOnError())
2385 flags |= eHandleCommandFlagStopOnError;
2386 } else if (m_command_source_flags.back() &
2387 eHandleCommandFlagStopOnError) {
2388 flags |= eHandleCommandFlagStopOnError;
2389 }
2390 } else if (options.m_stop_on_error == eLazyBoolYes) {
2391 flags |= eHandleCommandFlagStopOnError;
2392 }
2393
2394 if (options.GetStopOnCrash()) {
2395 if (m_command_source_flags.empty()) {
2396 // Echo command by default
2397 flags |= eHandleCommandFlagStopOnCrash;
2398 } else if (m_command_source_flags.back() &
2399 eHandleCommandFlagStopOnCrash) {
2400 flags |= eHandleCommandFlagStopOnCrash;
2401 }
2402 }
2403
2404 if (options.m_echo_commands == eLazyBoolCalculate) {
2405 if (m_command_source_flags.empty()) {
2406 // Echo command by default
2407 flags |= eHandleCommandFlagEchoCommand;
2408 } else if (m_command_source_flags.back() &
2409 eHandleCommandFlagEchoCommand) {
2410 flags |= eHandleCommandFlagEchoCommand;
2411 }
2412 } else if (options.m_echo_commands == eLazyBoolYes) {
2413 flags |= eHandleCommandFlagEchoCommand;
2414 }
2415
2416 if (options.m_print_results == eLazyBoolCalculate) {
2417 if (m_command_source_flags.empty()) {
2418 // Print output by default
2419 flags |= eHandleCommandFlagPrintResult;
2420 } else if (m_command_source_flags.back() &
2421 eHandleCommandFlagPrintResult) {
2422 flags |= eHandleCommandFlagPrintResult;
2423 }
2424 } else if (options.m_print_results == eLazyBoolYes) {
2425 flags |= eHandleCommandFlagPrintResult;
2426 }
2427
2428 if (flags & eHandleCommandFlagPrintResult) {
2429 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2430 cmd_file_path.c_str());
2431 }
2432
2433 // Used for inheriting the right settings when "command source" might have
2434 // nested "command source" commands
2435 lldb::StreamFileSP empty_stream_sp;
2436 m_command_source_flags.push_back(flags);
2437 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2438 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2439 empty_stream_sp, // Pass in an empty stream so we inherit the top
2440 // input reader output stream
2441 empty_stream_sp, // Pass in an empty stream so we inherit the top
2442 // input reader error stream
2443 flags,
2444 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2445 // or written
Zachary Turner514d8cd2016-09-23 18:06:53 +00002446 debugger.GetPrompt(), llvm::StringRef(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00002447 false, // Not multi-line
2448 debugger.GetUseColor(), 0, *this));
2449 const bool old_async_execution = debugger.GetAsyncExecution();
2450
2451 // Set synchronous execution if we are not stopping on continue
2452 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2453 debugger.SetAsyncExecution(false);
2454
2455 m_command_source_depth++;
2456
2457 debugger.RunIOHandler(io_handler_sp);
2458 if (!m_command_source_flags.empty())
2459 m_command_source_flags.pop_back();
2460 m_command_source_depth--;
2461 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2462 debugger.SetAsyncExecution(old_async_execution);
2463 } else {
2464 result.AppendErrorWithFormat(
2465 "error: an error occurred read file '%s': %s\n",
2466 cmd_file_path.c_str(), error.AsCString());
2467 result.SetStatus(eReturnStatusFailed);
2468 }
2469
2470 } else {
2471 result.AppendErrorWithFormat(
2472 "Error reading commands from file %s - file not found.\n",
2473 cmd_file.GetFilename().AsCString("<Unknown>"));
2474 result.SetStatus(eReturnStatusFailed);
2475 return;
2476 }
2477}
2478
2479ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
Jim Ingham30bac792017-07-13 19:45:54 +00002480 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
Greg Clayton79040462016-12-09 01:21:14 +00002481 if (!m_script_interpreter_sp) {
2482 if (!can_create)
2483 return nullptr;
2484 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2485 m_script_interpreter_sp =
2486 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2487 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002488 return m_script_interpreter_sp.get();
2489}
2490
2491bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2492
2493void CommandInterpreter::SetSynchronous(bool value) {
2494 m_synchronous_execution = value;
2495}
2496
2497void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002498 llvm::StringRef prefix,
2499 llvm::StringRef help_text) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002500 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002501
Zachary Turner0ac5f982016-11-08 04:12:42 +00002502 size_t line_width_max = max_columns - prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002503 if (line_width_max < 16)
Zachary Turner0ac5f982016-11-08 04:12:42 +00002504 line_width_max = help_text.size() + prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002505
Zachary Turner0ac5f982016-11-08 04:12:42 +00002506 strm.IndentMore(prefix.size());
2507 bool prefixed_yet = false;
2508 while (!help_text.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002509 // Prefix the first line, indent subsequent lines to line up
Zachary Turner0ac5f982016-11-08 04:12:42 +00002510 if (!prefixed_yet) {
2511 strm << prefix;
2512 prefixed_yet = true;
2513 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002514 strm.Indent();
Zachary Turner0ac5f982016-11-08 04:12:42 +00002515
2516 // Never print more than the maximum on one line.
2517 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2518
2519 // Always break on an explicit newline.
2520 std::size_t first_newline = this_line.find_first_of("\n");
2521
2522 // Don't break on space/tab unless the text is too long to fit on one line.
2523 std::size_t last_space = llvm::StringRef::npos;
2524 if (this_line.size() != help_text.size())
2525 last_space = this_line.find_last_of(" \t");
2526
2527 // Break at whichever condition triggered first.
2528 this_line = this_line.substr(0, std::min(first_newline, last_space));
2529 strm.PutCString(this_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002530 strm.EOL();
2531
Zachary Turner0ac5f982016-11-08 04:12:42 +00002532 // Remove whitespace / newlines after breaking.
2533 help_text = help_text.drop_front(this_line.size()).ltrim();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002534 }
Zachary Turner0ac5f982016-11-08 04:12:42 +00002535 strm.IndentLess(prefix.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002536}
2537
2538void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002539 llvm::StringRef word_text,
2540 llvm::StringRef separator,
2541 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002542 size_t max_word_len) {
2543 StreamString prefix_stream;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002544 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2545 (int)separator.size(), separator.data());
Zachary Turnerc1564272016-11-16 21:15:24 +00002546 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2547}
2548
Zachary Turner0ac5f982016-11-08 04:12:42 +00002549void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2550 llvm::StringRef separator,
2551 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002552 uint32_t max_word_len) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00002553 int indent_size = max_word_len + separator.size() + 2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002554
2555 strm.IndentMore(indent_size);
2556
2557 StreamString text_strm;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002558 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2559 text_strm << separator << " " << help_text;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002560
2561 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2562
Zachary Turnerc1564272016-11-16 21:15:24 +00002563 llvm::StringRef text = text_strm.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002564
2565 uint32_t chars_left = max_columns;
2566
Davide Italianocf8a8292017-04-14 22:36:08 +00002567 auto nextWordLength = [](llvm::StringRef S) {
2568 size_t pos = S.find_first_of(' ');
2569 return pos == llvm::StringRef::npos ? S.size() : pos;
2570 };
2571
Zachary Turnerc1564272016-11-16 21:15:24 +00002572 while (!text.empty()) {
2573 if (text.front() == '\n' ||
Jim Inghama81bd7f2017-07-27 00:18:18 +00002574 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002575 strm.EOL();
2576 strm.Indent();
Zachary Turnerc1564272016-11-16 21:15:24 +00002577 chars_left = max_columns - indent_size;
2578 if (text.front() == '\n')
2579 text = text.drop_front();
2580 else
2581 text = text.ltrim(' ');
Kate Stoneb9c1b512016-09-06 20:57:50 +00002582 } else {
Zachary Turnerc1564272016-11-16 21:15:24 +00002583 strm.PutChar(text.front());
2584 --chars_left;
2585 text = text.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002586 }
2587 }
2588
2589 strm.EOL();
2590 strm.IndentLess(indent_size);
2591}
2592
2593void CommandInterpreter::FindCommandsForApropos(
Zachary Turner067d1db2016-11-16 21:45:04 +00002594 llvm::StringRef search_word, StringList &commands_found,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002595 StringList &commands_help, CommandObject::CommandMap &command_map) {
2596 CommandObject::CommandMap::const_iterator pos;
2597
2598 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
Zachary Turner067d1db2016-11-16 21:45:04 +00002599 llvm::StringRef command_name = pos->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002600 CommandObject *cmd_obj = pos->second.get();
2601
2602 const bool search_short_help = true;
2603 const bool search_long_help = false;
2604 const bool search_syntax = false;
2605 const bool search_options = false;
Zachary Turner067d1db2016-11-16 21:45:04 +00002606 if (command_name.contains_lower(search_word) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002607 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2608 search_long_help, search_syntax,
2609 search_options)) {
2610 commands_found.AppendString(cmd_obj->GetCommandName());
2611 commands_help.AppendString(cmd_obj->GetHelp());
2612 }
2613
2614 if (cmd_obj->IsMultiwordObject()) {
2615 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2616 FindCommandsForApropos(search_word, commands_found, commands_help,
2617 cmd_multiword->GetSubcommandDictionary());
2618 }
2619 }
2620}
2621
Zachary Turner067d1db2016-11-16 21:45:04 +00002622void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002623 StringList &commands_found,
2624 StringList &commands_help,
2625 bool search_builtin_commands,
2626 bool search_user_commands,
2627 bool search_alias_commands) {
2628 CommandObject::CommandMap::const_iterator pos;
2629
2630 if (search_builtin_commands)
2631 FindCommandsForApropos(search_word, commands_found, commands_help,
2632 m_command_dict);
2633
2634 if (search_user_commands)
2635 FindCommandsForApropos(search_word, commands_found, commands_help,
2636 m_user_dict);
2637
2638 if (search_alias_commands)
2639 FindCommandsForApropos(search_word, commands_found, commands_help,
2640 m_alias_dict);
2641}
2642
2643void CommandInterpreter::UpdateExecutionContext(
2644 ExecutionContext *override_context) {
2645 if (override_context != nullptr) {
2646 m_exe_ctx_ref = *override_context;
2647 } else {
2648 const bool adopt_selected = true;
2649 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2650 adopt_selected);
2651 }
2652}
2653
2654size_t CommandInterpreter::GetProcessOutput() {
2655 // The process has stuff waiting for stderr; get it and write it out to the
2656 // appropriate place.
2657 char stdio_buffer[1024];
2658 size_t len;
2659 size_t total_bytes = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002660 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002661 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2662 if (target_sp) {
2663 ProcessSP process_sp(target_sp->GetProcessSP());
2664 if (process_sp) {
2665 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2666 error)) > 0) {
2667 size_t bytes_written = len;
2668 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2669 total_bytes += len;
2670 }
2671 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2672 error)) > 0) {
2673 size_t bytes_written = len;
2674 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2675 total_bytes += len;
2676 }
2677 }
2678 }
2679 return total_bytes;
2680}
2681
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002682void CommandInterpreter::StartHandlingCommand() {
2683 auto idle_state = CommandHandlingState::eIdle;
2684 if (m_command_state.compare_exchange_strong(
2685 idle_state, CommandHandlingState::eInProgress))
2686 lldbassert(m_iohandler_nesting_level == 0);
2687 else
2688 lldbassert(m_iohandler_nesting_level > 0);
2689 ++m_iohandler_nesting_level;
2690}
2691
2692void CommandInterpreter::FinishHandlingCommand() {
2693 lldbassert(m_iohandler_nesting_level > 0);
2694 if (--m_iohandler_nesting_level == 0) {
2695 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2696 lldbassert(prev_state != CommandHandlingState::eIdle);
2697 }
2698}
2699
2700bool CommandInterpreter::InterruptCommand() {
2701 auto in_progress = CommandHandlingState::eInProgress;
2702 return m_command_state.compare_exchange_strong(
2703 in_progress, CommandHandlingState::eInterrupted);
2704}
2705
2706bool CommandInterpreter::WasInterrupted() const {
2707 bool was_interrupted =
2708 (m_command_state == CommandHandlingState::eInterrupted);
2709 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2710 return was_interrupted;
2711}
2712
2713void CommandInterpreter::PrintCommandOutput(Stream &stream,
2714 llvm::StringRef str) {
2715 // Split the output into lines and poll for interrupt requests
2716 const char *data = str.data();
2717 size_t size = str.size();
2718 while (size > 0 && !WasInterrupted()) {
2719 size_t chunk_size = 0;
2720 for (; chunk_size < size; ++chunk_size) {
2721 lldbassert(data[chunk_size] != '\0');
2722 if (data[chunk_size] == '\n') {
2723 ++chunk_size;
2724 break;
2725 }
2726 }
2727 chunk_size = stream.Write(data, chunk_size);
2728 lldbassert(size >= chunk_size);
2729 data += chunk_size;
2730 size -= chunk_size;
2731 }
2732 if (size > 0) {
2733 stream.Printf("\n... Interrupted.\n");
2734 }
2735}
2736
Kate Stoneb9c1b512016-09-06 20:57:50 +00002737void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2738 std::string &line) {
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002739 // If we were interrupted, bail out...
2740 if (WasInterrupted())
2741 return;
2742
Kate Stoneb9c1b512016-09-06 20:57:50 +00002743 const bool is_interactive = io_handler.GetIsInteractive();
2744 if (is_interactive == false) {
2745 // When we are not interactive, don't execute blank lines. This will happen
2746 // sourcing a commands file. We don't want blank lines to repeat the
2747 // previous
2748 // command and cause any errors to occur (like redefining an alias, get an
2749 // error
2750 // and stop parsing the commands file).
2751 if (line.empty())
2752 return;
2753
2754 // When using a non-interactive file handle (like when sourcing commands
2755 // from a file)
2756 // we need to echo the command out so we don't just see the command output
2757 // and no
2758 // command...
2759 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2760 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2761 line.c_str());
2762 }
2763
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002764 StartHandlingCommand();
2765
Kate Stoneb9c1b512016-09-06 20:57:50 +00002766 lldb_private::CommandReturnObject result;
2767 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2768
2769 // Now emit the command output text from the command we just executed
2770 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2771 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2772 GetProcessOutput();
2773
2774 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002775 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002776 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002777 }
2778
2779 // Now emit the command error text from the command we just executed
2780 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002781 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002782 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002783 }
2784 }
2785
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002786 FinishHandlingCommand();
2787
Kate Stoneb9c1b512016-09-06 20:57:50 +00002788 switch (result.GetStatus()) {
2789 case eReturnStatusInvalid:
2790 case eReturnStatusSuccessFinishNoResult:
2791 case eReturnStatusSuccessFinishResult:
2792 case eReturnStatusStarted:
2793 break;
2794
2795 case eReturnStatusSuccessContinuingNoResult:
2796 case eReturnStatusSuccessContinuingResult:
2797 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2798 io_handler.SetIsDone(true);
2799 break;
2800
2801 case eReturnStatusFailed:
2802 m_num_errors++;
2803 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2804 io_handler.SetIsDone(true);
2805 break;
2806
2807 case eReturnStatusQuit:
2808 m_quit_requested = true;
2809 io_handler.SetIsDone(true);
2810 break;
2811 }
2812
2813 // Finally, if we're going to stop on crash, check that here:
2814 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2815 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2816 bool should_stop = false;
2817 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2818 if (target_sp) {
2819 ProcessSP process_sp(target_sp->GetProcessSP());
2820 if (process_sp) {
2821 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2822 StopReason reason = thread_sp->GetStopReason();
2823 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2824 reason == eStopReasonInstrumentation) &&
2825 !result.GetAbnormalStopWasExpected()) {
2826 should_stop = true;
2827 break;
2828 }
2829 }
2830 }
2831 }
2832 if (should_stop) {
2833 io_handler.SetIsDone(true);
2834 m_stopped_for_crash = true;
2835 }
2836 }
2837}
2838
2839bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2840 ExecutionContext exe_ctx(GetExecutionContext());
2841 Process *process = exe_ctx.GetProcessPtr();
2842
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002843 if (InterruptCommand())
2844 return true;
2845
Kate Stoneb9c1b512016-09-06 20:57:50 +00002846 if (process) {
2847 StateType state = process->GetState();
2848 if (StateIsRunningState(state)) {
2849 process->Halt();
2850 return true; // Don't do any updating when we are running
2851 }
2852 }
2853
2854 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2855 if (script_interpreter) {
2856 if (script_interpreter->Interrupt())
2857 return true;
2858 }
2859 return false;
2860}
2861
2862void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2863 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2864 void *baton) {
2865 Debugger &debugger = GetDebugger();
2866 IOHandlerSP io_handler_sp(
2867 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2868 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002869 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2870 llvm::StringRef(), // Continuation prompt
2871 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002872 debugger.GetUseColor(),
2873 0, // Don't show line numbers
2874 delegate)); // IOHandlerDelegate
2875
2876 if (io_handler_sp) {
2877 io_handler_sp->SetUserData(baton);
2878 if (asynchronously)
2879 debugger.PushIOHandler(io_handler_sp);
2880 else
2881 debugger.RunIOHandler(io_handler_sp);
2882 }
2883}
2884
2885void CommandInterpreter::GetPythonCommandsFromIOHandler(
2886 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2887 void *baton) {
2888 Debugger &debugger = GetDebugger();
2889 IOHandlerSP io_handler_sp(
2890 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2891 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002892 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2893 llvm::StringRef(), // Continuation prompt
2894 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002895 debugger.GetUseColor(),
2896 0, // Don't show line numbers
2897 delegate)); // IOHandlerDelegate
2898
2899 if (io_handler_sp) {
2900 io_handler_sp->SetUserData(baton);
2901 if (asynchronously)
2902 debugger.PushIOHandler(io_handler_sp);
2903 else
2904 debugger.RunIOHandler(io_handler_sp);
2905 }
2906}
2907
2908bool CommandInterpreter::IsActive() {
2909 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2910}
2911
2912lldb::IOHandlerSP
2913CommandInterpreter::GetIOHandler(bool force_create,
2914 CommandInterpreterRunOptions *options) {
2915 // Always re-create the IOHandlerEditline in case the input
2916 // changed. The old instance might have had a non-interactive
2917 // input and now it does or vice versa.
2918 if (force_create || !m_command_io_handler_sp) {
2919 // Always re-create the IOHandlerEditline in case the input
2920 // changed. The old instance might have had a non-interactive
2921 // input and now it does or vice versa.
2922 uint32_t flags = 0;
2923
2924 if (options) {
2925 if (options->m_stop_on_continue == eLazyBoolYes)
2926 flags |= eHandleCommandFlagStopOnContinue;
2927 if (options->m_stop_on_error == eLazyBoolYes)
2928 flags |= eHandleCommandFlagStopOnError;
2929 if (options->m_stop_on_crash == eLazyBoolYes)
2930 flags |= eHandleCommandFlagStopOnCrash;
2931 if (options->m_echo_commands != eLazyBoolNo)
2932 flags |= eHandleCommandFlagEchoCommand;
2933 if (options->m_print_results != eLazyBoolNo)
2934 flags |= eHandleCommandFlagPrintResult;
2935 } else {
2936 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2937 }
2938
2939 m_command_io_handler_sp.reset(new IOHandlerEditline(
2940 m_debugger, IOHandler::Type::CommandInterpreter,
2941 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2942 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002943 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002944 false, // Don't enable multiple line input, just single line commands
2945 m_debugger.GetUseColor(),
2946 0, // Don't show line numbers
2947 *this));
2948 }
2949 return m_command_io_handler_sp;
2950}
2951
2952void CommandInterpreter::RunCommandInterpreter(
2953 bool auto_handle_events, bool spawn_thread,
2954 CommandInterpreterRunOptions &options) {
2955 // Always re-create the command interpreter when we run it in case
2956 // any file handles have changed.
2957 bool force_create = true;
2958 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2959 m_stopped_for_crash = false;
2960
2961 if (auto_handle_events)
2962 m_debugger.StartEventHandlerThread();
2963
2964 if (spawn_thread) {
2965 m_debugger.StartIOHandlerThread();
2966 } else {
2967 m_debugger.ExecuteIOHandlers();
2968
2969 if (auto_handle_events)
2970 m_debugger.StopEventHandlerThread();
2971 }
2972}
2973
2974CommandObject *
2975CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2976 CommandReturnObject &result) {
2977 std::string scratch_command(command_line); // working copy so we don't modify
2978 // command_line unless we succeed
2979 CommandObject *cmd_obj = nullptr;
2980 StreamString revised_command_line;
2981 bool wants_raw_input = false;
2982 size_t actual_cmd_name_len = 0;
2983 std::string next_word;
2984 StringList matches;
2985 bool done = false;
2986 while (!done) {
2987 char quote_char = '\0';
2988 std::string suffix;
2989 ExtractCommand(scratch_command, next_word, suffix, quote_char);
2990 if (cmd_obj == nullptr) {
2991 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002992 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00002993 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002994 bool is_real_command =
2995 (is_alias == false) ||
2996 (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
2997 if (!is_real_command) {
2998 matches.Clear();
2999 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003000 cmd_obj =
3001 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003002 revised_command_line.Printf("%s", alias_result.c_str());
3003 if (cmd_obj) {
3004 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00003005 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003006 }
3007 } else {
3008 if (!cmd_obj)
Zachary Turnera4496982016-10-05 21:14:38 +00003009 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003010 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00003011 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
3012 actual_cmd_name_len += cmd_name.size();
3013 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003014 wants_raw_input = cmd_obj->WantsRawCommandString();
3015 } else {
3016 revised_command_line.Printf("%s", next_word.c_str());
3017 }
3018 }
3019 } else {
3020 if (cmd_obj->IsMultiwordObject()) {
3021 CommandObject *sub_cmd_obj =
3022 cmd_obj->GetSubcommandObject(next_word.c_str());
3023 if (sub_cmd_obj) {
3024 // The subcommand's name includes the parent command's name,
3025 // so restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00003026 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3027 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003028 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00003029 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003030 cmd_obj = sub_cmd_obj;
3031 wants_raw_input = cmd_obj->WantsRawCommandString();
3032 } else {
3033 if (quote_char)
3034 revised_command_line.Printf(" %c%s%s%c", quote_char,
3035 next_word.c_str(), suffix.c_str(),
3036 quote_char);
3037 else
3038 revised_command_line.Printf(" %s%s", next_word.c_str(),
3039 suffix.c_str());
3040 done = true;
3041 }
3042 } else {
3043 if (quote_char)
3044 revised_command_line.Printf(" %c%s%s%c", quote_char,
3045 next_word.c_str(), suffix.c_str(),
3046 quote_char);
3047 else
3048 revised_command_line.Printf(" %s%s", next_word.c_str(),
3049 suffix.c_str());
3050 done = true;
3051 }
3052 }
3053
3054 if (cmd_obj == nullptr) {
3055 const size_t num_matches = matches.GetSize();
3056 if (matches.GetSize() > 1) {
3057 StreamString error_msg;
3058 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3059 next_word.c_str());
3060
3061 for (uint32_t i = 0; i < num_matches; ++i) {
3062 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3063 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003064 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003065 } else {
3066 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003067 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003068 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3069 next_word.c_str());
3070 }
3071 result.SetStatus(eReturnStatusFailed);
3072 return nullptr;
3073 }
3074
3075 if (cmd_obj->IsMultiwordObject()) {
3076 if (!suffix.empty()) {
3077 result.AppendErrorWithFormat(
3078 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3079 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003080 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003081 next_word.empty() ? "" : next_word.c_str(),
3082 next_word.empty() ? " -- " : " ", suffix.c_str());
3083 result.SetStatus(eReturnStatusFailed);
3084 return nullptr;
3085 }
3086 } else {
3087 // If we found a normal command, we are done
3088 done = true;
3089 if (!suffix.empty()) {
3090 switch (suffix[0]) {
3091 case '/':
3092 // GDB format suffixes
3093 {
3094 Options *command_options = cmd_obj->GetOptions();
3095 if (command_options &&
3096 command_options->SupportsLongOption("gdb-format")) {
3097 std::string gdb_format_option("--gdb-format=");
3098 gdb_format_option += (suffix.c_str() + 1);
3099
Zachary Turnerc1564272016-11-16 21:15:24 +00003100 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003101 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3102 if (arg_terminator_idx != std::string::npos) {
3103 // Insert the gdb format option before the "--" that terminates
3104 // options
3105 gdb_format_option.append(1, ' ');
3106 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003107 revised_command_line.Clear();
3108 revised_command_line.PutCString(cmd);
3109 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003110 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3111
3112 if (wants_raw_input &&
3113 FindArgumentTerminator(cmd) == std::string::npos)
3114 revised_command_line.PutCString(" --");
3115 } else {
3116 result.AppendErrorWithFormat(
3117 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003118 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003119 result.SetStatus(eReturnStatusFailed);
3120 return nullptr;
3121 }
3122 }
3123 break;
3124
3125 default:
3126 result.AppendErrorWithFormat(
3127 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3128 result.SetStatus(eReturnStatusFailed);
3129 return nullptr;
3130 }
3131 }
3132 }
3133 if (scratch_command.empty())
3134 done = true;
3135 }
3136
3137 if (!scratch_command.empty())
3138 revised_command_line.Printf(" %s", scratch_command.c_str());
3139
3140 if (cmd_obj != NULL)
Zachary Turnerc1564272016-11-16 21:15:24 +00003141 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003142
3143 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003144}