blob: ec812d61ea29e2eeb3dfd9e1e59573470dbb52d1 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Kate Stoneb9c1b512016-09-06 20:57:50 +000010#include <stdlib.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000011#include <string>
Caroline Tice4ab31c92010-10-12 21:57:09 +000012#include <vector>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013
Greg Clayton4a33d312011-06-23 17:59:56 +000014#include "CommandObjectScript.h"
Peter Collingbourne08405b62011-06-23 20:37:26 +000015#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000016
James Y Knight2ad48212018-05-22 22:53:50 +000017#include "Commands/CommandObjectApropos.h"
18#include "Commands/CommandObjectBreakpoint.h"
19#include "Commands/CommandObjectBugreport.h"
20#include "Commands/CommandObjectCommands.h"
21#include "Commands/CommandObjectDisassemble.h"
22#include "Commands/CommandObjectExpression.h"
23#include "Commands/CommandObjectFrame.h"
24#include "Commands/CommandObjectGUI.h"
25#include "Commands/CommandObjectHelp.h"
26#include "Commands/CommandObjectLanguage.h"
27#include "Commands/CommandObjectLog.h"
28#include "Commands/CommandObjectMemory.h"
29#include "Commands/CommandObjectPlatform.h"
30#include "Commands/CommandObjectPlugin.h"
31#include "Commands/CommandObjectProcess.h"
32#include "Commands/CommandObjectQuit.h"
33#include "Commands/CommandObjectRegister.h"
34#include "Commands/CommandObjectSettings.h"
35#include "Commands/CommandObjectSource.h"
36#include "Commands/CommandObjectStats.h"
37#include "Commands/CommandObjectTarget.h"
38#include "Commands/CommandObjectThread.h"
39#include "Commands/CommandObjectType.h"
40#include "Commands/CommandObjectVersion.h"
41#include "Commands/CommandObjectWatchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043#include "lldb/Core/Debugger.h"
Zachary Turner2c1f46d2015-07-30 20:28:07 +000044#include "lldb/Core/PluginManager.h"
Greg Clayton44d93782014-01-27 23:43:24 +000045#include "lldb/Core/StreamFile.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000046#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000047#include "lldb/Utility/State.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000048#include "lldb/Utility/Stream.h"
Pavel Labath38d06322017-06-29 14:32:17 +000049#include "lldb/Utility/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000050
Todd Fialacacde7d2014-09-27 16:54:22 +000051#ifndef LLDB_DISABLE_LIBEDIT
Greg Clayton44d93782014-01-27 23:43:24 +000052#include "lldb/Host/Editline.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000053#endif
Greg Clayton7fb56d02011-02-01 01:31:41 +000054#include "lldb/Host/Host.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000055#include "lldb/Host/HostInfo.h"
Enrico Granatab5887262012-10-29 21:18:03 +000056
Greg Clayton7d2ef162013-03-29 17:03:23 +000057#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000058#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000059#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000060#include "lldb/Interpreter/OptionValueProperties.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000061#include "lldb/Interpreter/Options.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000062#include "lldb/Interpreter/Property.h"
Pavel Labath145d95c2018-04-17 18:53:35 +000063#include "lldb/Utility/Args.h"
Enrico Granatab5887262012-10-29 21:18:03 +000064
Chris Lattner30fdc8d2010-06-08 16:52:24 +000065#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066#include "lldb/Target/TargetList.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000067#include "lldb/Target/Thread.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000068
Saleem Abdulrasool28606952014-06-27 05:17:41 +000069#include "llvm/ADT/STLExtras.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000070#include "llvm/ADT/SmallString.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000071#include "llvm/Support/Path.h"
Sean Callanan237c3ed2016-12-14 21:31:31 +000072#include "llvm/Support/PrettyStackTrace.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000073
Chris Lattner30fdc8d2010-06-08 16:52:24 +000074using namespace lldb;
75using namespace lldb_private;
76
Adrian McCarthy2304b6f2015-04-23 20:00:25 +000077static const char *k_white_space = " \t\v";
Greg Clayton754a9362012-08-23 00:22:02 +000078
Stefan Granitzc678ed72018-10-05 16:49:47 +000079static constexpr bool NoGlobalSetting = true;
80static constexpr uintptr_t DefaultValueTrue = true;
81static constexpr uintptr_t DefaultValueFalse = false;
82static constexpr const char *NoCStrDefault = nullptr;
83
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000084static constexpr PropertyDefinition g_properties[] = {
Stefan Granitzc678ed72018-10-05 16:49:47 +000085 {"expand-regex-aliases", OptionValue::eTypeBoolean, NoGlobalSetting,
86 DefaultValueFalse, NoCStrDefault, {},
87 "If true, regular expression alias commands will show the "
88 "expanded command that will be executed. This can be used to "
89 "debug new regular expression alias commands."},
90 {"prompt-on-quit", OptionValue::eTypeBoolean, NoGlobalSetting,
91 DefaultValueTrue, NoCStrDefault, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +000092 "If true, LLDB will prompt you before quitting if there are any live "
93 "processes being debugged. If false, LLDB will quit without asking in any "
94 "case."},
Stefan Granitzc678ed72018-10-05 16:49:47 +000095 {"stop-command-source-on-error", OptionValue::eTypeBoolean, NoGlobalSetting,
96 DefaultValueTrue, NoCStrDefault, {},
97 "If true, LLDB will stop running a 'command source' "
98 "script upon encountering an error."},
99 {"space-repl-prompts", OptionValue::eTypeBoolean, NoGlobalSetting,
100 DefaultValueFalse, NoCStrDefault, {},
101 "If true, blank lines will be printed between between REPL submissions."},
102 {"echo-commands", OptionValue::eTypeBoolean, NoGlobalSetting,
103 DefaultValueTrue, NoCStrDefault, {},
104 "If true, commands will be echoed before they are evaluated."},
105 {"echo-comment-commands", OptionValue::eTypeBoolean, NoGlobalSetting,
106 DefaultValueTrue, NoCStrDefault, {},
107 "If true, commands will be echoed even if they are pure comment lines."}};
Kate Stoneb9c1b512016-09-06 20:57:50 +0000108
109enum {
110 ePropertyExpandRegexAliases = 0,
111 ePropertyPromptOnQuit = 1,
112 ePropertyStopCmdSourceOnError = 2,
Stefan Granitzc678ed72018-10-05 16:49:47 +0000113 eSpaceReplPrompts = 3,
114 eEchoCommands = 4,
115 eEchoCommentCommands = 5
Greg Clayton754a9362012-08-23 00:22:02 +0000116};
117
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118ConstString &CommandInterpreter::GetStaticBroadcasterClass() {
119 static ConstString class_name("lldb.commandInterpreter");
120 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000121}
122
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123CommandInterpreter::CommandInterpreter(Debugger &debugger,
124 ScriptLanguage script_language,
125 bool synchronous_execution)
126 : Broadcaster(debugger.GetBroadcasterManager(),
127 CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
128 Properties(OptionValuePropertiesSP(
129 new OptionValueProperties(ConstString("interpreter")))),
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000130 IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 m_debugger(debugger), m_synchronous_execution(synchronous_execution),
132 m_skip_lldbinit_files(false), m_skip_app_init_files(false),
133 m_script_interpreter_sp(), m_command_io_handler_sp(), m_comment_char('#'),
134 m_batch_command_mode(false), m_truncation_warning(eNoTruncation),
135 m_command_source_depth(0), m_num_errors(0), m_quit_requested(false),
136 m_stopped_for_crash(false) {
137 debugger.SetScriptLanguage(script_language);
138 SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit");
139 SetEventName(eBroadcastBitResetPrompt, "reset-prompt");
140 SetEventName(eBroadcastBitQuitCommandReceived, "quit");
141 CheckInWithManager();
142 m_collection_sp->Initialize(g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000143}
144
Kate Stoneb9c1b512016-09-06 20:57:50 +0000145bool CommandInterpreter::GetExpandRegexAliases() const {
146 const uint32_t idx = ePropertyExpandRegexAliases;
147 return m_collection_sp->GetPropertyAtIndexAsBoolean(
148 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000149}
150
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151bool CommandInterpreter::GetPromptOnQuit() const {
152 const uint32_t idx = ePropertyPromptOnQuit;
153 return m_collection_sp->GetPropertyAtIndexAsBoolean(
154 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000155}
Greg Clayton754a9362012-08-23 00:22:02 +0000156
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157void CommandInterpreter::SetPromptOnQuit(bool b) {
158 const uint32_t idx = ePropertyPromptOnQuit;
159 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ilia Kacf28be2015-03-23 22:45:13 +0000160}
161
Stefan Granitzc678ed72018-10-05 16:49:47 +0000162bool CommandInterpreter::GetEchoCommands() const {
163 const uint32_t idx = eEchoCommands;
164 return m_collection_sp->GetPropertyAtIndexAsBoolean(
165 nullptr, idx, g_properties[idx].default_uint_value != 0);
166}
167
168void CommandInterpreter::SetEchoCommands(bool b) {
169 const uint32_t idx = eEchoCommands;
170 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
171}
172
173bool CommandInterpreter::GetEchoCommentCommands() const {
174 const uint32_t idx = eEchoCommentCommands;
175 return m_collection_sp->GetPropertyAtIndexAsBoolean(
176 nullptr, idx, g_properties[idx].default_uint_value != 0);
177}
178
179void CommandInterpreter::SetEchoCommentCommands(bool b) {
180 const uint32_t idx = eEchoCommentCommands;
181 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
182}
183
Raphael Isemannc094d232018-07-11 17:18:01 +0000184void CommandInterpreter::AllowExitCodeOnQuit(bool allow) {
185 m_allow_exit_code = allow;
186 if (!allow)
187 m_quit_exit_code.reset();
188}
189
190bool CommandInterpreter::SetQuitExitCode(int exit_code) {
191 if (!m_allow_exit_code)
192 return false;
193 m_quit_exit_code = exit_code;
194 return true;
195}
196
197int CommandInterpreter::GetQuitExitCode(bool &exited) const {
198 exited = m_quit_exit_code.hasValue();
199 if (exited)
200 return *m_quit_exit_code;
201 return 0;
202}
203
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204void CommandInterpreter::ResolveCommand(const char *command_line,
205 CommandReturnObject &result) {
206 std::string command = command_line;
207 if (ResolveCommandImpl(command, result) != nullptr) {
208 result.AppendMessageWithFormat("%s", command.c_str());
209 result.SetStatus(eReturnStatusSuccessFinishResult);
210 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000211}
212
Kate Stoneb9c1b512016-09-06 20:57:50 +0000213bool CommandInterpreter::GetStopCmdSourceOnError() const {
214 const uint32_t idx = ePropertyStopCmdSourceOnError;
215 return m_collection_sp->GetPropertyAtIndexAsBoolean(
216 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000217}
218
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219bool CommandInterpreter::GetSpaceReplPrompts() const {
220 const uint32_t idx = eSpaceReplPrompts;
221 return m_collection_sp->GetPropertyAtIndexAsBoolean(
222 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callanan66810412015-10-19 23:11:07 +0000223}
224
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225void CommandInterpreter::Initialize() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000226 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
227 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000228
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229 CommandReturnObject result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000230
Kate Stoneb9c1b512016-09-06 20:57:50 +0000231 LoadCommandDictionary();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000232
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233 // An alias arguments vector to reuse - reset it before use...
234 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
235
236 // Set up some initial aliases.
237 CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
238 if (cmd_obj_sp) {
239 AddAlias("q", cmd_obj_sp);
240 AddAlias("exit", cmd_obj_sp);
241 }
242
243 cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
244 if (cmd_obj_sp)
245 AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
246
247 cmd_obj_sp = GetCommandSPExact("process detach", false);
248 if (cmd_obj_sp) {
249 AddAlias("detach", cmd_obj_sp);
250 }
251
252 cmd_obj_sp = GetCommandSPExact("process continue", false);
253 if (cmd_obj_sp) {
254 AddAlias("c", cmd_obj_sp);
255 AddAlias("continue", cmd_obj_sp);
256 }
257
258 cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
259 if (cmd_obj_sp)
260 AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
261
262 cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
263 if (cmd_obj_sp)
264 AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
265
266 cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
267 if (cmd_obj_sp) {
268 AddAlias("stepi", cmd_obj_sp);
269 AddAlias("si", cmd_obj_sp);
270 }
271
272 cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
273 if (cmd_obj_sp) {
274 AddAlias("nexti", cmd_obj_sp);
275 AddAlias("ni", cmd_obj_sp);
276 }
277
278 cmd_obj_sp = GetCommandSPExact("thread step-in", false);
279 if (cmd_obj_sp) {
280 AddAlias("s", cmd_obj_sp);
281 AddAlias("step", cmd_obj_sp);
282 CommandAlias *sif_alias = AddAlias(
283 "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
284 if (sif_alias) {
285 sif_alias->SetHelp("Step through the current block, stopping if you step "
286 "directly into a function whose name matches the "
287 "TargetFunctionName.");
288 sif_alias->SetSyntax("sif <TargetFunctionName>");
Caroline Ticeca90c472011-05-06 21:37:15 +0000289 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000290 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000291
Kate Stoneb9c1b512016-09-06 20:57:50 +0000292 cmd_obj_sp = GetCommandSPExact("thread step-over", false);
293 if (cmd_obj_sp) {
294 AddAlias("n", cmd_obj_sp);
295 AddAlias("next", cmd_obj_sp);
296 }
297
298 cmd_obj_sp = GetCommandSPExact("thread step-out", false);
299 if (cmd_obj_sp) {
300 AddAlias("finish", cmd_obj_sp);
301 }
302
303 cmd_obj_sp = GetCommandSPExact("frame select", false);
304 if (cmd_obj_sp) {
305 AddAlias("f", cmd_obj_sp);
306 }
307
308 cmd_obj_sp = GetCommandSPExact("thread select", false);
309 if (cmd_obj_sp) {
310 AddAlias("t", cmd_obj_sp);
311 }
312
313 cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
314 if (cmd_obj_sp) {
315 AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
316 AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
317 }
318
319 cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
320 if (cmd_obj_sp) {
321 AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
322 AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
323 }
324
325 cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
326 if (cmd_obj_sp)
327 AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
328
329 cmd_obj_sp = GetCommandSPExact("memory read", false);
330 if (cmd_obj_sp)
331 AddAlias("x", cmd_obj_sp);
332
333 cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
334 if (cmd_obj_sp)
335 AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
336
337 cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
338 if (cmd_obj_sp)
339 AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
340
341 cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
342 if (cmd_obj_sp)
343 AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
344
345 cmd_obj_sp = GetCommandSPExact("disassemble", false);
346 if (cmd_obj_sp)
347 AddAlias("dis", cmd_obj_sp);
348
349 cmd_obj_sp = GetCommandSPExact("disassemble", false);
350 if (cmd_obj_sp)
351 AddAlias("di", cmd_obj_sp);
352
353 cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
354 if (cmd_obj_sp)
355 AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
356
357 cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
358 if (cmd_obj_sp)
359 AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
360
361 cmd_obj_sp = GetCommandSPExact("target create", false);
362 if (cmd_obj_sp)
363 AddAlias("file", cmd_obj_sp);
364
365 cmd_obj_sp = GetCommandSPExact("target modules", false);
366 if (cmd_obj_sp)
367 AddAlias("image", cmd_obj_sp);
368
369 alias_arguments_vector_sp.reset(new OptionArgVector);
370
371 cmd_obj_sp = GetCommandSPExact("expression", false);
372 if (cmd_obj_sp) {
373 AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
374 AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
375 AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
376 if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
377 po->SetHelp("Evaluate an expression on the current thread. Displays any "
378 "returned value with formatting "
379 "controlled by the type's author.");
380 po->SetHelpLong("");
Johnny Chen6d675242012-08-24 18:15:45 +0000381 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382 AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
383 AddAlias("poarray", cmd_obj_sp,
384 "--object-description --element-count %1 --")
385 ->SetHelpLong("");
386 }
Johnny Chen6d675242012-08-24 18:15:45 +0000387
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 cmd_obj_sp = GetCommandSPExact("process kill", false);
389 if (cmd_obj_sp) {
390 AddAlias("kill", cmd_obj_sp);
391 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000392
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 cmd_obj_sp = GetCommandSPExact("process launch", false);
394 if (cmd_obj_sp) {
Chaoren Lin6fc5c7f2016-02-26 03:36:27 +0000395 alias_arguments_vector_sp.reset(new OptionArgVector);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
397 AddAlias("r", cmd_obj_sp, "--");
398 AddAlias("run", cmd_obj_sp, "--");
Jason Molenda85da3122012-07-06 02:46:23 +0000399#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400#if defined(__APPLE__)
401 std::string shell_option;
402 shell_option.append("--shell-expand-args");
403 shell_option.append(" true");
404 shell_option.append(" --");
405 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
406 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
407#else
408 StreamString defaultshell;
409 defaultshell.Printf("--shell=%s --",
410 HostInfo::GetDefaultShell().GetPath().c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +0000411 AddAlias("r", cmd_obj_sp, defaultshell.GetString());
412 AddAlias("run", cmd_obj_sp, defaultshell.GetString());
Jason Molenda85da3122012-07-06 02:46:23 +0000413#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414#endif
415 }
416
417 cmd_obj_sp = GetCommandSPExact("target symbols add", false);
418 if (cmd_obj_sp) {
419 AddAlias("add-dsym", cmd_obj_sp);
420 }
421
422 cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
423 if (cmd_obj_sp) {
424 AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
425 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000426}
427
Kate Stoneb9c1b512016-09-06 20:57:50 +0000428void CommandInterpreter::Clear() {
429 m_command_io_handler_sp.reset();
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000430
Kate Stoneb9c1b512016-09-06 20:57:50 +0000431 if (m_script_interpreter_sp)
432 m_script_interpreter_sp->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000433}
434
Kate Stoneb9c1b512016-09-06 20:57:50 +0000435const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
436 // This function has not yet been implemented.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000437
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438 // Look for any embedded script command
439 // If found,
440 // get interpreter object from the command dictionary,
441 // call execute_one_command on it,
442 // get the results as a string,
443 // substitute that string for current stuff.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000444
Kate Stoneb9c1b512016-09-06 20:57:50 +0000445 return arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000446}
447
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448void CommandInterpreter::LoadCommandDictionary() {
Pavel Labathf9d16472017-05-15 13:02:37 +0000449 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
450 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000451
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000453
Kate Stoneb9c1b512016-09-06 20:57:50 +0000454 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
455 m_command_dict["breakpoint"] =
456 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
457 m_command_dict["bugreport"] =
458 CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
459 m_command_dict["command"] =
460 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
461 m_command_dict["disassemble"] =
462 CommandObjectSP(new CommandObjectDisassemble(*this));
463 m_command_dict["expression"] =
464 CommandObjectSP(new CommandObjectExpression(*this));
465 m_command_dict["frame"] =
466 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
467 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
468 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
469 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
470 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
471 m_command_dict["platform"] =
472 CommandObjectSP(new CommandObjectPlatform(*this));
473 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
474 m_command_dict["process"] =
475 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
476 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
477 m_command_dict["register"] =
478 CommandObjectSP(new CommandObjectRegister(*this));
479 m_command_dict["script"] =
480 CommandObjectSP(new CommandObjectScript(*this, script_language));
481 m_command_dict["settings"] =
482 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
483 m_command_dict["source"] =
484 CommandObjectSP(new CommandObjectMultiwordSource(*this));
Davide Italiano24fff242018-04-13 18:02:39 +0000485 m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486 m_command_dict["target"] =
487 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
488 m_command_dict["thread"] =
489 CommandObjectSP(new CommandObjectMultiwordThread(*this));
490 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
491 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
492 m_command_dict["watchpoint"] =
493 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
494 m_command_dict["language"] =
495 CommandObjectSP(new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000496
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497 const char *break_regexes[][2] = {
498 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
499 "breakpoint set --file '%1' --line %2"},
500 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
501 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
502 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
503 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
504 "breakpoint set --name '%1'"},
505 {"^(-.*)$", "breakpoint set %1"},
506 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
507 "breakpoint set --name '%2' --shlib '%1'"},
508 {"^\\&(.*[^[:space:]])[[:space:]]*$",
509 "breakpoint set --name '%1' --skip-prologue=0"},
510 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
511 "breakpoint set --name '%1'"}};
Kate Stone7428a182016-07-14 22:03:10 +0000512
Kate Stoneb9c1b512016-09-06 20:57:50 +0000513 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000514
Kate Stoneb9c1b512016-09-06 20:57:50 +0000515 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap(
516 new CommandObjectRegexCommand(
517 *this, "_regexp-break",
Raphael Isemann129fe892018-07-30 21:41:13 +0000518 "Set a breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 "\n"
520 "_regexp-break <filename>:<linenum>\n"
521 " main.c:12 // Break at line 12 of "
522 "main.c\n\n"
523 "_regexp-break <linenum>\n"
524 " 12 // Break at line 12 of current "
525 "file\n\n"
526 "_regexp-break 0x<address>\n"
527 " 0x1234000 // Break at address "
528 "0x1234000\n\n"
529 "_regexp-break <name>\n"
530 " main // Break in 'main' after the "
531 "prologue\n\n"
532 "_regexp-break &<name>\n"
533 " &main // Break at first instruction "
534 "in 'main'\n\n"
535 "_regexp-break <module>`<name>\n"
536 " libc.so`malloc // Break in 'malloc' from "
537 "'libc.so'\n\n"
538 "_regexp-break /<source-regex>/\n"
539 " /break here/ // Break on source lines in "
540 "current file\n"
541 " // containing text 'break "
542 "here'.\n",
543 2, CommandCompletions::eSymbolCompletion |
544 CommandCompletions::eSourceFileCompletion,
545 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000546
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547 if (break_regex_cmd_ap.get()) {
548 bool success = true;
549 for (size_t i = 0; i < num_regexes; i++) {
550 success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0],
551 break_regexes[i][1]);
552 if (!success)
553 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000554 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 success =
556 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Jim Inghamffba2292011-03-22 02:29:32 +0000557
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 if (success) {
559 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
560 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
Jim Inghamca36cd12012-10-05 19:16:31 +0000561 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 }
Jim Inghamca36cd12012-10-05 19:16:31 +0000563
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap(
565 new CommandObjectRegexCommand(
566 *this, "_regexp-tbreak",
Raphael Isemann129fe892018-07-30 21:41:13 +0000567 "Set a one-shot breakpoint using one of several shorthand formats.",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 "\n"
569 "_regexp-break <filename>:<linenum>\n"
570 " main.c:12 // Break at line 12 of "
571 "main.c\n\n"
572 "_regexp-break <linenum>\n"
573 " 12 // Break at line 12 of current "
574 "file\n\n"
575 "_regexp-break 0x<address>\n"
576 " 0x1234000 // Break at address "
577 "0x1234000\n\n"
578 "_regexp-break <name>\n"
579 " main // Break in 'main' after the "
580 "prologue\n\n"
581 "_regexp-break &<name>\n"
582 " &main // Break at first instruction "
583 "in 'main'\n\n"
584 "_regexp-break <module>`<name>\n"
585 " libc.so`malloc // Break in 'malloc' from "
586 "'libc.so'\n\n"
587 "_regexp-break /<source-regex>/\n"
588 " /break here/ // Break on source lines in "
589 "current file\n"
590 " // containing text 'break "
591 "here'.\n",
592 2, CommandCompletions::eSymbolCompletion |
593 CommandCompletions::eSourceFileCompletion,
594 false));
595
596 if (tbreak_regex_cmd_ap.get()) {
597 bool success = true;
598 for (size_t i = 0; i < num_regexes; i++) {
599 // If you add a resultant command string longer than 1024 characters be
600 // sure to increase the size of this buffer.
601 char buffer[1024];
602 int num_printed =
Frederic Riss49c9d8b2018-06-18 04:34:33 +0000603 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1");
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000604 lldbassert(num_printed < 1024);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605 UNUSED_IF_ASSERT_DISABLED(num_printed);
606 success =
607 tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer);
608 if (!success)
609 break;
Johnny Chen6d675242012-08-24 18:15:45 +0000610 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000611 success =
612 tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Kate Stone7428a182016-07-14 22:03:10 +0000613
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614 if (success) {
615 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
616 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
617 tbreak_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000618 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000619 }
Kate Stone7428a182016-07-14 22:03:10 +0000620
Kate Stoneb9c1b512016-09-06 20:57:50 +0000621 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap(
622 new CommandObjectRegexCommand(
623 *this, "_regexp-attach", "Attach to process by ID or name.",
624 "_regexp-attach <pid> | <process-name>", 2, 0, false));
625 if (attach_regex_cmd_ap.get()) {
626 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
627 "process attach --pid %1") &&
628 attach_regex_cmd_ap->AddRegexCommand(
629 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
630 // specified get passed to
631 // 'process attach'
632 attach_regex_cmd_ap->AddRegexCommand("^(.+)$",
633 "process attach --name '%1'") &&
634 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) {
635 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
636 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
637 attach_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000638 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000639 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000640
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap(
642 new CommandObjectRegexCommand(*this, "_regexp-down",
643 "Select a newer stack frame. Defaults to "
644 "moving one frame, a numeric argument can "
645 "specify an arbitrary number.",
646 "_regexp-down [<count>]", 2, 0, false));
647 if (down_regex_cmd_ap.get()) {
648 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
649 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
650 "frame select -r -%1")) {
651 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
652 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000653 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000654 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000655
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap(
657 new CommandObjectRegexCommand(
658 *this, "_regexp-up",
659 "Select an older stack frame. Defaults to moving one "
660 "frame, a numeric argument can specify an arbitrary number.",
661 "_regexp-up [<count>]", 2, 0, false));
662 if (up_regex_cmd_ap.get()) {
663 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
664 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
665 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
666 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000667 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000669
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap(
671 new CommandObjectRegexCommand(
672 *this, "_regexp-display",
673 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
674 "_regexp-display expression", 2, 0, false));
675 if (display_regex_cmd_ap.get()) {
676 if (display_regex_cmd_ap->AddRegexCommand(
677 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
678 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
679 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
680 display_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000681 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000682 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000683
Kate Stoneb9c1b512016-09-06 20:57:50 +0000684 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap(
685 new CommandObjectRegexCommand(
686 *this, "_regexp-undisplay", "Stop displaying expression at every "
687 "stop (specified by stop-hook index.)",
688 "_regexp-undisplay stop-hook-number", 2, 0, false));
689 if (undisplay_regex_cmd_ap.get()) {
690 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
691 "target stop-hook delete %1")) {
692 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
693 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
694 undisplay_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000695 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000697
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap(
699 new CommandObjectRegexCommand(
700 *this, "gdb-remote", "Connect to a process via remote GDB server. "
701 "If no host is specifed, localhost is assumed.",
702 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
703 if (connect_gdb_remote_cmd_ap.get()) {
704 if (connect_gdb_remote_cmd_ap->AddRegexCommand(
Chris Bieneman51978f52017-04-27 16:13:58 +0000705 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
706 "process connect --plugin gdb-remote connect://%1:%2") &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707 connect_gdb_remote_cmd_ap->AddRegexCommand(
708 "^([[:digit:]]+)$",
709 "process connect --plugin gdb-remote connect://localhost:%1")) {
710 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
711 m_command_dict[command_sp->GetCommandName()] = command_sp;
Jason Molenda4cddfed2012-10-05 05:29:32 +0000712 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000713 }
Jason Molenda4cddfed2012-10-05 05:29:32 +0000714
Kate Stoneb9c1b512016-09-06 20:57:50 +0000715 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap(
716 new CommandObjectRegexCommand(
717 *this, "kdp-remote", "Connect to a process via remote KDP server. "
718 "If no UDP port is specified, port 41139 is "
719 "assumed.",
720 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
721 if (connect_kdp_remote_cmd_ap.get()) {
722 if (connect_kdp_remote_cmd_ap->AddRegexCommand(
723 "^([^:]+:[[:digit:]]+)$",
724 "process connect --plugin kdp-remote udp://%1") &&
725 connect_kdp_remote_cmd_ap->AddRegexCommand(
726 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
727 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
728 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Clayton6bade322013-02-01 23:33:03 +0000729 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 }
Greg Clayton6bade322013-02-01 23:33:03 +0000731
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap(
733 new CommandObjectRegexCommand(
734 *this, "_regexp-bt",
735 "Show the current thread's call stack. Any numeric argument "
736 "displays at most that many "
737 "frames. The argument 'all' displays all threads.",
738 "bt [<digit> | all]", 2, 0, false));
739 if (bt_regex_cmd_ap.get()) {
740 // accept but don't document "bt -c <number>" -- before bt was a regex
Adrian Prantl05097242018-04-30 16:49:04 +0000741 // command if you wanted to backtrace three frames you would do "bt -c 3"
742 // but the intention is to have this emulate the gdb "bt" command and so
743 // now "bt 3" is the preferred form, in line with gdb.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000744 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$",
745 "thread backtrace -c %1") &&
746 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$",
747 "thread backtrace -c %1") &&
748 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
749 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) {
750 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
751 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Claytonef5651d2013-02-12 18:52:24 +0000752 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 }
Greg Claytonef5651d2013-02-12 18:52:24 +0000754
Kate Stoneb9c1b512016-09-06 20:57:50 +0000755 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap(
756 new CommandObjectRegexCommand(
757 *this, "_regexp-list",
758 "List relevant source code using one of several shorthand formats.",
759 "\n"
760 "_regexp-list <file>:<line> // List around specific file/line\n"
761 "_regexp-list <line> // List current file around specified "
762 "line\n"
763 "_regexp-list <function-name> // List specified function\n"
764 "_regexp-list 0x<address> // List around specified address\n"
765 "_regexp-list -[<count>] // List previous <count> lines\n"
766 "_regexp-list // List subsequent lines",
767 2, CommandCompletions::eSourceFileCompletion, false));
768 if (list_regex_cmd_ap.get()) {
769 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
770 "source list --line %1") &&
771 list_regex_cmd_ap->AddRegexCommand(
772 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
773 "]*$",
774 "source list --file '%1' --line %2") &&
775 list_regex_cmd_ap->AddRegexCommand(
776 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
777 "source list --address %1") &&
778 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$",
779 "source list --reverse") &&
780 list_regex_cmd_ap->AddRegexCommand(
781 "^-([[:digit:]]+)[[:space:]]*$",
782 "source list --reverse --count %1") &&
783 list_regex_cmd_ap->AddRegexCommand("^(.+)$",
784 "source list --name \"%1\"") &&
785 list_regex_cmd_ap->AddRegexCommand("^$", "source list")) {
786 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
787 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
Richard Mittonf86248d2013-09-12 02:20:34 +0000788 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000789 }
Richard Mittonf86248d2013-09-12 02:20:34 +0000790
Kate Stoneb9c1b512016-09-06 20:57:50 +0000791 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap(
792 new CommandObjectRegexCommand(
793 *this, "_regexp-env",
794 "Shorthand for viewing and setting environment variables.",
795 "\n"
796 "_regexp-env // Show enrivonment\n"
797 "_regexp-env <name>=<value> // Set an environment variable",
798 2, 0, false));
799 if (env_regex_cmd_ap.get()) {
800 if (env_regex_cmd_ap->AddRegexCommand("^$",
801 "settings show target.env-vars") &&
802 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
803 "settings set target.env-vars %1")) {
804 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
805 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
806 }
807 }
808
809 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap(
810 new CommandObjectRegexCommand(
811 *this, "_regexp-jump", "Set the program counter to a new address.",
812 "\n"
813 "_regexp-jump <line>\n"
814 "_regexp-jump +<line-offset> | -<line-offset>\n"
815 "_regexp-jump <file>:<line>\n"
816 "_regexp-jump *<addr>\n",
817 2, 0, false));
818 if (jump_regex_cmd_ap.get()) {
819 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$",
820 "thread jump --addr %1") &&
821 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
822 "thread jump --line %1") &&
823 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$",
824 "thread jump --file %1 --line %2") &&
825 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$",
826 "thread jump --by %1")) {
827 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
828 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
829 }
830 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000831}
832
Kate Stoneb9c1b512016-09-06 20:57:50 +0000833int CommandInterpreter::GetCommandNamesMatchingPartialString(
Raphael Isemann7f888292018-09-13 21:26:00 +0000834 const char *cmd_str, bool include_aliases, StringList &matches,
835 StringList &descriptions) {
836 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches,
837 &descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000838
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 if (include_aliases) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000840 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches,
841 &descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000843
Kate Stoneb9c1b512016-09-06 20:57:50 +0000844 return matches.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000845}
846
Raphael Isemann7f888292018-09-13 21:26:00 +0000847CommandObjectSP
848CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases,
849 bool exact, StringList *matches,
850 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000852
Zachary Turnera4496982016-10-05 21:14:38 +0000853 std::string cmd = cmd_str;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000854
Kate Stoneb9c1b512016-09-06 20:57:50 +0000855 if (HasCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000856 auto pos = m_command_dict.find(cmd);
Greg Claytonb5472782015-01-09 19:08:20 +0000857 if (pos != m_command_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000858 command_sp = pos->second;
859 }
860
861 if (include_aliases && HasAliases()) {
862 auto alias_pos = m_alias_dict.find(cmd);
863 if (alias_pos != m_alias_dict.end())
864 command_sp = alias_pos->second;
865 }
866
867 if (HasUserCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000868 auto pos = m_user_dict.find(cmd);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000869 if (pos != m_user_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000870 command_sp = pos->second;
871 }
872
873 if (!exact && !command_sp) {
874 // We will only get into here if we didn't find any exact matches.
875
876 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
877
878 StringList local_matches;
879 if (matches == nullptr)
880 matches = &local_matches;
881
882 unsigned int num_cmd_matches = 0;
883 unsigned int num_alias_matches = 0;
884 unsigned int num_user_matches = 0;
885
886 // Look through the command dictionaries one by one, and if we get only one
Adrian Prantl05097242018-04-30 16:49:04 +0000887 // match from any of them in toto, then return that, otherwise return an
888 // empty CommandObjectSP and the list of matches.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000889
890 if (HasCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000891 num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str,
892 *matches, descriptions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000893 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000894
895 if (num_cmd_matches == 1) {
896 cmd.assign(matches->GetStringAtIndex(0));
Zachary Turnera4496982016-10-05 21:14:38 +0000897 auto pos = m_command_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000898 if (pos != m_command_dict.end())
899 real_match_sp = pos->second;
900 }
901
902 if (include_aliases && HasAliases()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000903 num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str,
904 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000905 }
906
907 if (num_alias_matches == 1) {
908 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
909 auto alias_pos = m_alias_dict.find(cmd);
910 if (alias_pos != m_alias_dict.end())
911 alias_match_sp = alias_pos->second;
912 }
913
914 if (HasUserCommands()) {
Raphael Isemann7f888292018-09-13 21:26:00 +0000915 num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str,
916 *matches, descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000917 }
918
919 if (num_user_matches == 1) {
920 cmd.assign(
921 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
922
Zachary Turnera4496982016-10-05 21:14:38 +0000923 auto pos = m_user_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 if (pos != m_user_dict.end())
925 user_match_sp = pos->second;
926 }
927
928 // If we got exactly one match, return that, otherwise return the match
929 // list.
930
931 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
932 if (num_cmd_matches)
933 return real_match_sp;
934 else if (num_alias_matches)
935 return alias_match_sp;
936 else
937 return user_match_sp;
938 }
939 } else if (matches && command_sp) {
Zachary Turnera4496982016-10-05 21:14:38 +0000940 matches->AppendString(cmd_str);
Raphael Isemann7f888292018-09-13 21:26:00 +0000941 if (descriptions)
942 descriptions->AppendString(command_sp->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000943 }
944
945 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000946}
947
Zachary Turnera4496982016-10-05 21:14:38 +0000948bool CommandInterpreter::AddCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949 const lldb::CommandObjectSP &cmd_sp,
950 bool can_replace) {
951 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000952 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
953 "tried to add a CommandObject from a different interpreter");
Kate Stonea487aa42015-01-15 00:52:41 +0000954
Zachary Turnera4496982016-10-05 21:14:38 +0000955 if (name.empty())
956 return false;
957
958 std::string name_sstr(name);
959 auto name_iter = m_command_dict.find(name_sstr);
960 if (name_iter != m_command_dict.end()) {
961 if (!can_replace || !name_iter->second->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000962 return false;
Zachary Turnera4496982016-10-05 21:14:38 +0000963 name_iter->second = cmd_sp;
964 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000965 m_command_dict[name_sstr] = cmd_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000966 }
Zachary Turnera4496982016-10-05 21:14:38 +0000967 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000968}
969
Zachary Turnera483f572016-10-05 21:14:49 +0000970bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 const lldb::CommandObjectSP &cmd_sp,
972 bool can_replace) {
973 if (cmd_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +0000974 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
975 "tried to add a CommandObject from a different interpreter");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000976
Kate Stoneb9c1b512016-09-06 20:57:50 +0000977 if (!name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978 // do not allow replacement of internal commands
Zachary Turnera483f572016-10-05 21:14:49 +0000979 if (CommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980 if (can_replace == false)
981 return false;
982 if (m_command_dict[name]->IsRemovable() == false)
Greg Clayton5a314712011-10-14 07:41:33 +0000983 return false;
984 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000985
Zachary Turnera483f572016-10-05 21:14:49 +0000986 if (UserCommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000987 if (can_replace == false)
988 return false;
989 if (m_user_dict[name]->IsRemovable() == false)
990 return false;
Caroline Tice844d2302010-12-09 22:52:49 +0000991 }
992
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993 m_user_dict[name] = cmd_sp;
994 return true;
995 }
996 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000997}
998
Zachary Turnera4496982016-10-05 21:14:38 +0000999CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
1000 bool include_aliases) const {
1001 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002 // it's a multi-word command.
1003 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001004
Zachary Turnera4496982016-10-05 21:14:38 +00001005 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001006 return ret_val;
1007
1008 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +00001009 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001010 else {
1011 // We have a multi-word command (seemingly), so we need to do more work.
1012 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +00001013 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001014 include_aliases, true, nullptr);
1015 if (cmd_obj_sp.get() != nullptr) {
Adrian Prantl05097242018-04-30 16:49:04 +00001016 // Loop through the rest of the words in the command (everything passed
1017 // in was supposed to be part of a command name), and find the
1018 // appropriate sub-command SP for each command word....
Kate Stoneb9c1b512016-09-06 20:57:50 +00001019 size_t end = cmd_words.GetArgumentCount();
1020 for (size_t j = 1; j < end; ++j) {
1021 if (cmd_obj_sp->IsMultiwordObject()) {
1022 cmd_obj_sp =
1023 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
1024 if (cmd_obj_sp.get() == nullptr)
1025 // The sub-command name was invalid. Fail and return the empty
1026 // 'ret_val'.
1027 return ret_val;
1028 } else
1029 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +00001030 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001031 return ret_val;
1032 }
1033 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +00001034 // command objects for them. Assign the last object retrieved to
1035 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001037 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001038 }
1039 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001040}
1041
Raphael Isemann7f888292018-09-13 21:26:00 +00001042CommandObject *
1043CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
1044 StringList *matches,
1045 StringList *descriptions) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001046 CommandObject *command_obj =
Raphael Isemann7f888292018-09-13 21:26:00 +00001047 GetCommandSP(cmd_str, false, true, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001048
Kate Stoneb9c1b512016-09-06 20:57:50 +00001049 // If we didn't find an exact match to the command string in the commands,
Adrian Prantl05097242018-04-30 16:49:04 +00001050 // look in the aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001051
1052 if (command_obj)
1053 return command_obj;
1054
Raphael Isemann7f888292018-09-13 21:26:00 +00001055 command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001056
1057 if (command_obj)
1058 return command_obj;
1059
1060 // If there wasn't an exact match then look for an inexact one in just the
1061 // commands
Zachary Turnera4496982016-10-05 21:14:38 +00001062 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063
1064 // Finally, if there wasn't an inexact match among the commands, look for an
Adrian Prantl05097242018-04-30 16:49:04 +00001065 // inexact match in both the commands and aliases.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001066
1067 if (command_obj) {
1068 if (matches)
1069 matches->AppendString(command_obj->GetCommandName());
Raphael Isemann7f888292018-09-13 21:26:00 +00001070 if (descriptions)
1071 descriptions->AppendString(command_obj->GetHelp());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001072 return command_obj;
1073 }
1074
Raphael Isemann7f888292018-09-13 21:26:00 +00001075 return GetCommandSP(cmd_str, true, false, matches, descriptions).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001076}
1077
Zachary Turnera483f572016-10-05 21:14:49 +00001078bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001079 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001080}
1081
Zachary Turnera483f572016-10-05 21:14:49 +00001082bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1083 std::string &full_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001084 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1085 if (exact_match) {
1086 full_name.assign(cmd);
1087 return exact_match;
1088 } else {
1089 StringList matches;
1090 size_t num_alias_matches;
1091 num_alias_matches =
1092 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1093 if (num_alias_matches == 1) {
1094 // Make sure this isn't shadowing a command in the regular command space:
1095 StringList regular_matches;
1096 const bool include_aliases = false;
1097 const bool exact = false;
1098 CommandObjectSP cmd_obj_sp(
1099 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1100 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1101 return false;
1102 else {
1103 full_name.assign(matches.GetStringAtIndex(0));
1104 return true;
1105 }
1106 } else
1107 return false;
1108 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001109}
1110
Zachary Turnera483f572016-10-05 21:14:49 +00001111bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001112 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001113}
1114
Zachary Turnera483f572016-10-05 21:14:49 +00001115bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001116 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001117}
1118
Kate Stoneb9c1b512016-09-06 20:57:50 +00001119CommandAlias *
Zachary Turnera483f572016-10-05 21:14:49 +00001120CommandInterpreter::AddAlias(llvm::StringRef alias_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001121 lldb::CommandObjectSP &command_obj_sp,
Zachary Turnera483f572016-10-05 21:14:49 +00001122 llvm::StringRef args_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123 if (command_obj_sp.get())
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001124 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1125 "tried to add a CommandObject from a different interpreter");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001126
1127 std::unique_ptr<CommandAlias> command_alias_up(
1128 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1129
1130 if (command_alias_up && command_alias_up->IsValid()) {
1131 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1132 return command_alias_up.release();
1133 }
1134
1135 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001136}
1137
Zachary Turnera483f572016-10-05 21:14:49 +00001138bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139 auto pos = m_alias_dict.find(alias_name);
1140 if (pos != m_alias_dict.end()) {
1141 m_alias_dict.erase(pos);
1142 return true;
1143 }
1144 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001145}
1146
Zachary Turnera483f572016-10-05 21:14:49 +00001147bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001148 auto pos = m_command_dict.find(cmd);
1149 if (pos != m_command_dict.end()) {
1150 if (pos->second->IsRemovable()) {
1151 // Only regular expression objects or python commands are removable
1152 m_command_dict.erase(pos);
1153 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001154 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001155 }
1156 return false;
1157}
Zachary Turnera483f572016-10-05 21:14:49 +00001158bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001159 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1160 if (pos != m_user_dict.end()) {
1161 m_user_dict.erase(pos);
1162 return true;
1163 }
1164 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001165}
1166
Kate Stoneb9c1b512016-09-06 20:57:50 +00001167void CommandInterpreter::GetHelp(CommandReturnObject &result,
1168 uint32_t cmd_types) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001169 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1170 if (!help_prologue.empty()) {
1171 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1172 help_prologue);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001174
Kate Stoneb9c1b512016-09-06 20:57:50 +00001175 CommandObject::CommandMap::const_iterator pos;
1176 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001177
Kate Stoneb9c1b512016-09-06 20:57:50 +00001178 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1179 result.AppendMessage("Debugger commands:");
1180 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001181
Kate Stoneb9c1b512016-09-06 20:57:50 +00001182 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1183 if (!(cmd_types & eCommandTypesHidden) &&
1184 (pos->first.compare(0, 1, "_") == 0))
1185 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001186
Zachary Turner0ac5f982016-11-08 04:12:42 +00001187 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1188 pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001189 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190 result.AppendMessage("");
1191 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001192
Kate Stoneb9c1b512016-09-06 20:57:50 +00001193 if (!m_alias_dict.empty() &&
1194 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1195 result.AppendMessageWithFormat(
1196 "Current command abbreviations "
1197 "(type '%shelp command alias' for more info):\n",
1198 GetCommandPrefix());
1199 result.AppendMessage("");
1200 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001201
Kate Stoneb9c1b512016-09-06 20:57:50 +00001202 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1203 ++alias_pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001204 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
Kate Stoneb9c1b512016-09-06 20:57:50 +00001205 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001206 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001207 result.AppendMessage("");
1208 }
Greg Clayton14a35512011-09-11 00:01:44 +00001209
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 if (!m_user_dict.empty() &&
1211 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1212 result.AppendMessage("Current user-defined commands:");
1213 result.AppendMessage("");
1214 max_len = FindLongestCommandWord(m_user_dict);
1215 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00001216 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1217 pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001218 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001219 result.AppendMessage("");
1220 }
Greg Clayton14a35512011-09-11 00:01:44 +00001221
Kate Stoneb9c1b512016-09-06 20:57:50 +00001222 result.AppendMessageWithFormat(
1223 "For more information on any command, type '%shelp <command-name>'.\n",
1224 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001225}
1226
Zachary Turnera01bccd2016-10-05 21:14:56 +00001227CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1228 llvm::StringRef &command_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229 // This function finds the final, lowest-level, alias-resolved command object
Adrian Prantl05097242018-04-30 16:49:04 +00001230 // whose 'Execute' function will eventually be invoked by the given command
1231 // line.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001232
1233 CommandObject *cmd_obj = nullptr;
1234 size_t start = command_string.find_first_not_of(k_white_space);
1235 size_t end = 0;
1236 bool done = false;
1237 while (!done) {
1238 if (start != std::string::npos) {
1239 // Get the next word from command_string.
1240 end = command_string.find_first_of(k_white_space, start);
1241 if (end == std::string::npos)
1242 end = command_string.size();
1243 std::string cmd_word = command_string.substr(start, end - start);
1244
1245 if (cmd_obj == nullptr)
1246 // Since cmd_obj is NULL we are on our first time through this loop.
Zachary Turnera01bccd2016-10-05 21:14:56 +00001247 // Check to see if cmd_word is a valid command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001248 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001249 else if (cmd_obj->IsMultiwordObject()) {
1250 // Our current object is a multi-word object; see if the cmd_word is a
1251 // valid sub-command for our object.
1252 CommandObject *sub_cmd_obj =
1253 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1254 if (sub_cmd_obj)
1255 cmd_obj = sub_cmd_obj;
1256 else // cmd_word was not a valid sub-command word, so we are done
1257 done = true;
1258 } else
1259 // We have a cmd_obj and it is not a multi-word object, so we are done.
1260 done = true;
1261
1262 // If we didn't find a valid command object, or our command object is not
Zachary Turnera01bccd2016-10-05 21:14:56 +00001263 // a multi-word object, or we are at the end of the command_string, then
1264 // we are done. Otherwise, find the start of the next word.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265
1266 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1267 end >= command_string.size())
1268 done = true;
1269 else
1270 start = command_string.find_first_not_of(k_white_space, end);
1271 } else
1272 // Unable to find any more words.
1273 done = true;
1274 }
1275
Zachary Turnera01bccd2016-10-05 21:14:56 +00001276 command_string = command_string.substr(end);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001277 return cmd_obj;
1278}
1279
1280static const char *k_valid_command_chars =
1281 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1282static void StripLeadingSpaces(std::string &s) {
1283 if (!s.empty()) {
1284 size_t pos = s.find_first_not_of(k_white_space);
1285 if (pos == std::string::npos)
1286 s.clear();
1287 else if (pos == 0)
1288 return;
1289 s.erase(0, pos);
1290 }
1291}
1292
1293static size_t FindArgumentTerminator(const std::string &s) {
1294 const size_t s_len = s.size();
1295 size_t offset = 0;
1296 while (offset < s_len) {
1297 size_t pos = s.find("--", offset);
1298 if (pos == std::string::npos)
1299 break;
1300 if (pos > 0) {
1301 if (isspace(s[pos - 1])) {
Adrian Prantl05097242018-04-30 16:49:04 +00001302 // Check if the string ends "\s--" (where \s is a space character) or
1303 // if we have "\s--\s".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1305 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001306 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001307 }
1308 }
1309 offset = pos + 2;
1310 }
1311 return std::string::npos;
1312}
1313
1314static bool ExtractCommand(std::string &command_string, std::string &command,
1315 std::string &suffix, char &quote_char) {
1316 command.clear();
1317 suffix.clear();
1318 StripLeadingSpaces(command_string);
1319
1320 bool result = false;
1321 quote_char = '\0';
1322
1323 if (!command_string.empty()) {
1324 const char first_char = command_string[0];
1325 if (first_char == '\'' || first_char == '"') {
1326 quote_char = first_char;
1327 const size_t end_quote_pos = command_string.find(quote_char, 1);
1328 if (end_quote_pos == std::string::npos) {
1329 command.swap(command_string);
1330 command_string.erase();
1331 } else {
1332 command.assign(command_string, 1, end_quote_pos - 1);
1333 if (end_quote_pos + 1 < command_string.size())
1334 command_string.erase(0, command_string.find_first_not_of(
1335 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001336 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001337 command_string.erase();
1338 }
1339 } else {
1340 const size_t first_space_pos =
1341 command_string.find_first_of(k_white_space);
1342 if (first_space_pos == std::string::npos) {
1343 command.swap(command_string);
1344 command_string.erase();
1345 } else {
1346 command.assign(command_string, 0, first_space_pos);
1347 command_string.erase(0, command_string.find_first_not_of(
1348 k_white_space, first_space_pos));
1349 }
1350 }
1351 result = true;
1352 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001353
Kate Stoneb9c1b512016-09-06 20:57:50 +00001354 if (!command.empty()) {
1355 // actual commands can't start with '-' or '_'
1356 if (command[0] != '-' && command[0] != '_') {
1357 size_t pos = command.find_first_not_of(k_valid_command_chars);
1358 if (pos > 0 && pos != std::string::npos) {
1359 suffix.assign(command.begin() + pos, command.end());
1360 command.erase(pos);
1361 }
1362 }
1363 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001364
Kate Stoneb9c1b512016-09-06 20:57:50 +00001365 return result;
1366}
1367
1368CommandObject *CommandInterpreter::BuildAliasResult(
Zachary Turnera483f572016-10-05 21:14:49 +00001369 llvm::StringRef alias_name, std::string &raw_input_string,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001370 std::string &alias_result, CommandReturnObject &result) {
1371 CommandObject *alias_cmd_obj = nullptr;
1372 Args cmd_args(raw_input_string);
1373 alias_cmd_obj = GetCommandObject(alias_name);
1374 StreamString result_str;
1375
Zachary Turner5c28c662016-10-03 23:20:36 +00001376 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1377 alias_result.clear();
1378 return alias_cmd_obj;
1379 }
1380 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1381 ((CommandAlias *)alias_cmd_obj)->Desugar();
1382 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1383 alias_cmd_obj = desugared.first.get();
1384 std::string alias_name_str = alias_name;
1385 if ((cmd_args.GetArgumentCount() == 0) ||
1386 (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0))
1387 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001388
Zachary Turnera4496982016-10-05 21:14:38 +00001389 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001390
Zachary Turner5c28c662016-10-03 23:20:36 +00001391 if (!option_arg_vector_sp.get()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001392 alias_result = result_str.GetString();
Zachary Turner5c28c662016-10-03 23:20:36 +00001393 return alias_cmd_obj;
1394 }
1395 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001396
Zachary Turner5c28c662016-10-03 23:20:36 +00001397 int value_type;
1398 std::string option;
1399 std::string value;
1400 for (const auto &entry : *option_arg_vector) {
1401 std::tie(option, value_type, value) = entry;
1402 if (option == "<argument>") {
1403 result_str.Printf(" %s", value.c_str());
1404 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001405 }
1406
Zachary Turner5c28c662016-10-03 23:20:36 +00001407 result_str.Printf(" %s", option.c_str());
1408 if (value_type == OptionParser::eNoArgument)
1409 continue;
1410
1411 if (value_type != OptionParser::eOptionalArgument)
1412 result_str.Printf(" ");
1413 int index = GetOptionArgumentPosition(value.c_str());
1414 if (index == 0)
1415 result_str.Printf("%s", value.c_str());
1416 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1417
1418 result.AppendErrorWithFormat("Not enough arguments provided; you "
1419 "need at least %d arguments to use "
1420 "this alias.\n",
1421 index);
1422 result.SetStatus(eReturnStatusFailed);
1423 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001424 } else {
1425 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1426 if (strpos != std::string::npos)
1427 raw_input_string = raw_input_string.erase(
1428 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1429 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001430 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001431 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001432
Zachary Turnerc1564272016-11-16 21:15:24 +00001433 alias_result = result_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001434 return alias_cmd_obj;
1435}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001436
Zachary Turner97206d52017-05-12 04:51:55 +00001437Status CommandInterpreter::PreprocessCommand(std::string &command) {
Adrian Prantl05097242018-04-30 16:49:04 +00001438 // The command preprocessor needs to do things to the command line before any
1439 // parsing of arguments or anything else is done. The only current stuff that
1440 // gets preprocessed is anything enclosed in backtick ('`') characters is
1441 // evaluated as an expression and the result of the expression must be a
1442 // scalar that can be substituted into the command. An example would be:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 // (lldb) memory read `$rsp + 20`
Zachary Turner97206d52017-05-12 04:51:55 +00001444 Status error; // Status for any expressions that might not evaluate
Kate Stoneb9c1b512016-09-06 20:57:50 +00001445 size_t start_backtick;
1446 size_t pos = 0;
1447 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1448 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
Adrian Prantl05097242018-04-30 16:49:04 +00001449 // The backtick was preceded by a '\' character, remove the slash and
1450 // don't treat the backtick as the start of an expression
Kate Stoneb9c1b512016-09-06 20:57:50 +00001451 command.erase(start_backtick - 1, 1);
1452 // No need to add one to start_backtick since we just deleted a char
1453 pos = start_backtick;
1454 } else {
1455 const size_t expr_content_start = start_backtick + 1;
1456 const size_t end_backtick = command.find('`', expr_content_start);
1457 if (end_backtick == std::string::npos)
1458 return error;
1459 else if (end_backtick == expr_content_start) {
1460 // Empty expression (two backticks in a row)
1461 command.erase(start_backtick, 2);
1462 } else {
1463 std::string expr_str(command, expr_content_start,
1464 end_backtick - expr_content_start);
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001465
Kate Stoneb9c1b512016-09-06 20:57:50 +00001466 ExecutionContext exe_ctx(GetExecutionContext());
1467 Target *target = exe_ctx.GetTargetPtr();
1468 // Get a dummy target to allow for calculator mode while processing
Adrian Prantl05097242018-04-30 16:49:04 +00001469 // backticks. This also helps break the infinite loop caused when
1470 // target is null.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001471 if (!target)
1472 target = m_debugger.GetDummyTarget();
1473 if (target) {
1474 ValueObjectSP expr_result_valobj_sp;
1475
1476 EvaluateExpressionOptions options;
1477 options.SetCoerceToId(false);
1478 options.SetUnwindOnError(true);
1479 options.SetIgnoreBreakpoints(true);
1480 options.SetKeepInMemory(false);
1481 options.SetTryAllThreads(true);
Pavel Labath43d35412016-12-06 11:24:51 +00001482 options.SetTimeout(llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001483
1484 ExpressionResults expr_result = target->EvaluateExpression(
1485 expr_str.c_str(), exe_ctx.GetFramePtr(), expr_result_valobj_sp,
1486 options);
1487
1488 if (expr_result == eExpressionCompleted) {
1489 Scalar scalar;
1490 if (expr_result_valobj_sp)
1491 expr_result_valobj_sp =
1492 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1493 expr_result_valobj_sp->GetDynamicValueType(), true);
1494 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1495 command.erase(start_backtick, end_backtick - start_backtick + 1);
1496 StreamString value_strm;
1497 const bool show_type = false;
1498 scalar.GetValue(&value_strm, show_type);
1499 size_t value_string_size = value_strm.GetSize();
1500 if (value_string_size) {
Zachary Turnerc1564272016-11-16 21:15:24 +00001501 command.insert(start_backtick, value_strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001502 pos = start_backtick + value_string_size;
1503 continue;
1504 } else {
1505 error.SetErrorStringWithFormat("expression value didn't result "
1506 "in a scalar value for the "
1507 "expression '%s'",
1508 expr_str.c_str());
1509 }
1510 } else {
1511 error.SetErrorStringWithFormat("expression value didn't result "
1512 "in a scalar value for the "
1513 "expression '%s'",
1514 expr_str.c_str());
1515 }
1516 } else {
1517 if (expr_result_valobj_sp)
1518 error = expr_result_valobj_sp->GetError();
1519 if (error.Success()) {
1520
1521 switch (expr_result) {
1522 case eExpressionSetupError:
1523 error.SetErrorStringWithFormat(
1524 "expression setup error for the expression '%s'",
1525 expr_str.c_str());
1526 break;
1527 case eExpressionParseError:
1528 error.SetErrorStringWithFormat(
1529 "expression parse error for the expression '%s'",
1530 expr_str.c_str());
1531 break;
1532 case eExpressionResultUnavailable:
1533 error.SetErrorStringWithFormat(
1534 "expression error fetching result for the expression '%s'",
1535 expr_str.c_str());
1536 break;
1537 case eExpressionCompleted:
1538 break;
1539 case eExpressionDiscarded:
1540 error.SetErrorStringWithFormat(
1541 "expression discarded for the expression '%s'",
1542 expr_str.c_str());
1543 break;
1544 case eExpressionInterrupted:
1545 error.SetErrorStringWithFormat(
1546 "expression interrupted for the expression '%s'",
1547 expr_str.c_str());
1548 break;
1549 case eExpressionHitBreakpoint:
1550 error.SetErrorStringWithFormat(
1551 "expression hit breakpoint for the expression '%s'",
1552 expr_str.c_str());
1553 break;
1554 case eExpressionTimedOut:
1555 error.SetErrorStringWithFormat(
1556 "expression timed out for the expression '%s'",
1557 expr_str.c_str());
1558 break;
1559 case eExpressionStoppedForDebug:
1560 error.SetErrorStringWithFormat("expression stop at entry point "
1561 "for debugging for the "
1562 "expression '%s'",
1563 expr_str.c_str());
1564 break;
1565 }
1566 }
1567 }
1568 }
1569 }
1570 if (error.Fail())
1571 break;
1572 }
1573 }
1574 return error;
1575}
1576
1577bool CommandInterpreter::HandleCommand(const char *command_line,
1578 LazyBool lazy_add_to_history,
1579 CommandReturnObject &result,
1580 ExecutionContext *override_context,
1581 bool repeat_on_empty_command,
1582 bool no_context_switching)
1583
1584{
1585
1586 std::string command_string(command_line);
1587 std::string original_command_string(command_line);
1588
1589 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
Jim Ingham8f7db522016-12-15 00:30:30 +00001590 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
Sean Callanan237c3ed2016-12-14 21:31:31 +00001591 command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001592
1593 if (log)
1594 log->Printf("Processing command: %s", command_line);
1595
Pavel Labathf9d16472017-05-15 13:02:37 +00001596 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1597 Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001598
1599 if (!no_context_switching)
1600 UpdateExecutionContext(override_context);
1601
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001602 if (WasInterrupted()) {
1603 result.AppendError("interrupted");
1604 result.SetStatus(eReturnStatusFailed);
1605 return false;
1606 }
1607
Kate Stoneb9c1b512016-09-06 20:57:50 +00001608 bool add_to_history;
1609 if (lazy_add_to_history == eLazyBoolCalculate)
1610 add_to_history = (m_command_source_depth == 0);
1611 else
1612 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1613
1614 bool empty_command = false;
1615 bool comment_command = false;
1616 if (command_string.empty())
1617 empty_command = true;
1618 else {
1619 const char *k_space_characters = "\t\n\v\f\r ";
1620
1621 size_t non_space = command_string.find_first_not_of(k_space_characters);
Adrian Prantl05097242018-04-30 16:49:04 +00001622 // Check for empty line or comment line (lines whose first non-space
1623 // character is the comment character for this interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001624 if (non_space == std::string::npos)
1625 empty_command = true;
1626 else if (command_string[non_space] == m_comment_char)
1627 comment_command = true;
1628 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001629 llvm::StringRef search_str(command_string);
1630 search_str = search_str.drop_front(non_space);
1631 if (auto hist_str = m_command_history.FindString(search_str)) {
1632 add_to_history = false;
1633 command_string = *hist_str;
1634 original_command_string = *hist_str;
1635 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001636 result.AppendErrorWithFormat("Could not find entry: %s in history",
1637 command_string.c_str());
1638 result.SetStatus(eReturnStatusFailed);
1639 return false;
1640 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001641 }
1642 }
1643
1644 if (empty_command) {
1645 if (repeat_on_empty_command) {
1646 if (m_command_history.IsEmpty()) {
1647 result.AppendError("empty command");
1648 result.SetStatus(eReturnStatusFailed);
1649 return false;
1650 } else {
1651 command_line = m_repeat_command.c_str();
1652 command_string = command_line;
1653 original_command_string = command_line;
1654 if (m_repeat_command.empty()) {
1655 result.AppendErrorWithFormat("No auto repeat.\n");
1656 result.SetStatus(eReturnStatusFailed);
1657 return false;
1658 }
1659 }
1660 add_to_history = false;
1661 } else {
1662 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1663 return true;
1664 }
1665 } else if (comment_command) {
1666 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1667 return true;
1668 }
1669
Zachary Turner97206d52017-05-12 04:51:55 +00001670 Status error(PreprocessCommand(command_string));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001671
1672 if (error.Fail()) {
1673 result.AppendError(error.AsCString());
1674 result.SetStatus(eReturnStatusFailed);
1675 return false;
1676 }
1677
1678 // Phase 1.
1679
1680 // Before we do ANY kind of argument processing, we need to figure out what
1681 // the real/final command object is for the specified command. This gets
1682 // complicated by the fact that the user could have specified an alias, and,
1683 // in translating the alias, there may also be command options and/or even
1684 // data (including raw text strings) that need to be found and inserted into
1685 // the command line as part of the translation. So this first step is plain
1686 // look-up and replacement, resulting in:
1687 // 1. the command object whose Execute method will actually be called
1688 // 2. a revised command string, with all substitutions and replacements
1689 // taken care of
1690 // From 1 above, we can determine whether the Execute function wants raw
1691 // input or not.
1692
1693 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1694
1695 // Although the user may have abbreviated the command, the command_string now
Adrian Prantl05097242018-04-30 16:49:04 +00001696 // has the command expanded to the full name. For example, if the input was
1697 // "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001698 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001699 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1700 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001701 log->Printf("HandleCommand, (revised) command_string: '%s'",
1702 command_string.c_str());
1703 const bool wants_raw_input =
1704 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1705 log->Printf("HandleCommand, wants_raw_input:'%s'",
1706 wants_raw_input ? "True" : "False");
1707 }
1708
1709 // Phase 2.
1710 // Take care of things like setting up the history command & calling the
Adrian Prantl05097242018-04-30 16:49:04 +00001711 // appropriate Execute method on the CommandObject, with the appropriate
1712 // arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001713
1714 if (cmd_obj != nullptr) {
1715 if (add_to_history) {
1716 Args command_args(command_string);
1717 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1718 if (repeat_command != nullptr)
1719 m_repeat_command.assign(repeat_command);
1720 else
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001721 m_repeat_command.assign(original_command_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001722
1723 m_command_history.AppendString(original_command_string);
1724 }
1725
1726 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001727 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001728 if (actual_cmd_name_len < command_string.length())
1729 remainder = command_string.substr(actual_cmd_name_len);
1730
1731 // Remove any initial spaces
1732 size_t pos = remainder.find_first_not_of(k_white_space);
1733 if (pos != 0 && pos != std::string::npos)
1734 remainder.erase(0, pos);
1735
1736 if (log)
1737 log->Printf(
1738 "HandleCommand, command line after removing command name(s): '%s'",
1739 remainder.c_str());
1740
1741 cmd_obj->Execute(remainder.c_str(), result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001742 }
1743
1744 if (log)
1745 log->Printf("HandleCommand, command %s",
1746 (result.Succeeded() ? "succeeded" : "did not succeed"));
1747
1748 return result.Succeeded();
1749}
1750
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001751int CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001752 int num_command_matches = 0;
1753 bool look_for_subcommand = false;
1754
1755 // For any of the command completions a unique match will be a complete word.
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001756 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001757
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001758 if (request.GetCursorIndex() == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001759 // We got nothing on the command line, so return the list of commands
1760 bool include_aliases = true;
Raphael Isemann7f888292018-09-13 21:26:00 +00001761 StringList new_matches, descriptions;
1762 num_command_matches = GetCommandNamesMatchingPartialString(
1763 "", include_aliases, new_matches, descriptions);
1764 request.AddCompletions(new_matches, descriptions);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001765 } else if (request.GetCursorIndex() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001766 // The cursor is in the first argument, so just do a lookup in the
1767 // dictionary.
Raphael Isemann7f888292018-09-13 21:26:00 +00001768 StringList new_matches, new_descriptions;
1769 CommandObject *cmd_obj =
1770 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0),
1771 &new_matches, &new_descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001772
1773 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001774 new_matches.GetStringAtIndex(0) != nullptr &&
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001775 strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001776 new_matches.GetStringAtIndex(0)) == 0) {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001777 if (request.GetParsedLine().GetArgumentCount() == 1) {
1778 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001779 } else {
1780 look_for_subcommand = true;
1781 num_command_matches = 0;
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001782 new_matches.DeleteStringAtIndex(0);
Raphael Isemann7f888292018-09-13 21:26:00 +00001783 new_descriptions.DeleteStringAtIndex(0);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001784 request.GetParsedLine().AppendArgument(llvm::StringRef());
1785 request.SetCursorIndex(request.GetCursorIndex() + 1);
1786 request.SetCursorCharPosition(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001787 }
1788 }
Raphael Isemann7f888292018-09-13 21:26:00 +00001789 request.AddCompletions(new_matches, new_descriptions);
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001790 num_command_matches = request.GetNumberOfMatches();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001791 }
1792
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001793 if (request.GetCursorIndex() > 0 || look_for_subcommand) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001794 // We are completing further on into a commands arguments, so find the
Adrian Prantl05097242018-04-30 16:49:04 +00001795 // command and tell it to complete the command. First see if there is a
1796 // matching initial command:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001797 CommandObject *command_object =
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001798 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001799 if (command_object == nullptr) {
1800 return 0;
1801 } else {
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001802 request.GetParsedLine().Shift();
1803 request.SetCursorIndex(request.GetCursorIndex() - 1);
1804 num_command_matches = command_object->HandleCompletion(request);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001805 }
1806 }
1807
1808 return num_command_matches;
1809}
1810
1811int CommandInterpreter::HandleCompletion(
1812 const char *current_line, const char *cursor, const char *last_char,
Raphael Isemann7f888292018-09-13 21:26:00 +00001813 int match_start_point, int max_return_elements, StringList &matches,
1814 StringList &descriptions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001815
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001816 llvm::StringRef command_line(current_line, last_char - current_line);
Raphael Isemann7f888292018-09-13 21:26:00 +00001817 CompletionResult result;
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001818 CompletionRequest request(command_line, cursor - current_line,
Raphael Isemann7f888292018-09-13 21:26:00 +00001819 match_start_point, max_return_elements, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001820 // Don't complete comments, and if the line we are completing is just the
Adrian Prantl05097242018-04-30 16:49:04 +00001821 // history repeat character, substitute the appropriate history line.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001822 const char *first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001823 if (first_arg) {
1824 if (first_arg[0] == m_comment_char)
1825 return 0;
1826 else if (first_arg[0] == CommandHistory::g_repeat_char) {
Zachary Turner53877af2016-11-18 23:22:42 +00001827 if (auto hist_str = m_command_history.FindString(first_arg)) {
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001828 matches.InsertStringAtIndex(0, *hist_str);
Raphael Isemann7f888292018-09-13 21:26:00 +00001829 descriptions.InsertStringAtIndex(0, "Previous command history event");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001830 return -2;
1831 } else
1832 return 0;
1833 }
1834 }
1835
Kate Stoneb9c1b512016-09-06 20:57:50 +00001836 // Only max_return_elements == -1 is supported at present:
Leonard Mosescu17ffd392017-10-05 23:41:28 +00001837 lldbassert(max_return_elements == -1);
Raphael Isemann2443bbd2018-07-02 21:29:56 +00001838
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001839 int num_command_matches = HandleCompletionMatches(request);
Raphael Isemann7f888292018-09-13 21:26:00 +00001840 result.GetMatches(matches);
1841 result.GetDescriptions(descriptions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001842
1843 if (num_command_matches <= 0)
1844 return num_command_matches;
1845
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001846 if (request.GetParsedLine().GetArgumentCount() == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001847 // If we got an empty string, insert nothing.
1848 matches.InsertStringAtIndex(0, "");
Raphael Isemann7f888292018-09-13 21:26:00 +00001849 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001850 } else {
1851 // Now figure out if there is a common substring, and if so put that in
Adrian Prantl05097242018-04-30 16:49:04 +00001852 // element 0, otherwise put an empty string in element 0.
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001853 std::string command_partial_str = request.GetCursorArgumentPrefix().str();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001854
1855 std::string common_prefix;
1856 matches.LongestCommonPrefix(common_prefix);
1857 const size_t partial_name_len = command_partial_str.size();
1858 common_prefix.erase(0, partial_name_len);
1859
Adrian Prantl05097242018-04-30 16:49:04 +00001860 // If we matched a unique single command, add a space... Only do this if
1861 // the completer told us this was a complete word, however...
Raphael Isemanna2e76c02018-07-13 18:28:14 +00001862 if (num_command_matches == 1 && request.GetWordComplete()) {
1863 char quote_char = request.GetParsedLine()[request.GetCursorIndex()].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001864 common_prefix =
1865 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1866 if (quote_char != '\0')
1867 common_prefix.push_back(quote_char);
1868 common_prefix.push_back(' ');
1869 }
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +00001870 matches.InsertStringAtIndex(0, common_prefix.c_str());
Raphael Isemann7f888292018-09-13 21:26:00 +00001871 descriptions.InsertStringAtIndex(0, "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001872 }
1873 return num_command_matches;
1874}
1875
1876CommandInterpreter::~CommandInterpreter() {}
1877
Zachary Turner514d8cd2016-09-23 18:06:53 +00001878void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001879 EventSP prompt_change_event_sp(
1880 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1881 ;
1882 BroadcastEvent(prompt_change_event_sp);
1883 if (m_command_io_handler_sp)
1884 m_command_io_handler_sp->SetPrompt(new_prompt);
1885}
1886
Zachary Turner7a120c82016-11-13 03:05:58 +00001887bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001888 // Check AutoConfirm first:
1889 if (m_debugger.GetAutoConfirm())
1890 return default_answer;
1891
1892 IOHandlerConfirm *confirm =
1893 new IOHandlerConfirm(m_debugger, message, default_answer);
1894 IOHandlerSP io_handler_sp(confirm);
1895 m_debugger.RunIOHandler(io_handler_sp);
1896 return confirm->GetResponse();
1897}
1898
Zachary Turnera483f572016-10-05 21:14:49 +00001899const CommandAlias *
1900CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001901 OptionArgVectorSP ret_val;
1902
Zachary Turnera483f572016-10-05 21:14:49 +00001903 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001904 if (pos != m_alias_dict.end())
1905 return (CommandAlias *)pos->second.get();
1906
1907 return nullptr;
1908}
1909
Zachary Turnera4496982016-10-05 21:14:38 +00001910bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001911
Zachary Turnera4496982016-10-05 21:14:38 +00001912bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001913
Zachary Turnera4496982016-10-05 21:14:38 +00001914bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001915
Zachary Turnera4496982016-10-05 21:14:38 +00001916bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001917
1918void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1919 const char *alias_name,
1920 Args &cmd_args,
1921 std::string &raw_input_string,
1922 CommandReturnObject &result) {
1923 OptionArgVectorSP option_arg_vector_sp =
1924 GetAlias(alias_name)->GetOptionArguments();
1925
1926 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1927
1928 // Make sure that the alias name is the 0th element in cmd_args
1929 std::string alias_name_str = alias_name;
1930 if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)
Zachary Turner5c725f32016-09-19 21:56:59 +00001931 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001932
1933 Args new_args(alias_cmd_obj->GetCommandName());
1934 if (new_args.GetArgumentCount() == 2)
1935 new_args.Shift();
1936
1937 if (option_arg_vector_sp.get()) {
1938 if (wants_raw_input) {
1939 // We have a command that both has command options and takes raw input.
Adrian Prantl05097242018-04-30 16:49:04 +00001940 // Make *sure* it has a " -- " in the right place in the
1941 // raw_input_string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001942 size_t pos = raw_input_string.find(" -- ");
1943 if (pos == std::string::npos) {
1944 // None found; assume it goes at the beginning of the raw input string
1945 raw_input_string.insert(0, " -- ");
1946 }
1947 }
1948
1949 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1950 const size_t old_size = cmd_args.GetArgumentCount();
1951 std::vector<bool> used(old_size + 1, false);
1952
1953 used[0] = true;
1954
Zachary Turner5c28c662016-10-03 23:20:36 +00001955 int value_type;
1956 std::string option;
1957 std::string value;
1958 for (const auto &option_entry : *option_arg_vector) {
1959 std::tie(option, value_type, value) = option_entry;
1960 if (option == "<argument>") {
1961 if (!wants_raw_input || (value != "--")) {
1962 // Since we inserted this above, make sure we don't insert it twice
1963 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001964 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001965 continue;
1966 }
1967
1968 if (value_type != OptionParser::eOptionalArgument)
1969 new_args.AppendArgument(option);
1970
1971 if (value == "<no-argument>")
1972 continue;
1973
1974 int index = GetOptionArgumentPosition(value.c_str());
1975 if (index == 0) {
1976 // value was NOT a positional argument; must be a real value
1977 if (value_type != OptionParser::eOptionalArgument)
1978 new_args.AppendArgument(value);
1979 else {
1980 char buffer[255];
1981 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1982 value.c_str());
1983 new_args.AppendArgument(llvm::StringRef(buffer));
1984 }
1985
1986 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1987 result.AppendErrorWithFormat("Not enough arguments provided; you "
1988 "need at least %d arguments to use "
1989 "this alias.\n",
1990 index);
1991 result.SetStatus(eReturnStatusFailed);
1992 return;
1993 } else {
1994 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1995 size_t strpos =
1996 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1997 if (strpos != std::string::npos) {
1998 raw_input_string = raw_input_string.erase(
1999 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2000 }
2001
2002 if (value_type != OptionParser::eOptionalArgument)
2003 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2004 else {
2005 char buffer[255];
2006 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2007 cmd_args.GetArgumentAtIndex(index));
2008 new_args.AppendArgument(buffer);
2009 }
2010 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002011 }
2012 }
2013
Zachary Turner97d2c402016-10-05 23:40:23 +00002014 for (auto entry : llvm::enumerate(cmd_args.entries())) {
Zachary Turner4eb84492017-03-13 17:12:12 +00002015 if (!used[entry.index()] && !wants_raw_input)
2016 new_args.AppendArgument(entry.value().ref);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002017 }
2018
2019 cmd_args.Clear();
2020 cmd_args.SetArguments(new_args.GetArgumentCount(),
2021 new_args.GetConstArgumentVector());
2022 } else {
2023 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2024 // This alias was not created with any options; nothing further needs to be
Adrian Prantl05097242018-04-30 16:49:04 +00002025 // done, unless it is a command that wants raw input, in which case we need
2026 // to clear the rest of the data from cmd_args, since its in the raw input
2027 // string.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002028 if (wants_raw_input) {
2029 cmd_args.Clear();
2030 cmd_args.SetArguments(new_args.GetArgumentCount(),
2031 new_args.GetConstArgumentVector());
2032 }
2033 return;
2034 }
2035
2036 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2037 return;
2038}
2039
2040int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2041 int position = 0; // Any string that isn't an argument position, i.e. '%'
2042 // followed by an integer, gets a position
2043 // of zero.
2044
2045 const char *cptr = in_string;
2046
2047 // Does it start with '%'
2048 if (cptr[0] == '%') {
2049 ++cptr;
2050
2051 // Is the rest of it entirely digits?
2052 if (isdigit(cptr[0])) {
2053 const char *start = cptr;
2054 while (isdigit(cptr[0]))
2055 ++cptr;
2056
Adrian Prantl05097242018-04-30 16:49:04 +00002057 // We've gotten to the end of the digits; are we at the end of the
2058 // string?
Kate Stoneb9c1b512016-09-06 20:57:50 +00002059 if (cptr[0] == '\0')
2060 position = atoi(start);
2061 }
2062 }
2063
2064 return position;
2065}
2066
2067void CommandInterpreter::SourceInitFile(bool in_cwd,
2068 CommandReturnObject &result) {
2069 FileSpec init_file;
2070 if (in_cwd) {
2071 ExecutionContext exe_ctx(GetExecutionContext());
2072 Target *target = exe_ctx.GetTargetPtr();
2073 if (target) {
2074 // In the current working directory we don't load any program specific
2075 // .lldbinit files, we only look for a ".lldbinit" file.
2076 if (m_skip_lldbinit_files)
2077 return;
2078
2079 LoadCWDlldbinitFile should_load =
2080 target->TargetProperties::GetLoadCWDlldbinitFile();
2081 if (should_load == eLoadCWDlldbinitWarn) {
2082 FileSpec dot_lldb(".lldbinit", true);
2083 llvm::SmallString<64> home_dir_path;
2084 llvm::sys::path::home_directory(home_dir_path);
2085 FileSpec homedir_dot_lldb(home_dir_path.c_str(), false);
2086 homedir_dot_lldb.AppendPathComponent(".lldbinit");
2087 homedir_dot_lldb.ResolvePath();
2088 if (dot_lldb.Exists() &&
2089 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2090 result.AppendErrorWithFormat(
2091 "There is a .lldbinit file in the current directory which is not "
2092 "being read.\n"
2093 "To silence this warning without sourcing in the local "
2094 ".lldbinit,\n"
2095 "add the following to the lldbinit file in your home directory:\n"
2096 " settings set target.load-cwd-lldbinit false\n"
2097 "To allow lldb to source .lldbinit files in the current working "
2098 "directory,\n"
2099 "set the value of this variable to true. Only do so if you "
2100 "understand and\n"
2101 "accept the security risk.");
2102 result.SetStatus(eReturnStatusFailed);
2103 return;
2104 }
2105 } else if (should_load == eLoadCWDlldbinitTrue) {
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002106 init_file.SetFile("./.lldbinit", true, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002107 }
2108 }
2109 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002110 // If we aren't looking in the current working directory we are looking in
2111 // the home directory. We will first see if there is an application
2112 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a "-"
2113 // and the name of the program. If this file doesn't exist, we fall back to
2114 // just the "~/.lldbinit" file. We also obey any requests to not load the
2115 // init files.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002116 llvm::SmallString<64> home_dir_path;
2117 llvm::sys::path::home_directory(home_dir_path);
2118 FileSpec profilePath(home_dir_path.c_str(), false);
2119 profilePath.AppendPathComponent(".lldbinit");
2120 std::string init_file_path = profilePath.GetPath();
2121
2122 if (m_skip_app_init_files == false) {
2123 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2124 const char *program_name = program_file_spec.GetFilename().AsCString();
2125
2126 if (program_name) {
2127 char program_init_file_name[PATH_MAX];
2128 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2129 "%s-%s", init_file_path.c_str(), program_name);
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002130 init_file.SetFile(program_init_file_name, true,
2131 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002132 if (!init_file.Exists())
2133 init_file.Clear();
2134 }
2135 }
2136
2137 if (!init_file && !m_skip_lldbinit_files)
Jonas Devlieghere937348c2018-06-13 22:08:14 +00002138 init_file.SetFile(init_file_path, false, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002139 }
2140
2141 // If the file exists, tell HandleCommand to 'source' it; this will do the
Adrian Prantl05097242018-04-30 16:49:04 +00002142 // actual broadcasting of the commands back to any appropriate listener (see
Kate Stoneb9c1b512016-09-06 20:57:50 +00002143 // CommandObjectSource::Execute for more details).
2144
2145 if (init_file.Exists()) {
2146 const bool saved_batch = SetBatchCommandMode(true);
2147 CommandInterpreterRunOptions options;
2148 options.SetSilent(true);
2149 options.SetStopOnError(false);
2150 options.SetStopOnContinue(true);
2151
2152 HandleCommandsFromFile(init_file,
2153 nullptr, // Execution context
2154 options, result);
2155 SetBatchCommandMode(saved_batch);
2156 } else {
2157 // nothing to be done if the file doesn't exist
2158 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2159 }
2160}
2161
2162const char *CommandInterpreter::GetCommandPrefix() {
2163 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2164 return prefix == NULL ? "" : prefix;
2165}
2166
2167PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2168 PlatformSP platform_sp;
2169 if (prefer_target_platform) {
2170 ExecutionContext exe_ctx(GetExecutionContext());
2171 Target *target = exe_ctx.GetTargetPtr();
2172 if (target)
2173 platform_sp = target->GetPlatform();
2174 }
2175
2176 if (!platform_sp)
2177 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2178 return platform_sp;
2179}
2180
2181void CommandInterpreter::HandleCommands(const StringList &commands,
2182 ExecutionContext *override_context,
2183 CommandInterpreterRunOptions &options,
2184 CommandReturnObject &result) {
2185 size_t num_lines = commands.GetSize();
2186
2187 // If we are going to continue past a "continue" then we need to run the
Adrian Prantl05097242018-04-30 16:49:04 +00002188 // commands synchronously. Make sure you reset this value anywhere you return
2189 // from the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002190
2191 bool old_async_execution = m_debugger.GetAsyncExecution();
2192
2193 // If we've been given an execution context, set it at the start, but don't
Adrian Prantl05097242018-04-30 16:49:04 +00002194 // keep resetting it or we will cause series of commands that change the
2195 // context, then do an operation that relies on that context to fail.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002196
2197 if (override_context != nullptr)
2198 UpdateExecutionContext(override_context);
2199
2200 if (!options.GetStopOnContinue()) {
2201 m_debugger.SetAsyncExecution(false);
2202 }
2203
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002204 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002205 const char *cmd = commands.GetStringAtIndex(idx);
2206 if (cmd[0] == '\0')
2207 continue;
2208
2209 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002210 // TODO: Add Stream support.
2211 result.AppendMessageWithFormat("%s %s\n",
2212 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002213 }
2214
2215 CommandReturnObject tmp_result;
2216 // If override_context is not NULL, pass no_context_switching = true for
2217 // HandleCommand() since we updated our context already.
2218
2219 // We might call into a regex or alias command, in which case the
Adrian Prantl05097242018-04-30 16:49:04 +00002220 // add_to_history will get lost. This m_command_source_depth dingus is the
2221 // way we turn off adding to the history in that case, so set it up here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002222 if (!options.GetAddToHistory())
2223 m_command_source_depth++;
2224 bool success =
2225 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2226 nullptr, /* override_context */
2227 true, /* repeat_on_empty_command */
2228 override_context != nullptr /* no_context_switching */);
2229 if (!options.GetAddToHistory())
2230 m_command_source_depth--;
2231
2232 if (options.GetPrintResults()) {
2233 if (tmp_result.Succeeded())
Zachary Turner03c9f362016-11-14 23:23:31 +00002234 result.AppendMessage(tmp_result.GetOutputData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 }
2236
2237 if (!success || !tmp_result.Succeeded()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002238 llvm::StringRef error_msg = tmp_result.GetErrorData();
2239 if (error_msg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002240 error_msg = "<unknown error>.\n";
2241 if (options.GetStopOnError()) {
2242 result.AppendErrorWithFormat(
2243 "Aborting reading of commands after command #%" PRIu64
2244 ": '%s' failed with %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00002245 (uint64_t)idx, cmd, error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002246 result.SetStatus(eReturnStatusFailed);
2247 m_debugger.SetAsyncExecution(old_async_execution);
2248 return;
2249 } else if (options.GetPrintResults()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002250 result.AppendMessageWithFormat(
2251 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2252 error_msg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002253 }
2254 }
2255
2256 if (result.GetImmediateOutputStream())
2257 result.GetImmediateOutputStream()->Flush();
2258
2259 if (result.GetImmediateErrorStream())
2260 result.GetImmediateErrorStream()->Flush();
2261
Adrian Prantl05097242018-04-30 16:49:04 +00002262 // N.B. Can't depend on DidChangeProcessState, because the state coming
2263 // into the command execution could be running (for instance in Breakpoint
2264 // Commands. So we check the return value to see if it is has running in
2265 // it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002266 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2267 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2268 if (options.GetStopOnContinue()) {
2269 // If we caused the target to proceed, and we're going to stop in that
Adrian Prantl05097242018-04-30 16:49:04 +00002270 // case, set the status in our real result before returning. This is
2271 // an error if the continue was not the last command in the set of
2272 // commands to be run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002273 if (idx != num_lines - 1)
2274 result.AppendErrorWithFormat(
2275 "Aborting reading of commands after command #%" PRIu64
2276 ": '%s' continued the target.\n",
2277 (uint64_t)idx + 1, cmd);
2278 else
2279 result.AppendMessageWithFormat("Command #%" PRIu64
2280 " '%s' continued the target.\n",
2281 (uint64_t)idx + 1, cmd);
2282
2283 result.SetStatus(tmp_result.GetStatus());
2284 m_debugger.SetAsyncExecution(old_async_execution);
2285
2286 return;
2287 }
2288 }
2289
2290 // Also check for "stop on crash here:
2291 bool should_stop = false;
2292 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2293 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2294 if (target_sp) {
2295 ProcessSP process_sp(target_sp->GetProcessSP());
2296 if (process_sp) {
2297 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2298 StopReason reason = thread_sp->GetStopReason();
2299 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2300 reason == eStopReasonInstrumentation) {
2301 should_stop = true;
2302 break;
2303 }
2304 }
2305 }
2306 }
2307 if (should_stop) {
2308 if (idx != num_lines - 1)
2309 result.AppendErrorWithFormat(
2310 "Aborting reading of commands after command #%" PRIu64
2311 ": '%s' stopped with a signal or exception.\n",
2312 (uint64_t)idx + 1, cmd);
2313 else
2314 result.AppendMessageWithFormat(
2315 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2316 (uint64_t)idx + 1, cmd);
2317
2318 result.SetStatus(tmp_result.GetStatus());
2319 m_debugger.SetAsyncExecution(old_async_execution);
2320
2321 return;
2322 }
2323 }
2324 }
2325
2326 result.SetStatus(eReturnStatusSuccessFinishResult);
2327 m_debugger.SetAsyncExecution(old_async_execution);
2328
2329 return;
2330}
2331
2332// Make flags that we can pass into the IOHandler so our delegates can do the
2333// right thing
2334enum {
2335 eHandleCommandFlagStopOnContinue = (1u << 0),
2336 eHandleCommandFlagStopOnError = (1u << 1),
2337 eHandleCommandFlagEchoCommand = (1u << 2),
Stefan Granitzc678ed72018-10-05 16:49:47 +00002338 eHandleCommandFlagEchoCommentCommand = (1u << 3),
2339 eHandleCommandFlagPrintResult = (1u << 4),
2340 eHandleCommandFlagStopOnCrash = (1u << 5)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002341};
2342
2343void CommandInterpreter::HandleCommandsFromFile(
2344 FileSpec &cmd_file, ExecutionContext *context,
2345 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2346 if (cmd_file.Exists()) {
2347 StreamFileSP input_file_sp(new StreamFile());
2348
2349 std::string cmd_file_path = cmd_file.GetPath();
Zachary Turner97206d52017-05-12 04:51:55 +00002350 Status error = input_file_sp->GetFile().Open(cmd_file_path.c_str(),
2351 File::eOpenOptionRead);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002352
2353 if (error.Success()) {
2354 Debugger &debugger = GetDebugger();
2355
2356 uint32_t flags = 0;
2357
2358 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2359 if (m_command_source_flags.empty()) {
2360 // Stop on continue by default
2361 flags |= eHandleCommandFlagStopOnContinue;
2362 } else if (m_command_source_flags.back() &
2363 eHandleCommandFlagStopOnContinue) {
2364 flags |= eHandleCommandFlagStopOnContinue;
2365 }
2366 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2367 flags |= eHandleCommandFlagStopOnContinue;
2368 }
2369
2370 if (options.m_stop_on_error == eLazyBoolCalculate) {
2371 if (m_command_source_flags.empty()) {
2372 if (GetStopCmdSourceOnError())
2373 flags |= eHandleCommandFlagStopOnError;
2374 } else if (m_command_source_flags.back() &
2375 eHandleCommandFlagStopOnError) {
2376 flags |= eHandleCommandFlagStopOnError;
2377 }
2378 } else if (options.m_stop_on_error == eLazyBoolYes) {
2379 flags |= eHandleCommandFlagStopOnError;
2380 }
2381
Stefan Granitzc678ed72018-10-05 16:49:47 +00002382 // stop-on-crash can only be set, if it is present in all levels of
2383 // pushed flag sets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002384 if (options.GetStopOnCrash()) {
2385 if (m_command_source_flags.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002386 flags |= eHandleCommandFlagStopOnCrash;
2387 } else if (m_command_source_flags.back() &
2388 eHandleCommandFlagStopOnCrash) {
2389 flags |= eHandleCommandFlagStopOnCrash;
2390 }
2391 }
2392
2393 if (options.m_echo_commands == eLazyBoolCalculate) {
2394 if (m_command_source_flags.empty()) {
2395 // Echo command by default
2396 flags |= eHandleCommandFlagEchoCommand;
2397 } else if (m_command_source_flags.back() &
2398 eHandleCommandFlagEchoCommand) {
2399 flags |= eHandleCommandFlagEchoCommand;
2400 }
2401 } else if (options.m_echo_commands == eLazyBoolYes) {
2402 flags |= eHandleCommandFlagEchoCommand;
2403 }
2404
Stefan Granitzc678ed72018-10-05 16:49:47 +00002405 // We will only ever ask for this flag, if we echo commands in general.
2406 if (options.m_echo_comment_commands == eLazyBoolCalculate) {
2407 if (m_command_source_flags.empty()) {
2408 // Echo comments by default
2409 flags |= eHandleCommandFlagEchoCommentCommand;
2410 } else if (m_command_source_flags.back() &
2411 eHandleCommandFlagEchoCommentCommand) {
2412 flags |= eHandleCommandFlagEchoCommentCommand;
2413 }
2414 } else if (options.m_echo_comment_commands == eLazyBoolYes) {
2415 flags |= eHandleCommandFlagEchoCommentCommand;
2416 }
2417
Kate Stoneb9c1b512016-09-06 20:57:50 +00002418 if (options.m_print_results == eLazyBoolCalculate) {
2419 if (m_command_source_flags.empty()) {
2420 // Print output by default
2421 flags |= eHandleCommandFlagPrintResult;
2422 } else if (m_command_source_flags.back() &
2423 eHandleCommandFlagPrintResult) {
2424 flags |= eHandleCommandFlagPrintResult;
2425 }
2426 } else if (options.m_print_results == eLazyBoolYes) {
2427 flags |= eHandleCommandFlagPrintResult;
2428 }
2429
2430 if (flags & eHandleCommandFlagPrintResult) {
2431 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2432 cmd_file_path.c_str());
2433 }
2434
Adrian Prantl05097242018-04-30 16:49:04 +00002435 // Used for inheriting the right settings when "command source" might
2436 // have nested "command source" commands
Kate Stoneb9c1b512016-09-06 20:57:50 +00002437 lldb::StreamFileSP empty_stream_sp;
2438 m_command_source_flags.push_back(flags);
2439 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2440 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2441 empty_stream_sp, // Pass in an empty stream so we inherit the top
2442 // input reader output stream
2443 empty_stream_sp, // Pass in an empty stream so we inherit the top
2444 // input reader error stream
2445 flags,
2446 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2447 // or written
Zachary Turner514d8cd2016-09-23 18:06:53 +00002448 debugger.GetPrompt(), llvm::StringRef(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00002449 false, // Not multi-line
2450 debugger.GetUseColor(), 0, *this));
2451 const bool old_async_execution = debugger.GetAsyncExecution();
2452
2453 // Set synchronous execution if we are not stopping on continue
2454 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2455 debugger.SetAsyncExecution(false);
2456
2457 m_command_source_depth++;
2458
2459 debugger.RunIOHandler(io_handler_sp);
2460 if (!m_command_source_flags.empty())
2461 m_command_source_flags.pop_back();
2462 m_command_source_depth--;
2463 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2464 debugger.SetAsyncExecution(old_async_execution);
2465 } else {
2466 result.AppendErrorWithFormat(
2467 "error: an error occurred read file '%s': %s\n",
2468 cmd_file_path.c_str(), error.AsCString());
2469 result.SetStatus(eReturnStatusFailed);
2470 }
2471
2472 } else {
2473 result.AppendErrorWithFormat(
2474 "Error reading commands from file %s - file not found.\n",
2475 cmd_file.GetFilename().AsCString("<Unknown>"));
2476 result.SetStatus(eReturnStatusFailed);
2477 return;
2478 }
2479}
2480
2481ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
Jim Ingham30bac792017-07-13 19:45:54 +00002482 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
Greg Clayton79040462016-12-09 01:21:14 +00002483 if (!m_script_interpreter_sp) {
2484 if (!can_create)
2485 return nullptr;
2486 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2487 m_script_interpreter_sp =
2488 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2489 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002490 return m_script_interpreter_sp.get();
2491}
2492
2493bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2494
2495void CommandInterpreter::SetSynchronous(bool value) {
2496 m_synchronous_execution = value;
2497}
2498
2499void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002500 llvm::StringRef prefix,
2501 llvm::StringRef help_text) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002502 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002503
Zachary Turner0ac5f982016-11-08 04:12:42 +00002504 size_t line_width_max = max_columns - prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002505 if (line_width_max < 16)
Zachary Turner0ac5f982016-11-08 04:12:42 +00002506 line_width_max = help_text.size() + prefix.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002507
Zachary Turner0ac5f982016-11-08 04:12:42 +00002508 strm.IndentMore(prefix.size());
2509 bool prefixed_yet = false;
2510 while (!help_text.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002511 // Prefix the first line, indent subsequent lines to line up
Zachary Turner0ac5f982016-11-08 04:12:42 +00002512 if (!prefixed_yet) {
2513 strm << prefix;
2514 prefixed_yet = true;
2515 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002516 strm.Indent();
Zachary Turner0ac5f982016-11-08 04:12:42 +00002517
2518 // Never print more than the maximum on one line.
2519 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2520
2521 // Always break on an explicit newline.
2522 std::size_t first_newline = this_line.find_first_of("\n");
2523
2524 // Don't break on space/tab unless the text is too long to fit on one line.
2525 std::size_t last_space = llvm::StringRef::npos;
2526 if (this_line.size() != help_text.size())
2527 last_space = this_line.find_last_of(" \t");
2528
2529 // Break at whichever condition triggered first.
2530 this_line = this_line.substr(0, std::min(first_newline, last_space));
2531 strm.PutCString(this_line);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002532 strm.EOL();
2533
Zachary Turner0ac5f982016-11-08 04:12:42 +00002534 // Remove whitespace / newlines after breaking.
2535 help_text = help_text.drop_front(this_line.size()).ltrim();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002536 }
Zachary Turner0ac5f982016-11-08 04:12:42 +00002537 strm.IndentLess(prefix.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002538}
2539
2540void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
Zachary Turner0ac5f982016-11-08 04:12:42 +00002541 llvm::StringRef word_text,
2542 llvm::StringRef separator,
2543 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002544 size_t max_word_len) {
2545 StreamString prefix_stream;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002546 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2547 (int)separator.size(), separator.data());
Zachary Turnerc1564272016-11-16 21:15:24 +00002548 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2549}
2550
Zachary Turner0ac5f982016-11-08 04:12:42 +00002551void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2552 llvm::StringRef separator,
2553 llvm::StringRef help_text,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002554 uint32_t max_word_len) {
Zachary Turner0ac5f982016-11-08 04:12:42 +00002555 int indent_size = max_word_len + separator.size() + 2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002556
2557 strm.IndentMore(indent_size);
2558
2559 StreamString text_strm;
Zachary Turner0ac5f982016-11-08 04:12:42 +00002560 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2561 text_strm << separator << " " << help_text;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002562
2563 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2564
Zachary Turnerc1564272016-11-16 21:15:24 +00002565 llvm::StringRef text = text_strm.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002566
2567 uint32_t chars_left = max_columns;
2568
Davide Italianocf8a8292017-04-14 22:36:08 +00002569 auto nextWordLength = [](llvm::StringRef S) {
2570 size_t pos = S.find_first_of(' ');
2571 return pos == llvm::StringRef::npos ? S.size() : pos;
2572 };
2573
Zachary Turnerc1564272016-11-16 21:15:24 +00002574 while (!text.empty()) {
2575 if (text.front() == '\n' ||
Jim Inghama81bd7f2017-07-27 00:18:18 +00002576 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002577 strm.EOL();
2578 strm.Indent();
Zachary Turnerc1564272016-11-16 21:15:24 +00002579 chars_left = max_columns - indent_size;
2580 if (text.front() == '\n')
2581 text = text.drop_front();
2582 else
2583 text = text.ltrim(' ');
Kate Stoneb9c1b512016-09-06 20:57:50 +00002584 } else {
Zachary Turnerc1564272016-11-16 21:15:24 +00002585 strm.PutChar(text.front());
2586 --chars_left;
2587 text = text.drop_front();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002588 }
2589 }
2590
2591 strm.EOL();
2592 strm.IndentLess(indent_size);
2593}
2594
2595void CommandInterpreter::FindCommandsForApropos(
Zachary Turner067d1db2016-11-16 21:45:04 +00002596 llvm::StringRef search_word, StringList &commands_found,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002597 StringList &commands_help, CommandObject::CommandMap &command_map) {
2598 CommandObject::CommandMap::const_iterator pos;
2599
2600 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
Zachary Turner067d1db2016-11-16 21:45:04 +00002601 llvm::StringRef command_name = pos->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002602 CommandObject *cmd_obj = pos->second.get();
2603
2604 const bool search_short_help = true;
2605 const bool search_long_help = false;
2606 const bool search_syntax = false;
2607 const bool search_options = false;
Zachary Turner067d1db2016-11-16 21:45:04 +00002608 if (command_name.contains_lower(search_word) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002609 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2610 search_long_help, search_syntax,
2611 search_options)) {
2612 commands_found.AppendString(cmd_obj->GetCommandName());
2613 commands_help.AppendString(cmd_obj->GetHelp());
2614 }
2615
2616 if (cmd_obj->IsMultiwordObject()) {
2617 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2618 FindCommandsForApropos(search_word, commands_found, commands_help,
2619 cmd_multiword->GetSubcommandDictionary());
2620 }
2621 }
2622}
2623
Zachary Turner067d1db2016-11-16 21:45:04 +00002624void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002625 StringList &commands_found,
2626 StringList &commands_help,
2627 bool search_builtin_commands,
2628 bool search_user_commands,
2629 bool search_alias_commands) {
2630 CommandObject::CommandMap::const_iterator pos;
2631
2632 if (search_builtin_commands)
2633 FindCommandsForApropos(search_word, commands_found, commands_help,
2634 m_command_dict);
2635
2636 if (search_user_commands)
2637 FindCommandsForApropos(search_word, commands_found, commands_help,
2638 m_user_dict);
2639
2640 if (search_alias_commands)
2641 FindCommandsForApropos(search_word, commands_found, commands_help,
2642 m_alias_dict);
2643}
2644
2645void CommandInterpreter::UpdateExecutionContext(
2646 ExecutionContext *override_context) {
2647 if (override_context != nullptr) {
2648 m_exe_ctx_ref = *override_context;
2649 } else {
2650 const bool adopt_selected = true;
2651 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2652 adopt_selected);
2653 }
2654}
2655
2656size_t CommandInterpreter::GetProcessOutput() {
2657 // The process has stuff waiting for stderr; get it and write it out to the
2658 // appropriate place.
2659 char stdio_buffer[1024];
2660 size_t len;
2661 size_t total_bytes = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002662 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002663 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2664 if (target_sp) {
2665 ProcessSP process_sp(target_sp->GetProcessSP());
2666 if (process_sp) {
2667 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2668 error)) > 0) {
2669 size_t bytes_written = len;
2670 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2671 total_bytes += len;
2672 }
2673 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2674 error)) > 0) {
2675 size_t bytes_written = len;
2676 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2677 total_bytes += len;
2678 }
2679 }
2680 }
2681 return total_bytes;
2682}
2683
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002684void CommandInterpreter::StartHandlingCommand() {
2685 auto idle_state = CommandHandlingState::eIdle;
2686 if (m_command_state.compare_exchange_strong(
2687 idle_state, CommandHandlingState::eInProgress))
2688 lldbassert(m_iohandler_nesting_level == 0);
2689 else
2690 lldbassert(m_iohandler_nesting_level > 0);
2691 ++m_iohandler_nesting_level;
2692}
2693
2694void CommandInterpreter::FinishHandlingCommand() {
2695 lldbassert(m_iohandler_nesting_level > 0);
2696 if (--m_iohandler_nesting_level == 0) {
2697 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2698 lldbassert(prev_state != CommandHandlingState::eIdle);
2699 }
2700}
2701
2702bool CommandInterpreter::InterruptCommand() {
2703 auto in_progress = CommandHandlingState::eInProgress;
2704 return m_command_state.compare_exchange_strong(
2705 in_progress, CommandHandlingState::eInterrupted);
2706}
2707
2708bool CommandInterpreter::WasInterrupted() const {
2709 bool was_interrupted =
2710 (m_command_state == CommandHandlingState::eInterrupted);
2711 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2712 return was_interrupted;
2713}
2714
2715void CommandInterpreter::PrintCommandOutput(Stream &stream,
2716 llvm::StringRef str) {
2717 // Split the output into lines and poll for interrupt requests
2718 const char *data = str.data();
2719 size_t size = str.size();
2720 while (size > 0 && !WasInterrupted()) {
2721 size_t chunk_size = 0;
2722 for (; chunk_size < size; ++chunk_size) {
2723 lldbassert(data[chunk_size] != '\0');
2724 if (data[chunk_size] == '\n') {
2725 ++chunk_size;
2726 break;
2727 }
2728 }
2729 chunk_size = stream.Write(data, chunk_size);
2730 lldbassert(size >= chunk_size);
2731 data += chunk_size;
2732 size -= chunk_size;
2733 }
2734 if (size > 0) {
2735 stream.Printf("\n... Interrupted.\n");
2736 }
2737}
2738
Stefan Granitzc678ed72018-10-05 16:49:47 +00002739bool CommandInterpreter::EchoCommandNonInteractive(
2740 llvm::StringRef line, const Flags &io_handler_flags) const {
2741 if (!io_handler_flags.Test(eHandleCommandFlagEchoCommand))
2742 return false;
2743
2744 llvm::StringRef command = line.trim();
2745 if (command.empty())
2746 return true;
2747
2748 if (command.front() == m_comment_char)
2749 return io_handler_flags.Test(eHandleCommandFlagEchoCommentCommand);
2750
2751 return true;
2752}
2753
Kate Stoneb9c1b512016-09-06 20:57:50 +00002754void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2755 std::string &line) {
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002756 // If we were interrupted, bail out...
2757 if (WasInterrupted())
2758 return;
2759
Kate Stoneb9c1b512016-09-06 20:57:50 +00002760 const bool is_interactive = io_handler.GetIsInteractive();
2761 if (is_interactive == false) {
2762 // When we are not interactive, don't execute blank lines. This will happen
2763 // sourcing a commands file. We don't want blank lines to repeat the
Adrian Prantl05097242018-04-30 16:49:04 +00002764 // previous command and cause any errors to occur (like redefining an
2765 // alias, get an error and stop parsing the commands file).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002766 if (line.empty())
2767 return;
2768
2769 // When using a non-interactive file handle (like when sourcing commands
Adrian Prantl05097242018-04-30 16:49:04 +00002770 // from a file) we need to echo the command out so we don't just see the
2771 // command output and no command...
Stefan Granitzc678ed72018-10-05 16:49:47 +00002772 if (EchoCommandNonInteractive(line, io_handler.GetFlags()))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002773 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2774 line.c_str());
2775 }
2776
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002777 StartHandlingCommand();
2778
Kate Stoneb9c1b512016-09-06 20:57:50 +00002779 lldb_private::CommandReturnObject result;
2780 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2781
2782 // Now emit the command output text from the command we just executed
2783 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2784 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2785 GetProcessOutput();
2786
2787 if (!result.GetImmediateOutputStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002788 llvm::StringRef output = result.GetOutputData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002789 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002790 }
2791
2792 // Now emit the command error text from the command we just executed
2793 if (!result.GetImmediateErrorStream()) {
Zachary Turnerc1564272016-11-16 21:15:24 +00002794 llvm::StringRef error = result.GetErrorData();
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002795 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002796 }
2797 }
2798
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002799 FinishHandlingCommand();
2800
Kate Stoneb9c1b512016-09-06 20:57:50 +00002801 switch (result.GetStatus()) {
2802 case eReturnStatusInvalid:
2803 case eReturnStatusSuccessFinishNoResult:
2804 case eReturnStatusSuccessFinishResult:
2805 case eReturnStatusStarted:
2806 break;
2807
2808 case eReturnStatusSuccessContinuingNoResult:
2809 case eReturnStatusSuccessContinuingResult:
2810 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2811 io_handler.SetIsDone(true);
2812 break;
2813
2814 case eReturnStatusFailed:
2815 m_num_errors++;
2816 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2817 io_handler.SetIsDone(true);
2818 break;
2819
2820 case eReturnStatusQuit:
2821 m_quit_requested = true;
2822 io_handler.SetIsDone(true);
2823 break;
2824 }
2825
2826 // Finally, if we're going to stop on crash, check that here:
2827 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2828 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2829 bool should_stop = false;
2830 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2831 if (target_sp) {
2832 ProcessSP process_sp(target_sp->GetProcessSP());
2833 if (process_sp) {
2834 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2835 StopReason reason = thread_sp->GetStopReason();
2836 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2837 reason == eStopReasonInstrumentation) &&
2838 !result.GetAbnormalStopWasExpected()) {
2839 should_stop = true;
2840 break;
2841 }
2842 }
2843 }
2844 }
2845 if (should_stop) {
2846 io_handler.SetIsDone(true);
2847 m_stopped_for_crash = true;
2848 }
2849 }
2850}
2851
2852bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2853 ExecutionContext exe_ctx(GetExecutionContext());
2854 Process *process = exe_ctx.GetProcessPtr();
2855
Leonard Mosescu17ffd392017-10-05 23:41:28 +00002856 if (InterruptCommand())
2857 return true;
2858
Kate Stoneb9c1b512016-09-06 20:57:50 +00002859 if (process) {
2860 StateType state = process->GetState();
2861 if (StateIsRunningState(state)) {
2862 process->Halt();
2863 return true; // Don't do any updating when we are running
2864 }
2865 }
2866
2867 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2868 if (script_interpreter) {
2869 if (script_interpreter->Interrupt())
2870 return true;
2871 }
2872 return false;
2873}
2874
2875void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2876 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2877 void *baton) {
2878 Debugger &debugger = GetDebugger();
2879 IOHandlerSP io_handler_sp(
2880 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2881 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002882 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2883 llvm::StringRef(), // Continuation prompt
2884 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002885 debugger.GetUseColor(),
2886 0, // Don't show line numbers
2887 delegate)); // IOHandlerDelegate
2888
2889 if (io_handler_sp) {
2890 io_handler_sp->SetUserData(baton);
2891 if (asynchronously)
2892 debugger.PushIOHandler(io_handler_sp);
2893 else
2894 debugger.RunIOHandler(io_handler_sp);
2895 }
2896}
2897
2898void CommandInterpreter::GetPythonCommandsFromIOHandler(
2899 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2900 void *baton) {
2901 Debugger &debugger = GetDebugger();
2902 IOHandlerSP io_handler_sp(
2903 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2904 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002905 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2906 llvm::StringRef(), // Continuation prompt
2907 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002908 debugger.GetUseColor(),
2909 0, // Don't show line numbers
2910 delegate)); // IOHandlerDelegate
2911
2912 if (io_handler_sp) {
2913 io_handler_sp->SetUserData(baton);
2914 if (asynchronously)
2915 debugger.PushIOHandler(io_handler_sp);
2916 else
2917 debugger.RunIOHandler(io_handler_sp);
2918 }
2919}
2920
2921bool CommandInterpreter::IsActive() {
2922 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2923}
2924
2925lldb::IOHandlerSP
2926CommandInterpreter::GetIOHandler(bool force_create,
2927 CommandInterpreterRunOptions *options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002928 // Always re-create the IOHandlerEditline in case the input changed. The old
2929 // instance might have had a non-interactive input and now it does or vice
2930 // versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002931 if (force_create || !m_command_io_handler_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002932 // Always re-create the IOHandlerEditline in case the input changed. The
2933 // old instance might have had a non-interactive input and now it does or
2934 // vice versa.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002935 uint32_t flags = 0;
2936
2937 if (options) {
2938 if (options->m_stop_on_continue == eLazyBoolYes)
2939 flags |= eHandleCommandFlagStopOnContinue;
2940 if (options->m_stop_on_error == eLazyBoolYes)
2941 flags |= eHandleCommandFlagStopOnError;
2942 if (options->m_stop_on_crash == eLazyBoolYes)
2943 flags |= eHandleCommandFlagStopOnCrash;
2944 if (options->m_echo_commands != eLazyBoolNo)
2945 flags |= eHandleCommandFlagEchoCommand;
Stefan Granitzc678ed72018-10-05 16:49:47 +00002946 if (options->m_echo_comment_commands != eLazyBoolNo)
2947 flags |= eHandleCommandFlagEchoCommentCommand;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002948 if (options->m_print_results != eLazyBoolNo)
2949 flags |= eHandleCommandFlagPrintResult;
2950 } else {
2951 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2952 }
2953
2954 m_command_io_handler_sp.reset(new IOHandlerEditline(
2955 m_debugger, IOHandler::Type::CommandInterpreter,
2956 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2957 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002958 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002959 false, // Don't enable multiple line input, just single line commands
2960 m_debugger.GetUseColor(),
2961 0, // Don't show line numbers
2962 *this));
2963 }
2964 return m_command_io_handler_sp;
2965}
2966
2967void CommandInterpreter::RunCommandInterpreter(
2968 bool auto_handle_events, bool spawn_thread,
2969 CommandInterpreterRunOptions &options) {
Adrian Prantl05097242018-04-30 16:49:04 +00002970 // Always re-create the command interpreter when we run it in case any file
2971 // handles have changed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002972 bool force_create = true;
2973 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2974 m_stopped_for_crash = false;
2975
2976 if (auto_handle_events)
2977 m_debugger.StartEventHandlerThread();
2978
2979 if (spawn_thread) {
2980 m_debugger.StartIOHandlerThread();
2981 } else {
2982 m_debugger.ExecuteIOHandlers();
2983
2984 if (auto_handle_events)
2985 m_debugger.StopEventHandlerThread();
2986 }
2987}
2988
2989CommandObject *
2990CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2991 CommandReturnObject &result) {
2992 std::string scratch_command(command_line); // working copy so we don't modify
2993 // command_line unless we succeed
2994 CommandObject *cmd_obj = nullptr;
2995 StreamString revised_command_line;
2996 bool wants_raw_input = false;
2997 size_t actual_cmd_name_len = 0;
2998 std::string next_word;
2999 StringList matches;
3000 bool done = false;
3001 while (!done) {
3002 char quote_char = '\0';
3003 std::string suffix;
3004 ExtractCommand(scratch_command, next_word, suffix, quote_char);
3005 if (cmd_obj == nullptr) {
3006 std::string full_name;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003007 bool is_alias = GetAliasFullName(next_word, full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00003008 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003009 bool is_real_command =
3010 (is_alias == false) ||
3011 (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
3012 if (!is_real_command) {
3013 matches.Clear();
3014 std::string alias_result;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003015 cmd_obj =
3016 BuildAliasResult(full_name, scratch_command, alias_result, result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003017 revised_command_line.Printf("%s", alias_result.c_str());
3018 if (cmd_obj) {
3019 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00003020 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003021 }
3022 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003023 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00003024 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
3025 actual_cmd_name_len += cmd_name.size();
3026 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003027 wants_raw_input = cmd_obj->WantsRawCommandString();
3028 } else {
3029 revised_command_line.Printf("%s", next_word.c_str());
3030 }
3031 }
3032 } else {
3033 if (cmd_obj->IsMultiwordObject()) {
3034 CommandObject *sub_cmd_obj =
3035 cmd_obj->GetSubcommandObject(next_word.c_str());
3036 if (sub_cmd_obj) {
Adrian Prantl05097242018-04-30 16:49:04 +00003037 // The subcommand's name includes the parent command's name, so
3038 // restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00003039 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3040 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003041 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00003042 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003043 cmd_obj = sub_cmd_obj;
3044 wants_raw_input = cmd_obj->WantsRawCommandString();
3045 } else {
3046 if (quote_char)
3047 revised_command_line.Printf(" %c%s%s%c", quote_char,
3048 next_word.c_str(), suffix.c_str(),
3049 quote_char);
3050 else
3051 revised_command_line.Printf(" %s%s", next_word.c_str(),
3052 suffix.c_str());
3053 done = true;
3054 }
3055 } else {
3056 if (quote_char)
3057 revised_command_line.Printf(" %c%s%s%c", quote_char,
3058 next_word.c_str(), suffix.c_str(),
3059 quote_char);
3060 else
3061 revised_command_line.Printf(" %s%s", next_word.c_str(),
3062 suffix.c_str());
3063 done = true;
3064 }
3065 }
3066
3067 if (cmd_obj == nullptr) {
3068 const size_t num_matches = matches.GetSize();
3069 if (matches.GetSize() > 1) {
3070 StreamString error_msg;
3071 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3072 next_word.c_str());
3073
3074 for (uint32_t i = 0; i < num_matches; ++i) {
3075 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3076 }
Zachary Turnerc1564272016-11-16 21:15:24 +00003077 result.AppendRawError(error_msg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003078 } else {
3079 // We didn't have only one match, otherwise we wouldn't get here.
Leonard Mosescu17ffd392017-10-05 23:41:28 +00003080 lldbassert(num_matches == 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003081 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3082 next_word.c_str());
3083 }
3084 result.SetStatus(eReturnStatusFailed);
3085 return nullptr;
3086 }
3087
3088 if (cmd_obj->IsMultiwordObject()) {
3089 if (!suffix.empty()) {
3090 result.AppendErrorWithFormat(
3091 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3092 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003093 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003094 next_word.empty() ? "" : next_word.c_str(),
3095 next_word.empty() ? " -- " : " ", suffix.c_str());
3096 result.SetStatus(eReturnStatusFailed);
3097 return nullptr;
3098 }
3099 } else {
3100 // If we found a normal command, we are done
3101 done = true;
3102 if (!suffix.empty()) {
3103 switch (suffix[0]) {
3104 case '/':
3105 // GDB format suffixes
3106 {
3107 Options *command_options = cmd_obj->GetOptions();
3108 if (command_options &&
3109 command_options->SupportsLongOption("gdb-format")) {
3110 std::string gdb_format_option("--gdb-format=");
3111 gdb_format_option += (suffix.c_str() + 1);
3112
Zachary Turnerc1564272016-11-16 21:15:24 +00003113 std::string cmd = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003114 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3115 if (arg_terminator_idx != std::string::npos) {
3116 // Insert the gdb format option before the "--" that terminates
3117 // options
3118 gdb_format_option.append(1, ' ');
3119 cmd.insert(arg_terminator_idx, gdb_format_option);
Zachary Turnerc1564272016-11-16 21:15:24 +00003120 revised_command_line.Clear();
3121 revised_command_line.PutCString(cmd);
3122 } else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003123 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3124
3125 if (wants_raw_input &&
3126 FindArgumentTerminator(cmd) == std::string::npos)
3127 revised_command_line.PutCString(" --");
3128 } else {
3129 result.AppendErrorWithFormat(
3130 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003131 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003132 result.SetStatus(eReturnStatusFailed);
3133 return nullptr;
3134 }
3135 }
3136 break;
3137
3138 default:
3139 result.AppendErrorWithFormat(
3140 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3141 result.SetStatus(eReturnStatusFailed);
3142 return nullptr;
3143 }
3144 }
3145 }
3146 if (scratch_command.empty())
3147 done = true;
3148 }
3149
3150 if (!scratch_command.empty())
3151 revised_command_line.Printf(" %s", scratch_command.c_str());
3152
3153 if (cmd_obj != NULL)
Zachary Turnerc1564272016-11-16 21:15:24 +00003154 command_line = revised_command_line.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003155
3156 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003157}