blob: 1850f8739ada9a7cf0969831bdb1fab9e4eee9a4 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Kate Stoneb9c1b512016-09-06 20:57:50 +000010#include <stdlib.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000011#include <string>
Caroline Tice4ab31c92010-10-12 21:57:09 +000012#include <vector>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013
Greg Clayton4a33d312011-06-23 17:59:56 +000014#include "CommandObjectScript.h"
Peter Collingbourne08405b62011-06-23 20:37:26 +000015#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000016
Eli Friedman3afb70c2010-06-13 02:17:17 +000017#include "../Commands/CommandObjectApropos.h"
18#include "../Commands/CommandObjectArgs.h"
19#include "../Commands/CommandObjectBreakpoint.h"
Tamas Berghammer3937bc62015-07-02 10:03:37 +000020#include "../Commands/CommandObjectBugreport.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000021#include "../Commands/CommandObjectCommands.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000022#include "../Commands/CommandObjectDisassemble.h"
23#include "../Commands/CommandObjectExpression.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000024#include "../Commands/CommandObjectFrame.h"
Greg Clayton44d93782014-01-27 23:43:24 +000025#include "../Commands/CommandObjectGUI.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectHelp.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000027#include "../Commands/CommandObjectLanguage.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000028#include "../Commands/CommandObjectLog.h"
29#include "../Commands/CommandObjectMemory.h"
Greg Claytonded470d2011-03-19 01:12:21 +000030#include "../Commands/CommandObjectPlatform.h"
Enrico Granata21dfcd92012-09-28 23:57:51 +000031#include "../Commands/CommandObjectPlugin.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000032#include "../Commands/CommandObjectProcess.h"
33#include "../Commands/CommandObjectQuit.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectRegister.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSettings.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000036#include "../Commands/CommandObjectSource.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000037#include "../Commands/CommandObjectSyntax.h"
38#include "../Commands/CommandObjectTarget.h"
39#include "../Commands/CommandObjectThread.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000040#include "../Commands/CommandObjectType.h"
Johnny Chen31c39da2010-12-23 20:21:44 +000041#include "../Commands/CommandObjectVersion.h"
Johnny Chenf04ee932011-09-22 18:04:58 +000042#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044#include "lldb/Core/Debugger.h"
Enrico Granatab5887262012-10-29 21:18:03 +000045#include "lldb/Core/Log.h"
Zachary Turner2c1f46d2015-07-30 20:28:07 +000046#include "lldb/Core/PluginManager.h"
Greg Claytonf0066ad2014-05-02 00:45:31 +000047#include "lldb/Core/State.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048#include "lldb/Core/Stream.h"
Greg Clayton44d93782014-01-27 23:43:24 +000049#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000050#include "lldb/Core/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000051
Todd Fialacacde7d2014-09-27 16:54:22 +000052#ifndef LLDB_DISABLE_LIBEDIT
Greg Clayton44d93782014-01-27 23:43:24 +000053#include "lldb/Host/Editline.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000054#endif
Greg Clayton7fb56d02011-02-01 01:31:41 +000055#include "lldb/Host/Host.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000056#include "lldb/Host/HostInfo.h"
Enrico Granatab5887262012-10-29 21:18:03 +000057
58#include "lldb/Interpreter/Args.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000059#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000060#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000061#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000062#include "lldb/Interpreter/OptionValueProperties.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000063#include "lldb/Interpreter/Options.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000064#include "lldb/Interpreter/Property.h"
Enrico Granatab5887262012-10-29 21:18:03 +000065
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000067#include "lldb/Target/TargetList.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000068#include "lldb/Target/Thread.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000069
Enrico Granatab5887262012-10-29 21:18:03 +000070#include "lldb/Utility/CleanUp.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000071
Saleem Abdulrasool28606952014-06-27 05:17:41 +000072#include "llvm/ADT/STLExtras.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000073#include "llvm/ADT/SmallString.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000074#include "llvm/Support/Path.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000075
Chris Lattner30fdc8d2010-06-08 16:52:24 +000076using namespace lldb;
77using namespace lldb_private;
78
Adrian McCarthy2304b6f2015-04-23 20:00:25 +000079static const char *k_white_space = " \t\v";
Greg Clayton754a9362012-08-23 00:22:02 +000080
Kate Stoneb9c1b512016-09-06 20:57:50 +000081static PropertyDefinition g_properties[] = {
82 {"expand-regex-aliases", OptionValue::eTypeBoolean, true, false, nullptr,
83 nullptr, "If true, regular expression alias commands will show the "
84 "expanded command that will be executed. This can be used to "
85 "debug new regular expression alias commands."},
86 {"prompt-on-quit", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
87 "If true, LLDB will prompt you before quitting if there are any live "
88 "processes being debugged. If false, LLDB will quit without asking in any "
89 "case."},
90 {"stop-command-source-on-error", OptionValue::eTypeBoolean, true, true,
91 nullptr, nullptr, "If true, LLDB will stop running a 'command source' "
92 "script upon encountering an error."},
93 {"space-repl-prompts", OptionValue::eTypeBoolean, true, false, nullptr,
94 nullptr,
95 "If true, blank lines will be printed between between REPL submissions."},
96 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
97
98enum {
99 ePropertyExpandRegexAliases = 0,
100 ePropertyPromptOnQuit = 1,
101 ePropertyStopCmdSourceOnError = 2,
102 eSpaceReplPrompts = 3
Greg Clayton754a9362012-08-23 00:22:02 +0000103};
104
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105ConstString &CommandInterpreter::GetStaticBroadcasterClass() {
106 static ConstString class_name("lldb.commandInterpreter");
107 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000108}
109
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110CommandInterpreter::CommandInterpreter(Debugger &debugger,
111 ScriptLanguage script_language,
112 bool synchronous_execution)
113 : Broadcaster(debugger.GetBroadcasterManager(),
114 CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
115 Properties(OptionValuePropertiesSP(
116 new OptionValueProperties(ConstString("interpreter")))),
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000117 IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118 m_debugger(debugger), m_synchronous_execution(synchronous_execution),
119 m_skip_lldbinit_files(false), m_skip_app_init_files(false),
120 m_script_interpreter_sp(), m_command_io_handler_sp(), m_comment_char('#'),
121 m_batch_command_mode(false), m_truncation_warning(eNoTruncation),
122 m_command_source_depth(0), m_num_errors(0), m_quit_requested(false),
123 m_stopped_for_crash(false) {
124 debugger.SetScriptLanguage(script_language);
125 SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit");
126 SetEventName(eBroadcastBitResetPrompt, "reset-prompt");
127 SetEventName(eBroadcastBitQuitCommandReceived, "quit");
128 CheckInWithManager();
129 m_collection_sp->Initialize(g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000130}
131
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132bool CommandInterpreter::GetExpandRegexAliases() const {
133 const uint32_t idx = ePropertyExpandRegexAliases;
134 return m_collection_sp->GetPropertyAtIndexAsBoolean(
135 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000136}
137
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138bool CommandInterpreter::GetPromptOnQuit() const {
139 const uint32_t idx = ePropertyPromptOnQuit;
140 return m_collection_sp->GetPropertyAtIndexAsBoolean(
141 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000142}
Greg Clayton754a9362012-08-23 00:22:02 +0000143
Kate Stoneb9c1b512016-09-06 20:57:50 +0000144void CommandInterpreter::SetPromptOnQuit(bool b) {
145 const uint32_t idx = ePropertyPromptOnQuit;
146 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ilia Kacf28be2015-03-23 22:45:13 +0000147}
148
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149void CommandInterpreter::ResolveCommand(const char *command_line,
150 CommandReturnObject &result) {
151 std::string command = command_line;
152 if (ResolveCommandImpl(command, result) != nullptr) {
153 result.AppendMessageWithFormat("%s", command.c_str());
154 result.SetStatus(eReturnStatusSuccessFinishResult);
155 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000156}
157
Kate Stoneb9c1b512016-09-06 20:57:50 +0000158bool CommandInterpreter::GetStopCmdSourceOnError() const {
159 const uint32_t idx = ePropertyStopCmdSourceOnError;
160 return m_collection_sp->GetPropertyAtIndexAsBoolean(
161 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000162}
163
Kate Stoneb9c1b512016-09-06 20:57:50 +0000164bool CommandInterpreter::GetSpaceReplPrompts() const {
165 const uint32_t idx = eSpaceReplPrompts;
166 return m_collection_sp->GetPropertyAtIndexAsBoolean(
167 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callanan66810412015-10-19 23:11:07 +0000168}
169
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170void CommandInterpreter::Initialize() {
171 Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000172
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173 CommandReturnObject result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000174
Kate Stoneb9c1b512016-09-06 20:57:50 +0000175 LoadCommandDictionary();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000176
Kate Stoneb9c1b512016-09-06 20:57:50 +0000177 // An alias arguments vector to reuse - reset it before use...
178 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
179
180 // Set up some initial aliases.
181 CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
182 if (cmd_obj_sp) {
183 AddAlias("q", cmd_obj_sp);
184 AddAlias("exit", cmd_obj_sp);
185 }
186
187 cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
188 if (cmd_obj_sp)
189 AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
190
191 cmd_obj_sp = GetCommandSPExact("process detach", false);
192 if (cmd_obj_sp) {
193 AddAlias("detach", cmd_obj_sp);
194 }
195
196 cmd_obj_sp = GetCommandSPExact("process continue", false);
197 if (cmd_obj_sp) {
198 AddAlias("c", cmd_obj_sp);
199 AddAlias("continue", cmd_obj_sp);
200 }
201
202 cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
203 if (cmd_obj_sp)
204 AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
205
206 cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
207 if (cmd_obj_sp)
208 AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
209
210 cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
211 if (cmd_obj_sp) {
212 AddAlias("stepi", cmd_obj_sp);
213 AddAlias("si", cmd_obj_sp);
214 }
215
216 cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
217 if (cmd_obj_sp) {
218 AddAlias("nexti", cmd_obj_sp);
219 AddAlias("ni", cmd_obj_sp);
220 }
221
222 cmd_obj_sp = GetCommandSPExact("thread step-in", false);
223 if (cmd_obj_sp) {
224 AddAlias("s", cmd_obj_sp);
225 AddAlias("step", cmd_obj_sp);
226 CommandAlias *sif_alias = AddAlias(
227 "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
228 if (sif_alias) {
229 sif_alias->SetHelp("Step through the current block, stopping if you step "
230 "directly into a function whose name matches the "
231 "TargetFunctionName.");
232 sif_alias->SetSyntax("sif <TargetFunctionName>");
Caroline Ticeca90c472011-05-06 21:37:15 +0000233 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000235
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236 cmd_obj_sp = GetCommandSPExact("thread step-over", false);
237 if (cmd_obj_sp) {
238 AddAlias("n", cmd_obj_sp);
239 AddAlias("next", cmd_obj_sp);
240 }
241
242 cmd_obj_sp = GetCommandSPExact("thread step-out", false);
243 if (cmd_obj_sp) {
244 AddAlias("finish", cmd_obj_sp);
245 }
246
247 cmd_obj_sp = GetCommandSPExact("frame select", false);
248 if (cmd_obj_sp) {
249 AddAlias("f", cmd_obj_sp);
250 }
251
252 cmd_obj_sp = GetCommandSPExact("thread select", false);
253 if (cmd_obj_sp) {
254 AddAlias("t", cmd_obj_sp);
255 }
256
257 cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
258 if (cmd_obj_sp) {
259 AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
260 AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
261 }
262
263 cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
264 if (cmd_obj_sp) {
265 AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
266 AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
267 }
268
269 cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
270 if (cmd_obj_sp)
271 AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
272
273 cmd_obj_sp = GetCommandSPExact("memory read", false);
274 if (cmd_obj_sp)
275 AddAlias("x", cmd_obj_sp);
276
277 cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
278 if (cmd_obj_sp)
279 AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
280
281 cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
282 if (cmd_obj_sp)
283 AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
284
285 cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
286 if (cmd_obj_sp)
287 AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
288
289 cmd_obj_sp = GetCommandSPExact("disassemble", false);
290 if (cmd_obj_sp)
291 AddAlias("dis", cmd_obj_sp);
292
293 cmd_obj_sp = GetCommandSPExact("disassemble", false);
294 if (cmd_obj_sp)
295 AddAlias("di", cmd_obj_sp);
296
297 cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
298 if (cmd_obj_sp)
299 AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
300
301 cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
302 if (cmd_obj_sp)
303 AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
304
305 cmd_obj_sp = GetCommandSPExact("target create", false);
306 if (cmd_obj_sp)
307 AddAlias("file", cmd_obj_sp);
308
309 cmd_obj_sp = GetCommandSPExact("target modules", false);
310 if (cmd_obj_sp)
311 AddAlias("image", cmd_obj_sp);
312
313 alias_arguments_vector_sp.reset(new OptionArgVector);
314
315 cmd_obj_sp = GetCommandSPExact("expression", false);
316 if (cmd_obj_sp) {
317 AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
318 AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
319 AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
320 if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
321 po->SetHelp("Evaluate an expression on the current thread. Displays any "
322 "returned value with formatting "
323 "controlled by the type's author.");
324 po->SetHelpLong("");
Johnny Chen6d675242012-08-24 18:15:45 +0000325 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326 AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
327 AddAlias("poarray", cmd_obj_sp,
328 "--object-description --element-count %1 --")
329 ->SetHelpLong("");
330 }
Johnny Chen6d675242012-08-24 18:15:45 +0000331
Kate Stoneb9c1b512016-09-06 20:57:50 +0000332 cmd_obj_sp = GetCommandSPExact("process kill", false);
333 if (cmd_obj_sp) {
334 AddAlias("kill", cmd_obj_sp);
335 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000336
Kate Stoneb9c1b512016-09-06 20:57:50 +0000337 cmd_obj_sp = GetCommandSPExact("process launch", false);
338 if (cmd_obj_sp) {
Chaoren Lin6fc5c7f2016-02-26 03:36:27 +0000339 alias_arguments_vector_sp.reset(new OptionArgVector);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
341 AddAlias("r", cmd_obj_sp, "--");
342 AddAlias("run", cmd_obj_sp, "--");
Jason Molenda85da3122012-07-06 02:46:23 +0000343#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344#if defined(__APPLE__)
345 std::string shell_option;
346 shell_option.append("--shell-expand-args");
347 shell_option.append(" true");
348 shell_option.append(" --");
349 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
350 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
351#else
352 StreamString defaultshell;
353 defaultshell.Printf("--shell=%s --",
354 HostInfo::GetDefaultShell().GetPath().c_str());
355 AddAlias("r", cmd_obj_sp, defaultshell.GetData());
356 AddAlias("run", cmd_obj_sp, defaultshell.GetData());
Jason Molenda85da3122012-07-06 02:46:23 +0000357#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358#endif
359 }
360
361 cmd_obj_sp = GetCommandSPExact("target symbols add", false);
362 if (cmd_obj_sp) {
363 AddAlias("add-dsym", cmd_obj_sp);
364 }
365
366 cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
367 if (cmd_obj_sp) {
368 AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
369 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000370}
371
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372void CommandInterpreter::Clear() {
373 m_command_io_handler_sp.reset();
Zachary Turner2c1f46d2015-07-30 20:28:07 +0000374
Kate Stoneb9c1b512016-09-06 20:57:50 +0000375 if (m_script_interpreter_sp)
376 m_script_interpreter_sp->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000377}
378
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
380 // This function has not yet been implemented.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000381
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382 // Look for any embedded script command
383 // If found,
384 // get interpreter object from the command dictionary,
385 // call execute_one_command on it,
386 // get the results as a string,
387 // substitute that string for current stuff.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000388
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389 return arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000390}
391
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392void CommandInterpreter::LoadCommandDictionary() {
393 Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000394
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
398 m_command_dict["breakpoint"] =
399 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
400 m_command_dict["bugreport"] =
401 CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
402 m_command_dict["command"] =
403 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
404 m_command_dict["disassemble"] =
405 CommandObjectSP(new CommandObjectDisassemble(*this));
406 m_command_dict["expression"] =
407 CommandObjectSP(new CommandObjectExpression(*this));
408 m_command_dict["frame"] =
409 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
410 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
411 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
412 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
413 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
414 m_command_dict["platform"] =
415 CommandObjectSP(new CommandObjectPlatform(*this));
416 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
417 m_command_dict["process"] =
418 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
419 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
420 m_command_dict["register"] =
421 CommandObjectSP(new CommandObjectRegister(*this));
422 m_command_dict["script"] =
423 CommandObjectSP(new CommandObjectScript(*this, script_language));
424 m_command_dict["settings"] =
425 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
426 m_command_dict["source"] =
427 CommandObjectSP(new CommandObjectMultiwordSource(*this));
428 m_command_dict["target"] =
429 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
430 m_command_dict["thread"] =
431 CommandObjectSP(new CommandObjectMultiwordThread(*this));
432 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
433 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
434 m_command_dict["watchpoint"] =
435 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
436 m_command_dict["language"] =
437 CommandObjectSP(new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000438
Kate Stoneb9c1b512016-09-06 20:57:50 +0000439 const char *break_regexes[][2] = {
440 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
441 "breakpoint set --file '%1' --line %2"},
442 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
443 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
444 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
445 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
446 "breakpoint set --name '%1'"},
447 {"^(-.*)$", "breakpoint set %1"},
448 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
449 "breakpoint set --name '%2' --shlib '%1'"},
450 {"^\\&(.*[^[:space:]])[[:space:]]*$",
451 "breakpoint set --name '%1' --skip-prologue=0"},
452 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
453 "breakpoint set --name '%1'"}};
Kate Stone7428a182016-07-14 22:03:10 +0000454
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000456
Kate Stoneb9c1b512016-09-06 20:57:50 +0000457 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap(
458 new CommandObjectRegexCommand(
459 *this, "_regexp-break",
460 "Set a breakpoint using one of several shorthand formats.\n",
461 "\n"
462 "_regexp-break <filename>:<linenum>\n"
463 " main.c:12 // Break at line 12 of "
464 "main.c\n\n"
465 "_regexp-break <linenum>\n"
466 " 12 // Break at line 12 of current "
467 "file\n\n"
468 "_regexp-break 0x<address>\n"
469 " 0x1234000 // Break at address "
470 "0x1234000\n\n"
471 "_regexp-break <name>\n"
472 " main // Break in 'main' after the "
473 "prologue\n\n"
474 "_regexp-break &<name>\n"
475 " &main // Break at first instruction "
476 "in 'main'\n\n"
477 "_regexp-break <module>`<name>\n"
478 " libc.so`malloc // Break in 'malloc' from "
479 "'libc.so'\n\n"
480 "_regexp-break /<source-regex>/\n"
481 " /break here/ // Break on source lines in "
482 "current file\n"
483 " // containing text 'break "
484 "here'.\n",
485 2, CommandCompletions::eSymbolCompletion |
486 CommandCompletions::eSourceFileCompletion,
487 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000488
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 if (break_regex_cmd_ap.get()) {
490 bool success = true;
491 for (size_t i = 0; i < num_regexes; i++) {
492 success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0],
493 break_regexes[i][1]);
494 if (!success)
495 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000496 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497 success =
498 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Jim Inghamffba2292011-03-22 02:29:32 +0000499
Kate Stoneb9c1b512016-09-06 20:57:50 +0000500 if (success) {
501 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
502 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
Jim Inghamca36cd12012-10-05 19:16:31 +0000503 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000504 }
Jim Inghamca36cd12012-10-05 19:16:31 +0000505
Kate Stoneb9c1b512016-09-06 20:57:50 +0000506 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap(
507 new CommandObjectRegexCommand(
508 *this, "_regexp-tbreak",
509 "Set a one-shot breakpoint using one of several shorthand formats.\n",
510 "\n"
511 "_regexp-break <filename>:<linenum>\n"
512 " main.c:12 // Break at line 12 of "
513 "main.c\n\n"
514 "_regexp-break <linenum>\n"
515 " 12 // Break at line 12 of current "
516 "file\n\n"
517 "_regexp-break 0x<address>\n"
518 " 0x1234000 // Break at address "
519 "0x1234000\n\n"
520 "_regexp-break <name>\n"
521 " main // Break in 'main' after the "
522 "prologue\n\n"
523 "_regexp-break &<name>\n"
524 " &main // Break at first instruction "
525 "in 'main'\n\n"
526 "_regexp-break <module>`<name>\n"
527 " libc.so`malloc // Break in 'malloc' from "
528 "'libc.so'\n\n"
529 "_regexp-break /<source-regex>/\n"
530 " /break here/ // Break on source lines in "
531 "current file\n"
532 " // containing text 'break "
533 "here'.\n",
534 2, CommandCompletions::eSymbolCompletion |
535 CommandCompletions::eSourceFileCompletion,
536 false));
537
538 if (tbreak_regex_cmd_ap.get()) {
539 bool success = true;
540 for (size_t i = 0; i < num_regexes; i++) {
541 // If you add a resultant command string longer than 1024 characters be
542 // sure to increase the size of this buffer.
543 char buffer[1024];
544 int num_printed =
545 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
546 assert(num_printed < 1024);
547 UNUSED_IF_ASSERT_DISABLED(num_printed);
548 success =
549 tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer);
550 if (!success)
551 break;
Johnny Chen6d675242012-08-24 18:15:45 +0000552 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000553 success =
554 tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
Kate Stone7428a182016-07-14 22:03:10 +0000555
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 if (success) {
557 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
558 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
559 tbreak_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000560 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561 }
Kate Stone7428a182016-07-14 22:03:10 +0000562
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap(
564 new CommandObjectRegexCommand(
565 *this, "_regexp-attach", "Attach to process by ID or name.",
566 "_regexp-attach <pid> | <process-name>", 2, 0, false));
567 if (attach_regex_cmd_ap.get()) {
568 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
569 "process attach --pid %1") &&
570 attach_regex_cmd_ap->AddRegexCommand(
571 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
572 // specified get passed to
573 // 'process attach'
574 attach_regex_cmd_ap->AddRegexCommand("^(.+)$",
575 "process attach --name '%1'") &&
576 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) {
577 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
578 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
579 attach_regex_cmd_sp;
Jim Inghamffba2292011-03-22 02:29:32 +0000580 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000581 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000582
Kate Stoneb9c1b512016-09-06 20:57:50 +0000583 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap(
584 new CommandObjectRegexCommand(*this, "_regexp-down",
585 "Select a newer stack frame. Defaults to "
586 "moving one frame, a numeric argument can "
587 "specify an arbitrary number.",
588 "_regexp-down [<count>]", 2, 0, false));
589 if (down_regex_cmd_ap.get()) {
590 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
591 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
592 "frame select -r -%1")) {
593 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
594 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000595 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000597
Kate Stoneb9c1b512016-09-06 20:57:50 +0000598 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap(
599 new CommandObjectRegexCommand(
600 *this, "_regexp-up",
601 "Select an older stack frame. Defaults to moving one "
602 "frame, a numeric argument can specify an arbitrary number.",
603 "_regexp-up [<count>]", 2, 0, false));
604 if (up_regex_cmd_ap.get()) {
605 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
606 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
607 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
608 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
Jason Molendabc7748b2011-10-22 01:30:52 +0000609 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000610 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000611
Kate Stoneb9c1b512016-09-06 20:57:50 +0000612 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap(
613 new CommandObjectRegexCommand(
614 *this, "_regexp-display",
615 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
616 "_regexp-display expression", 2, 0, false));
617 if (display_regex_cmd_ap.get()) {
618 if (display_regex_cmd_ap->AddRegexCommand(
619 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
620 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
621 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
622 display_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000623 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000624 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000625
Kate Stoneb9c1b512016-09-06 20:57:50 +0000626 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap(
627 new CommandObjectRegexCommand(
628 *this, "_regexp-undisplay", "Stop displaying expression at every "
629 "stop (specified by stop-hook index.)",
630 "_regexp-undisplay stop-hook-number", 2, 0, false));
631 if (undisplay_regex_cmd_ap.get()) {
632 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
633 "target stop-hook delete %1")) {
634 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
635 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
636 undisplay_regex_cmd_sp;
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000637 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000638 }
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000639
Kate Stoneb9c1b512016-09-06 20:57:50 +0000640 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap(
641 new CommandObjectRegexCommand(
642 *this, "gdb-remote", "Connect to a process via remote GDB server. "
643 "If no host is specifed, localhost is assumed.",
644 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
645 if (connect_gdb_remote_cmd_ap.get()) {
646 if (connect_gdb_remote_cmd_ap->AddRegexCommand(
647 "^([^:]+:[[:digit:]]+)$",
648 "process connect --plugin gdb-remote connect://%1") &&
649 connect_gdb_remote_cmd_ap->AddRegexCommand(
650 "^([[:digit:]]+)$",
651 "process connect --plugin gdb-remote connect://localhost:%1")) {
652 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
653 m_command_dict[command_sp->GetCommandName()] = command_sp;
Jason Molenda4cddfed2012-10-05 05:29:32 +0000654 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000655 }
Jason Molenda4cddfed2012-10-05 05:29:32 +0000656
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap(
658 new CommandObjectRegexCommand(
659 *this, "kdp-remote", "Connect to a process via remote KDP server. "
660 "If no UDP port is specified, port 41139 is "
661 "assumed.",
662 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
663 if (connect_kdp_remote_cmd_ap.get()) {
664 if (connect_kdp_remote_cmd_ap->AddRegexCommand(
665 "^([^:]+:[[:digit:]]+)$",
666 "process connect --plugin kdp-remote udp://%1") &&
667 connect_kdp_remote_cmd_ap->AddRegexCommand(
668 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
669 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
670 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Clayton6bade322013-02-01 23:33:03 +0000671 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672 }
Greg Clayton6bade322013-02-01 23:33:03 +0000673
Kate Stoneb9c1b512016-09-06 20:57:50 +0000674 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap(
675 new CommandObjectRegexCommand(
676 *this, "_regexp-bt",
677 "Show the current thread's call stack. Any numeric argument "
678 "displays at most that many "
679 "frames. The argument 'all' displays all threads.",
680 "bt [<digit> | all]", 2, 0, false));
681 if (bt_regex_cmd_ap.get()) {
682 // accept but don't document "bt -c <number>" -- before bt was a regex
683 // command if you wanted to backtrace
684 // three frames you would do "bt -c 3" but the intention is to have this
685 // emulate the gdb "bt" command and
686 // so now "bt 3" is the preferred form, in line with gdb.
687 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$",
688 "thread backtrace -c %1") &&
689 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$",
690 "thread backtrace -c %1") &&
691 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
692 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) {
693 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
694 m_command_dict[command_sp->GetCommandName()] = command_sp;
Greg Claytonef5651d2013-02-12 18:52:24 +0000695 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 }
Greg Claytonef5651d2013-02-12 18:52:24 +0000697
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap(
699 new CommandObjectRegexCommand(
700 *this, "_regexp-list",
701 "List relevant source code using one of several shorthand formats.",
702 "\n"
703 "_regexp-list <file>:<line> // List around specific file/line\n"
704 "_regexp-list <line> // List current file around specified "
705 "line\n"
706 "_regexp-list <function-name> // List specified function\n"
707 "_regexp-list 0x<address> // List around specified address\n"
708 "_regexp-list -[<count>] // List previous <count> lines\n"
709 "_regexp-list // List subsequent lines",
710 2, CommandCompletions::eSourceFileCompletion, false));
711 if (list_regex_cmd_ap.get()) {
712 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
713 "source list --line %1") &&
714 list_regex_cmd_ap->AddRegexCommand(
715 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
716 "]*$",
717 "source list --file '%1' --line %2") &&
718 list_regex_cmd_ap->AddRegexCommand(
719 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
720 "source list --address %1") &&
721 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$",
722 "source list --reverse") &&
723 list_regex_cmd_ap->AddRegexCommand(
724 "^-([[:digit:]]+)[[:space:]]*$",
725 "source list --reverse --count %1") &&
726 list_regex_cmd_ap->AddRegexCommand("^(.+)$",
727 "source list --name \"%1\"") &&
728 list_regex_cmd_ap->AddRegexCommand("^$", "source list")) {
729 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
730 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
Richard Mittonf86248d2013-09-12 02:20:34 +0000731 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732 }
Richard Mittonf86248d2013-09-12 02:20:34 +0000733
Kate Stoneb9c1b512016-09-06 20:57:50 +0000734 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap(
735 new CommandObjectRegexCommand(
736 *this, "_regexp-env",
737 "Shorthand for viewing and setting environment variables.",
738 "\n"
739 "_regexp-env // Show enrivonment\n"
740 "_regexp-env <name>=<value> // Set an environment variable",
741 2, 0, false));
742 if (env_regex_cmd_ap.get()) {
743 if (env_regex_cmd_ap->AddRegexCommand("^$",
744 "settings show target.env-vars") &&
745 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
746 "settings set target.env-vars %1")) {
747 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
748 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
749 }
750 }
751
752 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap(
753 new CommandObjectRegexCommand(
754 *this, "_regexp-jump", "Set the program counter to a new address.",
755 "\n"
756 "_regexp-jump <line>\n"
757 "_regexp-jump +<line-offset> | -<line-offset>\n"
758 "_regexp-jump <file>:<line>\n"
759 "_regexp-jump *<addr>\n",
760 2, 0, false));
761 if (jump_regex_cmd_ap.get()) {
762 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$",
763 "thread jump --addr %1") &&
764 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
765 "thread jump --line %1") &&
766 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$",
767 "thread jump --file %1 --line %2") &&
768 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$",
769 "thread jump --by %1")) {
770 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
771 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
772 }
773 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000774}
775
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776int CommandInterpreter::GetCommandNamesMatchingPartialString(
777 const char *cmd_str, bool include_aliases, StringList &matches) {
778 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000779
Kate Stoneb9c1b512016-09-06 20:57:50 +0000780 if (include_aliases) {
781 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches);
782 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000783
Kate Stoneb9c1b512016-09-06 20:57:50 +0000784 return matches.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000785}
786
Zachary Turnera4496982016-10-05 21:14:38 +0000787CommandObjectSP CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000788 bool include_aliases,
789 bool exact,
Zachary Turnera4496982016-10-05 21:14:38 +0000790 StringList *matches) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000791 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000792
Zachary Turnera4496982016-10-05 21:14:38 +0000793 std::string cmd = cmd_str;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000794
Kate Stoneb9c1b512016-09-06 20:57:50 +0000795 if (HasCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000796 auto pos = m_command_dict.find(cmd);
Greg Claytonb5472782015-01-09 19:08:20 +0000797 if (pos != m_command_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000798 command_sp = pos->second;
799 }
800
801 if (include_aliases && HasAliases()) {
802 auto alias_pos = m_alias_dict.find(cmd);
803 if (alias_pos != m_alias_dict.end())
804 command_sp = alias_pos->second;
805 }
806
807 if (HasUserCommands()) {
Zachary Turnera4496982016-10-05 21:14:38 +0000808 auto pos = m_user_dict.find(cmd);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000809 if (pos != m_user_dict.end())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000810 command_sp = pos->second;
811 }
812
813 if (!exact && !command_sp) {
814 // We will only get into here if we didn't find any exact matches.
815
816 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
817
818 StringList local_matches;
819 if (matches == nullptr)
820 matches = &local_matches;
821
822 unsigned int num_cmd_matches = 0;
823 unsigned int num_alias_matches = 0;
824 unsigned int num_user_matches = 0;
825
826 // Look through the command dictionaries one by one, and if we get only one
827 // match from any of
828 // them in toto, then return that, otherwise return an empty CommandObjectSP
829 // and the list of matches.
830
831 if (HasCommands()) {
832 num_cmd_matches =
Zachary Turnera4496982016-10-05 21:14:38 +0000833 AddNamesMatchingPartialString(m_command_dict, cmd_str, *matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000834 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000835
836 if (num_cmd_matches == 1) {
837 cmd.assign(matches->GetStringAtIndex(0));
Zachary Turnera4496982016-10-05 21:14:38 +0000838 auto pos = m_command_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 if (pos != m_command_dict.end())
840 real_match_sp = pos->second;
841 }
842
843 if (include_aliases && HasAliases()) {
844 num_alias_matches =
Zachary Turnera4496982016-10-05 21:14:38 +0000845 AddNamesMatchingPartialString(m_alias_dict, cmd_str, *matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 }
847
848 if (num_alias_matches == 1) {
849 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
850 auto alias_pos = m_alias_dict.find(cmd);
851 if (alias_pos != m_alias_dict.end())
852 alias_match_sp = alias_pos->second;
853 }
854
855 if (HasUserCommands()) {
856 num_user_matches =
Zachary Turnera4496982016-10-05 21:14:38 +0000857 AddNamesMatchingPartialString(m_user_dict, cmd_str, *matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000858 }
859
860 if (num_user_matches == 1) {
861 cmd.assign(
862 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
863
Zachary Turnera4496982016-10-05 21:14:38 +0000864 auto pos = m_user_dict.find(cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865 if (pos != m_user_dict.end())
866 user_match_sp = pos->second;
867 }
868
869 // If we got exactly one match, return that, otherwise return the match
870 // list.
871
872 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
873 if (num_cmd_matches)
874 return real_match_sp;
875 else if (num_alias_matches)
876 return alias_match_sp;
877 else
878 return user_match_sp;
879 }
880 } else if (matches && command_sp) {
Zachary Turnera4496982016-10-05 21:14:38 +0000881 matches->AppendString(cmd_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882 }
883
884 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000885}
886
Zachary Turnera4496982016-10-05 21:14:38 +0000887bool CommandInterpreter::AddCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 const lldb::CommandObjectSP &cmd_sp,
889 bool can_replace) {
890 if (cmd_sp.get())
891 assert((this == &cmd_sp->GetCommandInterpreter()) &&
892 "tried to add a CommandObject from a different interpreter");
Kate Stonea487aa42015-01-15 00:52:41 +0000893
Zachary Turnera4496982016-10-05 21:14:38 +0000894 if (name.empty())
895 return false;
896
897 std::string name_sstr(name);
898 auto name_iter = m_command_dict.find(name_sstr);
899 if (name_iter != m_command_dict.end()) {
900 if (!can_replace || !name_iter->second->IsRemovable())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901 return false;
Zachary Turnera4496982016-10-05 21:14:38 +0000902 name_iter->second = cmd_sp;
903 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904 m_command_dict[name_sstr] = cmd_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000905 }
Zachary Turnera4496982016-10-05 21:14:38 +0000906 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000907}
908
Zachary Turnera483f572016-10-05 21:14:49 +0000909bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910 const lldb::CommandObjectSP &cmd_sp,
911 bool can_replace) {
912 if (cmd_sp.get())
913 assert((this == &cmd_sp->GetCommandInterpreter()) &&
914 "tried to add a CommandObject from a different interpreter");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000915
Kate Stoneb9c1b512016-09-06 20:57:50 +0000916 if (!name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000917 // do not allow replacement of internal commands
Zachary Turnera483f572016-10-05 21:14:49 +0000918 if (CommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000919 if (can_replace == false)
920 return false;
921 if (m_command_dict[name]->IsRemovable() == false)
Greg Clayton5a314712011-10-14 07:41:33 +0000922 return false;
923 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000924
Zachary Turnera483f572016-10-05 21:14:49 +0000925 if (UserCommandExists(name)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000926 if (can_replace == false)
927 return false;
928 if (m_user_dict[name]->IsRemovable() == false)
929 return false;
Caroline Tice844d2302010-12-09 22:52:49 +0000930 }
931
Kate Stoneb9c1b512016-09-06 20:57:50 +0000932 m_user_dict[name] = cmd_sp;
933 return true;
934 }
935 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000936}
937
Zachary Turnera4496982016-10-05 21:14:38 +0000938CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
939 bool include_aliases) const {
940 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941 // it's a multi-word command.
942 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000943
Zachary Turnera4496982016-10-05 21:14:38 +0000944 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000945 return ret_val;
946
947 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +0000948 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949 else {
950 // We have a multi-word command (seemingly), so we need to do more work.
951 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +0000952 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000953 include_aliases, true, nullptr);
954 if (cmd_obj_sp.get() != nullptr) {
955 // Loop through the rest of the words in the command (everything passed in
956 // was supposed to be part of a
957 // command name), and find the appropriate sub-command SP for each command
958 // word....
959 size_t end = cmd_words.GetArgumentCount();
960 for (size_t j = 1; j < end; ++j) {
961 if (cmd_obj_sp->IsMultiwordObject()) {
962 cmd_obj_sp =
963 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
964 if (cmd_obj_sp.get() == nullptr)
965 // The sub-command name was invalid. Fail and return the empty
966 // 'ret_val'.
967 return ret_val;
968 } else
969 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +0000970 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 return ret_val;
972 }
973 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +0000974 // command objects for them. Assign the last object retrieved to
975 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000977 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978 }
979 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000980}
981
Zachary Turnera4496982016-10-05 21:14:38 +0000982CommandObject *CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
983 StringList *matches) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 CommandObject *command_obj =
Zachary Turnera4496982016-10-05 21:14:38 +0000985 GetCommandSP(cmd_str, false, true, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000986
Kate Stoneb9c1b512016-09-06 20:57:50 +0000987 // If we didn't find an exact match to the command string in the commands,
988 // look in
989 // the aliases.
990
991 if (command_obj)
992 return command_obj;
993
Zachary Turnera4496982016-10-05 21:14:38 +0000994 command_obj = GetCommandSP(cmd_str, true, true, matches).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000995
996 if (command_obj)
997 return command_obj;
998
999 // If there wasn't an exact match then look for an inexact one in just the
1000 // commands
Zachary Turnera4496982016-10-05 21:14:38 +00001001 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002
1003 // Finally, if there wasn't an inexact match among the commands, look for an
1004 // inexact
1005 // match in both the commands and aliases.
1006
1007 if (command_obj) {
1008 if (matches)
1009 matches->AppendString(command_obj->GetCommandName());
1010 return command_obj;
1011 }
1012
Zachary Turnera4496982016-10-05 21:14:38 +00001013 return GetCommandSP(cmd_str, true, false, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001014}
1015
Zachary Turnera483f572016-10-05 21:14:49 +00001016bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001017 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001018}
1019
Zachary Turnera483f572016-10-05 21:14:49 +00001020bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1021 std::string &full_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001022 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1023 if (exact_match) {
1024 full_name.assign(cmd);
1025 return exact_match;
1026 } else {
1027 StringList matches;
1028 size_t num_alias_matches;
1029 num_alias_matches =
1030 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1031 if (num_alias_matches == 1) {
1032 // Make sure this isn't shadowing a command in the regular command space:
1033 StringList regular_matches;
1034 const bool include_aliases = false;
1035 const bool exact = false;
1036 CommandObjectSP cmd_obj_sp(
1037 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1038 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1039 return false;
1040 else {
1041 full_name.assign(matches.GetStringAtIndex(0));
1042 return true;
1043 }
1044 } else
1045 return false;
1046 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047}
1048
Zachary Turnera483f572016-10-05 21:14:49 +00001049bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001050 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001051}
1052
Zachary Turnera483f572016-10-05 21:14:49 +00001053bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001054 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001055}
1056
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057CommandAlias *
Zachary Turnera483f572016-10-05 21:14:49 +00001058CommandInterpreter::AddAlias(llvm::StringRef alias_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059 lldb::CommandObjectSP &command_obj_sp,
Zachary Turnera483f572016-10-05 21:14:49 +00001060 llvm::StringRef args_string) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001061 if (command_obj_sp.get())
1062 assert((this == &command_obj_sp->GetCommandInterpreter()) &&
1063 "tried to add a CommandObject from a different interpreter");
1064
1065 std::unique_ptr<CommandAlias> command_alias_up(
1066 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1067
1068 if (command_alias_up && command_alias_up->IsValid()) {
1069 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1070 return command_alias_up.release();
1071 }
1072
1073 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001074}
1075
Zachary Turnera483f572016-10-05 21:14:49 +00001076bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077 auto pos = m_alias_dict.find(alias_name);
1078 if (pos != m_alias_dict.end()) {
1079 m_alias_dict.erase(pos);
1080 return true;
1081 }
1082 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001083}
1084
Zachary Turnera483f572016-10-05 21:14:49 +00001085bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001086 auto pos = m_command_dict.find(cmd);
1087 if (pos != m_command_dict.end()) {
1088 if (pos->second->IsRemovable()) {
1089 // Only regular expression objects or python commands are removable
1090 m_command_dict.erase(pos);
1091 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001092 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 }
1094 return false;
1095}
Zachary Turnera483f572016-10-05 21:14:49 +00001096bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001097 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1098 if (pos != m_user_dict.end()) {
1099 m_user_dict.erase(pos);
1100 return true;
1101 }
1102 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001103}
1104
Kate Stoneb9c1b512016-09-06 20:57:50 +00001105void CommandInterpreter::GetHelp(CommandReturnObject &result,
1106 uint32_t cmd_types) {
1107 const char *help_prologue = GetDebugger().GetIOHandlerHelpPrologue();
1108 if (help_prologue != NULL) {
1109 OutputFormattedHelpText(result.GetOutputStream(), NULL, help_prologue);
1110 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001111
Kate Stoneb9c1b512016-09-06 20:57:50 +00001112 CommandObject::CommandMap::const_iterator pos;
1113 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001114
Kate Stoneb9c1b512016-09-06 20:57:50 +00001115 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1116 result.AppendMessage("Debugger commands:");
1117 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001118
Kate Stoneb9c1b512016-09-06 20:57:50 +00001119 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1120 if (!(cmd_types & eCommandTypesHidden) &&
1121 (pos->first.compare(0, 1, "_") == 0))
1122 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001123
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124 OutputFormattedHelpText(result.GetOutputStream(), pos->first.c_str(),
1125 "--", pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001126 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127 result.AppendMessage("");
1128 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001129
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130 if (!m_alias_dict.empty() &&
1131 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1132 result.AppendMessageWithFormat(
1133 "Current command abbreviations "
1134 "(type '%shelp command alias' for more info):\n",
1135 GetCommandPrefix());
1136 result.AppendMessage("");
1137 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001138
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1140 ++alias_pos) {
1141 OutputFormattedHelpText(result.GetOutputStream(),
1142 alias_pos->first.c_str(), "--",
1143 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001144 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001145 result.AppendMessage("");
1146 }
Greg Clayton14a35512011-09-11 00:01:44 +00001147
Kate Stoneb9c1b512016-09-06 20:57:50 +00001148 if (!m_user_dict.empty() &&
1149 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1150 result.AppendMessage("Current user-defined commands:");
1151 result.AppendMessage("");
1152 max_len = FindLongestCommandWord(m_user_dict);
1153 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
1154 OutputFormattedHelpText(result.GetOutputStream(), pos->first.c_str(),
1155 "--", pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001156 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001157 result.AppendMessage("");
1158 }
Greg Clayton14a35512011-09-11 00:01:44 +00001159
Kate Stoneb9c1b512016-09-06 20:57:50 +00001160 result.AppendMessageWithFormat(
1161 "For more information on any command, type '%shelp <command-name>'.\n",
1162 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001163}
1164
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001165CommandObject *
Kate Stoneb9c1b512016-09-06 20:57:50 +00001166CommandInterpreter::GetCommandObjectForCommand(std::string &command_string) {
1167 // This function finds the final, lowest-level, alias-resolved command object
1168 // whose 'Execute' function will
1169 // eventually be invoked by the given command line.
1170
1171 CommandObject *cmd_obj = nullptr;
1172 size_t start = command_string.find_first_not_of(k_white_space);
1173 size_t end = 0;
1174 bool done = false;
1175 while (!done) {
1176 if (start != std::string::npos) {
1177 // Get the next word from command_string.
1178 end = command_string.find_first_of(k_white_space, start);
1179 if (end == std::string::npos)
1180 end = command_string.size();
1181 std::string cmd_word = command_string.substr(start, end - start);
1182
1183 if (cmd_obj == nullptr)
1184 // Since cmd_obj is NULL we are on our first time through this loop.
1185 // Check to see if cmd_word is a valid
1186 // command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001187 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001188 else if (cmd_obj->IsMultiwordObject()) {
1189 // Our current object is a multi-word object; see if the cmd_word is a
1190 // valid sub-command for our object.
1191 CommandObject *sub_cmd_obj =
1192 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1193 if (sub_cmd_obj)
1194 cmd_obj = sub_cmd_obj;
1195 else // cmd_word was not a valid sub-command word, so we are done
1196 done = true;
1197 } else
1198 // We have a cmd_obj and it is not a multi-word object, so we are done.
1199 done = true;
1200
1201 // If we didn't find a valid command object, or our command object is not
1202 // a multi-word object, or
1203 // we are at the end of the command_string, then we are done. Otherwise,
1204 // find the start of the
1205 // next word.
1206
1207 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1208 end >= command_string.size())
1209 done = true;
1210 else
1211 start = command_string.find_first_not_of(k_white_space, end);
1212 } else
1213 // Unable to find any more words.
1214 done = true;
1215 }
1216
1217 if (end == command_string.size())
1218 command_string.clear();
1219 else
1220 command_string = command_string.substr(end);
1221
1222 return cmd_obj;
1223}
1224
1225static const char *k_valid_command_chars =
1226 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1227static void StripLeadingSpaces(std::string &s) {
1228 if (!s.empty()) {
1229 size_t pos = s.find_first_not_of(k_white_space);
1230 if (pos == std::string::npos)
1231 s.clear();
1232 else if (pos == 0)
1233 return;
1234 s.erase(0, pos);
1235 }
1236}
1237
1238static size_t FindArgumentTerminator(const std::string &s) {
1239 const size_t s_len = s.size();
1240 size_t offset = 0;
1241 while (offset < s_len) {
1242 size_t pos = s.find("--", offset);
1243 if (pos == std::string::npos)
1244 break;
1245 if (pos > 0) {
1246 if (isspace(s[pos - 1])) {
1247 // Check if the string ends "\s--" (where \s is a space character)
1248 // or if we have "\s--\s".
1249 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1250 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001251 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001252 }
1253 }
1254 offset = pos + 2;
1255 }
1256 return std::string::npos;
1257}
1258
1259static bool ExtractCommand(std::string &command_string, std::string &command,
1260 std::string &suffix, char &quote_char) {
1261 command.clear();
1262 suffix.clear();
1263 StripLeadingSpaces(command_string);
1264
1265 bool result = false;
1266 quote_char = '\0';
1267
1268 if (!command_string.empty()) {
1269 const char first_char = command_string[0];
1270 if (first_char == '\'' || first_char == '"') {
1271 quote_char = first_char;
1272 const size_t end_quote_pos = command_string.find(quote_char, 1);
1273 if (end_quote_pos == std::string::npos) {
1274 command.swap(command_string);
1275 command_string.erase();
1276 } else {
1277 command.assign(command_string, 1, end_quote_pos - 1);
1278 if (end_quote_pos + 1 < command_string.size())
1279 command_string.erase(0, command_string.find_first_not_of(
1280 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001281 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001282 command_string.erase();
1283 }
1284 } else {
1285 const size_t first_space_pos =
1286 command_string.find_first_of(k_white_space);
1287 if (first_space_pos == std::string::npos) {
1288 command.swap(command_string);
1289 command_string.erase();
1290 } else {
1291 command.assign(command_string, 0, first_space_pos);
1292 command_string.erase(0, command_string.find_first_not_of(
1293 k_white_space, first_space_pos));
1294 }
1295 }
1296 result = true;
1297 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001298
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 if (!command.empty()) {
1300 // actual commands can't start with '-' or '_'
1301 if (command[0] != '-' && command[0] != '_') {
1302 size_t pos = command.find_first_not_of(k_valid_command_chars);
1303 if (pos > 0 && pos != std::string::npos) {
1304 suffix.assign(command.begin() + pos, command.end());
1305 command.erase(pos);
1306 }
1307 }
1308 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001309
Kate Stoneb9c1b512016-09-06 20:57:50 +00001310 return result;
1311}
1312
1313CommandObject *CommandInterpreter::BuildAliasResult(
Zachary Turnera483f572016-10-05 21:14:49 +00001314 llvm::StringRef alias_name, std::string &raw_input_string,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001315 std::string &alias_result, CommandReturnObject &result) {
1316 CommandObject *alias_cmd_obj = nullptr;
1317 Args cmd_args(raw_input_string);
1318 alias_cmd_obj = GetCommandObject(alias_name);
1319 StreamString result_str;
1320
Zachary Turner5c28c662016-10-03 23:20:36 +00001321 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1322 alias_result.clear();
1323 return alias_cmd_obj;
1324 }
1325 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1326 ((CommandAlias *)alias_cmd_obj)->Desugar();
1327 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1328 alias_cmd_obj = desugared.first.get();
1329 std::string alias_name_str = alias_name;
1330 if ((cmd_args.GetArgumentCount() == 0) ||
1331 (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0))
1332 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001333
Zachary Turnera4496982016-10-05 21:14:38 +00001334 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001335
Zachary Turner5c28c662016-10-03 23:20:36 +00001336 if (!option_arg_vector_sp.get()) {
1337 alias_result = result_str.GetData();
1338 return alias_cmd_obj;
1339 }
1340 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001341
Zachary Turner5c28c662016-10-03 23:20:36 +00001342 int value_type;
1343 std::string option;
1344 std::string value;
1345 for (const auto &entry : *option_arg_vector) {
1346 std::tie(option, value_type, value) = entry;
1347 if (option == "<argument>") {
1348 result_str.Printf(" %s", value.c_str());
1349 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001350 }
1351
Zachary Turner5c28c662016-10-03 23:20:36 +00001352 result_str.Printf(" %s", option.c_str());
1353 if (value_type == OptionParser::eNoArgument)
1354 continue;
1355
1356 if (value_type != OptionParser::eOptionalArgument)
1357 result_str.Printf(" ");
1358 int index = GetOptionArgumentPosition(value.c_str());
1359 if (index == 0)
1360 result_str.Printf("%s", value.c_str());
1361 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1362
1363 result.AppendErrorWithFormat("Not enough arguments provided; you "
1364 "need at least %d arguments to use "
1365 "this alias.\n",
1366 index);
1367 result.SetStatus(eReturnStatusFailed);
1368 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001369 } else {
1370 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1371 if (strpos != std::string::npos)
1372 raw_input_string = raw_input_string.erase(
1373 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1374 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001375 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001376 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001377
1378 alias_result = result_str.GetData();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001379 return alias_cmd_obj;
1380}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001381
Kate Stoneb9c1b512016-09-06 20:57:50 +00001382Error CommandInterpreter::PreprocessCommand(std::string &command) {
1383 // The command preprocessor needs to do things to the command
1384 // line before any parsing of arguments or anything else is done.
1385 // The only current stuff that gets preprocessed is anything enclosed
1386 // in backtick ('`') characters is evaluated as an expression and
1387 // the result of the expression must be a scalar that can be substituted
1388 // into the command. An example would be:
1389 // (lldb) memory read `$rsp + 20`
1390 Error error; // Error for any expressions that might not evaluate
1391 size_t start_backtick;
1392 size_t pos = 0;
1393 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1394 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
1395 // The backtick was preceded by a '\' character, remove the slash
1396 // and don't treat the backtick as the start of an expression
1397 command.erase(start_backtick - 1, 1);
1398 // No need to add one to start_backtick since we just deleted a char
1399 pos = start_backtick;
1400 } else {
1401 const size_t expr_content_start = start_backtick + 1;
1402 const size_t end_backtick = command.find('`', expr_content_start);
1403 if (end_backtick == std::string::npos)
1404 return error;
1405 else if (end_backtick == expr_content_start) {
1406 // Empty expression (two backticks in a row)
1407 command.erase(start_backtick, 2);
1408 } else {
1409 std::string expr_str(command, expr_content_start,
1410 end_backtick - expr_content_start);
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001411
Kate Stoneb9c1b512016-09-06 20:57:50 +00001412 ExecutionContext exe_ctx(GetExecutionContext());
1413 Target *target = exe_ctx.GetTargetPtr();
1414 // Get a dummy target to allow for calculator mode while processing
1415 // backticks.
1416 // This also helps break the infinite loop caused when target is null.
1417 if (!target)
1418 target = m_debugger.GetDummyTarget();
1419 if (target) {
1420 ValueObjectSP expr_result_valobj_sp;
1421
1422 EvaluateExpressionOptions options;
1423 options.SetCoerceToId(false);
1424 options.SetUnwindOnError(true);
1425 options.SetIgnoreBreakpoints(true);
1426 options.SetKeepInMemory(false);
1427 options.SetTryAllThreads(true);
1428 options.SetTimeoutUsec(0);
1429
1430 ExpressionResults expr_result = target->EvaluateExpression(
1431 expr_str.c_str(), exe_ctx.GetFramePtr(), expr_result_valobj_sp,
1432 options);
1433
1434 if (expr_result == eExpressionCompleted) {
1435 Scalar scalar;
1436 if (expr_result_valobj_sp)
1437 expr_result_valobj_sp =
1438 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1439 expr_result_valobj_sp->GetDynamicValueType(), true);
1440 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1441 command.erase(start_backtick, end_backtick - start_backtick + 1);
1442 StreamString value_strm;
1443 const bool show_type = false;
1444 scalar.GetValue(&value_strm, show_type);
1445 size_t value_string_size = value_strm.GetSize();
1446 if (value_string_size) {
1447 command.insert(start_backtick, value_strm.GetData(),
1448 value_string_size);
1449 pos = start_backtick + value_string_size;
1450 continue;
1451 } else {
1452 error.SetErrorStringWithFormat("expression value didn't result "
1453 "in a scalar value for the "
1454 "expression '%s'",
1455 expr_str.c_str());
1456 }
1457 } else {
1458 error.SetErrorStringWithFormat("expression value didn't result "
1459 "in a scalar value for the "
1460 "expression '%s'",
1461 expr_str.c_str());
1462 }
1463 } else {
1464 if (expr_result_valobj_sp)
1465 error = expr_result_valobj_sp->GetError();
1466 if (error.Success()) {
1467
1468 switch (expr_result) {
1469 case eExpressionSetupError:
1470 error.SetErrorStringWithFormat(
1471 "expression setup error for the expression '%s'",
1472 expr_str.c_str());
1473 break;
1474 case eExpressionParseError:
1475 error.SetErrorStringWithFormat(
1476 "expression parse error for the expression '%s'",
1477 expr_str.c_str());
1478 break;
1479 case eExpressionResultUnavailable:
1480 error.SetErrorStringWithFormat(
1481 "expression error fetching result for the expression '%s'",
1482 expr_str.c_str());
1483 break;
1484 case eExpressionCompleted:
1485 break;
1486 case eExpressionDiscarded:
1487 error.SetErrorStringWithFormat(
1488 "expression discarded for the expression '%s'",
1489 expr_str.c_str());
1490 break;
1491 case eExpressionInterrupted:
1492 error.SetErrorStringWithFormat(
1493 "expression interrupted for the expression '%s'",
1494 expr_str.c_str());
1495 break;
1496 case eExpressionHitBreakpoint:
1497 error.SetErrorStringWithFormat(
1498 "expression hit breakpoint for the expression '%s'",
1499 expr_str.c_str());
1500 break;
1501 case eExpressionTimedOut:
1502 error.SetErrorStringWithFormat(
1503 "expression timed out for the expression '%s'",
1504 expr_str.c_str());
1505 break;
1506 case eExpressionStoppedForDebug:
1507 error.SetErrorStringWithFormat("expression stop at entry point "
1508 "for debugging for the "
1509 "expression '%s'",
1510 expr_str.c_str());
1511 break;
1512 }
1513 }
1514 }
1515 }
1516 }
1517 if (error.Fail())
1518 break;
1519 }
1520 }
1521 return error;
1522}
1523
1524bool CommandInterpreter::HandleCommand(const char *command_line,
1525 LazyBool lazy_add_to_history,
1526 CommandReturnObject &result,
1527 ExecutionContext *override_context,
1528 bool repeat_on_empty_command,
1529 bool no_context_switching)
1530
1531{
1532
1533 std::string command_string(command_line);
1534 std::string original_command_string(command_line);
1535
1536 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
1537 Host::SetCrashDescriptionWithFormat("HandleCommand(command = \"%s\")",
1538 command_line);
1539
1540 // Make a scoped cleanup object that will clear the crash description string
1541 // on exit of this function.
1542 lldb_utility::CleanUp<const char *> crash_description_cleanup(
1543 nullptr, Host::SetCrashDescription);
1544
1545 if (log)
1546 log->Printf("Processing command: %s", command_line);
1547
1548 Timer scoped_timer(LLVM_PRETTY_FUNCTION, "Handling command: %s.",
1549 command_line);
1550
1551 if (!no_context_switching)
1552 UpdateExecutionContext(override_context);
1553
1554 bool add_to_history;
1555 if (lazy_add_to_history == eLazyBoolCalculate)
1556 add_to_history = (m_command_source_depth == 0);
1557 else
1558 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1559
1560 bool empty_command = false;
1561 bool comment_command = false;
1562 if (command_string.empty())
1563 empty_command = true;
1564 else {
1565 const char *k_space_characters = "\t\n\v\f\r ";
1566
1567 size_t non_space = command_string.find_first_not_of(k_space_characters);
1568 // Check for empty line or comment line (lines whose first
1569 // non-space character is the comment character for this interpreter)
1570 if (non_space == std::string::npos)
1571 empty_command = true;
1572 else if (command_string[non_space] == m_comment_char)
1573 comment_command = true;
1574 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
1575 const char *history_string =
1576 m_command_history.FindString(command_string.c_str() + non_space);
1577 if (history_string == nullptr) {
1578 result.AppendErrorWithFormat("Could not find entry: %s in history",
1579 command_string.c_str());
1580 result.SetStatus(eReturnStatusFailed);
1581 return false;
1582 }
1583 add_to_history = false;
1584 command_string = history_string;
1585 original_command_string = history_string;
1586 }
1587 }
1588
1589 if (empty_command) {
1590 if (repeat_on_empty_command) {
1591 if (m_command_history.IsEmpty()) {
1592 result.AppendError("empty command");
1593 result.SetStatus(eReturnStatusFailed);
1594 return false;
1595 } else {
1596 command_line = m_repeat_command.c_str();
1597 command_string = command_line;
1598 original_command_string = command_line;
1599 if (m_repeat_command.empty()) {
1600 result.AppendErrorWithFormat("No auto repeat.\n");
1601 result.SetStatus(eReturnStatusFailed);
1602 return false;
1603 }
1604 }
1605 add_to_history = false;
1606 } else {
1607 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1608 return true;
1609 }
1610 } else if (comment_command) {
1611 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1612 return true;
1613 }
1614
1615 Error error(PreprocessCommand(command_string));
1616
1617 if (error.Fail()) {
1618 result.AppendError(error.AsCString());
1619 result.SetStatus(eReturnStatusFailed);
1620 return false;
1621 }
1622
1623 // Phase 1.
1624
1625 // Before we do ANY kind of argument processing, we need to figure out what
1626 // the real/final command object is for the specified command. This gets
1627 // complicated by the fact that the user could have specified an alias, and,
1628 // in translating the alias, there may also be command options and/or even
1629 // data (including raw text strings) that need to be found and inserted into
1630 // the command line as part of the translation. So this first step is plain
1631 // look-up and replacement, resulting in:
1632 // 1. the command object whose Execute method will actually be called
1633 // 2. a revised command string, with all substitutions and replacements
1634 // taken care of
1635 // From 1 above, we can determine whether the Execute function wants raw
1636 // input or not.
1637
1638 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1639
1640 // Although the user may have abbreviated the command, the command_string now
1641 // has the command expanded to the full name. For example, if the input
1642 // was "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001643 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001644 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1645 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001646 log->Printf("HandleCommand, (revised) command_string: '%s'",
1647 command_string.c_str());
1648 const bool wants_raw_input =
1649 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1650 log->Printf("HandleCommand, wants_raw_input:'%s'",
1651 wants_raw_input ? "True" : "False");
1652 }
1653
1654 // Phase 2.
1655 // Take care of things like setting up the history command & calling the
1656 // appropriate Execute method on the
1657 // CommandObject, with the appropriate arguments.
1658
1659 if (cmd_obj != nullptr) {
1660 if (add_to_history) {
1661 Args command_args(command_string);
1662 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1663 if (repeat_command != nullptr)
1664 m_repeat_command.assign(repeat_command);
1665 else
1666 m_repeat_command.assign(original_command_string.c_str());
1667
1668 m_command_history.AppendString(original_command_string);
1669 }
1670
1671 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001672 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001673 if (actual_cmd_name_len < command_string.length())
1674 remainder = command_string.substr(actual_cmd_name_len);
1675
1676 // Remove any initial spaces
1677 size_t pos = remainder.find_first_not_of(k_white_space);
1678 if (pos != 0 && pos != std::string::npos)
1679 remainder.erase(0, pos);
1680
1681 if (log)
1682 log->Printf(
1683 "HandleCommand, command line after removing command name(s): '%s'",
1684 remainder.c_str());
1685
1686 cmd_obj->Execute(remainder.c_str(), result);
1687 } else {
1688 // We didn't find the first command object, so complete the first argument.
1689 Args command_args(command_string);
1690 StringList matches;
1691 int num_matches;
1692 int cursor_index = 0;
1693 int cursor_char_position = strlen(command_args.GetArgumentAtIndex(0));
1694 bool word_complete;
1695 num_matches = HandleCompletionMatches(command_args, cursor_index,
1696 cursor_char_position, 0, -1,
1697 word_complete, matches);
1698
1699 if (num_matches > 0) {
1700 std::string error_msg;
1701 error_msg.assign("ambiguous command '");
1702 error_msg.append(command_args.GetArgumentAtIndex(0));
1703 error_msg.append("'.");
1704
1705 error_msg.append(" Possible completions:");
1706 for (int i = 0; i < num_matches; i++) {
1707 error_msg.append("\n\t");
1708 error_msg.append(matches.GetStringAtIndex(i));
1709 }
1710 error_msg.append("\n");
1711 result.AppendRawError(error_msg.c_str());
1712 } else
1713 result.AppendErrorWithFormat("Unrecognized command '%s'.\n",
1714 command_args.GetArgumentAtIndex(0));
1715
1716 result.SetStatus(eReturnStatusFailed);
1717 }
1718
1719 if (log)
1720 log->Printf("HandleCommand, command %s",
1721 (result.Succeeded() ? "succeeded" : "did not succeed"));
1722
1723 return result.Succeeded();
1724}
1725
1726int CommandInterpreter::HandleCompletionMatches(
1727 Args &parsed_line, int &cursor_index, int &cursor_char_position,
1728 int match_start_point, int max_return_elements, bool &word_complete,
1729 StringList &matches) {
1730 int num_command_matches = 0;
1731 bool look_for_subcommand = false;
1732
1733 // For any of the command completions a unique match will be a complete word.
1734 word_complete = true;
1735
1736 if (cursor_index == -1) {
1737 // We got nothing on the command line, so return the list of commands
1738 bool include_aliases = true;
1739 num_command_matches =
1740 GetCommandNamesMatchingPartialString("", include_aliases, matches);
1741 } else if (cursor_index == 0) {
1742 // The cursor is in the first argument, so just do a lookup in the
1743 // dictionary.
1744 CommandObject *cmd_obj =
1745 GetCommandObject(parsed_line.GetArgumentAtIndex(0), &matches);
1746 num_command_matches = matches.GetSize();
1747
1748 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
1749 matches.GetStringAtIndex(0) != nullptr &&
1750 strcmp(parsed_line.GetArgumentAtIndex(0),
1751 matches.GetStringAtIndex(0)) == 0) {
1752 if (parsed_line.GetArgumentCount() == 1) {
1753 word_complete = true;
1754 } else {
1755 look_for_subcommand = true;
1756 num_command_matches = 0;
1757 matches.DeleteStringAtIndex(0);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001758 parsed_line.AppendArgument(llvm::StringRef());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001759 cursor_index++;
1760 cursor_char_position = 0;
1761 }
1762 }
1763 }
1764
1765 if (cursor_index > 0 || look_for_subcommand) {
1766 // We are completing further on into a commands arguments, so find the
1767 // command and tell it
1768 // to complete the command.
1769 // First see if there is a matching initial command:
1770 CommandObject *command_object =
1771 GetCommandObject(parsed_line.GetArgumentAtIndex(0));
1772 if (command_object == nullptr) {
1773 return 0;
1774 } else {
1775 parsed_line.Shift();
1776 cursor_index--;
1777 num_command_matches = command_object->HandleCompletion(
1778 parsed_line, cursor_index, cursor_char_position, match_start_point,
1779 max_return_elements, word_complete, matches);
1780 }
1781 }
1782
1783 return num_command_matches;
1784}
1785
1786int CommandInterpreter::HandleCompletion(
1787 const char *current_line, const char *cursor, const char *last_char,
1788 int match_start_point, int max_return_elements, StringList &matches) {
1789 // We parse the argument up to the cursor, so the last argument in parsed_line
1790 // is
1791 // the one containing the cursor, and the cursor is after the last character.
1792
1793 Args parsed_line(llvm::StringRef(current_line, last_char - current_line));
1794 Args partial_parsed_line(
1795 llvm::StringRef(current_line, cursor - current_line));
1796
1797 // Don't complete comments, and if the line we are completing is just the
1798 // history repeat character,
1799 // substitute the appropriate history line.
1800 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1801 if (first_arg) {
1802 if (first_arg[0] == m_comment_char)
1803 return 0;
1804 else if (first_arg[0] == CommandHistory::g_repeat_char) {
1805 const char *history_string = m_command_history.FindString(first_arg);
1806 if (history_string != nullptr) {
1807 matches.Clear();
1808 matches.InsertStringAtIndex(0, history_string);
1809 return -2;
1810 } else
1811 return 0;
1812 }
1813 }
1814
1815 int num_args = partial_parsed_line.GetArgumentCount();
1816 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1817 int cursor_char_position;
1818
1819 if (cursor_index == -1)
1820 cursor_char_position = 0;
1821 else
1822 cursor_char_position =
1823 strlen(partial_parsed_line.GetArgumentAtIndex(cursor_index));
1824
1825 if (cursor > current_line && cursor[-1] == ' ') {
1826 // We are just after a space. If we are in an argument, then we will
1827 // continue
1828 // parsing, but if we are between arguments, then we have to complete
1829 // whatever the next
1830 // element would be.
1831 // We can distinguish the two cases because if we are in an argument (e.g.
1832 // because the space is
1833 // protected by a quote) then the space will also be in the parsed
1834 // argument...
1835
1836 const char *current_elem =
1837 partial_parsed_line.GetArgumentAtIndex(cursor_index);
1838 if (cursor_char_position == 0 ||
1839 current_elem[cursor_char_position - 1] != ' ') {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001840 parsed_line.InsertArgumentAtIndex(cursor_index + 1, llvm::StringRef(),
1841 '\0');
Kate Stoneb9c1b512016-09-06 20:57:50 +00001842 cursor_index++;
1843 cursor_char_position = 0;
1844 }
1845 }
1846
1847 int num_command_matches;
1848
1849 matches.Clear();
1850
1851 // Only max_return_elements == -1 is supported at present:
1852 assert(max_return_elements == -1);
1853 bool word_complete;
1854 num_command_matches = HandleCompletionMatches(
1855 parsed_line, cursor_index, cursor_char_position, match_start_point,
1856 max_return_elements, word_complete, matches);
1857
1858 if (num_command_matches <= 0)
1859 return num_command_matches;
1860
1861 if (num_args == 0) {
1862 // If we got an empty string, insert nothing.
1863 matches.InsertStringAtIndex(0, "");
1864 } else {
1865 // Now figure out if there is a common substring, and if so put that in
1866 // element 0, otherwise
1867 // put an empty string in element 0.
1868 std::string command_partial_str;
1869 if (cursor_index >= 0)
1870 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1871 parsed_line.GetArgumentAtIndex(cursor_index) +
1872 cursor_char_position);
1873
1874 std::string common_prefix;
1875 matches.LongestCommonPrefix(common_prefix);
1876 const size_t partial_name_len = command_partial_str.size();
1877 common_prefix.erase(0, partial_name_len);
1878
1879 // If we matched a unique single command, add a space...
1880 // Only do this if the completer told us this was a complete word,
1881 // however...
1882 if (num_command_matches == 1 && word_complete) {
1883 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1884 common_prefix =
1885 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1886 if (quote_char != '\0')
1887 common_prefix.push_back(quote_char);
1888 common_prefix.push_back(' ');
1889 }
1890 matches.InsertStringAtIndex(0, common_prefix.c_str());
1891 }
1892 return num_command_matches;
1893}
1894
1895CommandInterpreter::~CommandInterpreter() {}
1896
Zachary Turner514d8cd2016-09-23 18:06:53 +00001897void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001898 EventSP prompt_change_event_sp(
1899 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1900 ;
1901 BroadcastEvent(prompt_change_event_sp);
1902 if (m_command_io_handler_sp)
1903 m_command_io_handler_sp->SetPrompt(new_prompt);
1904}
1905
1906bool CommandInterpreter::Confirm(const char *message, bool default_answer) {
1907 // Check AutoConfirm first:
1908 if (m_debugger.GetAutoConfirm())
1909 return default_answer;
1910
1911 IOHandlerConfirm *confirm =
1912 new IOHandlerConfirm(m_debugger, message, default_answer);
1913 IOHandlerSP io_handler_sp(confirm);
1914 m_debugger.RunIOHandler(io_handler_sp);
1915 return confirm->GetResponse();
1916}
1917
Zachary Turnera483f572016-10-05 21:14:49 +00001918const CommandAlias *
1919CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001920 OptionArgVectorSP ret_val;
1921
Zachary Turnera483f572016-10-05 21:14:49 +00001922 auto pos = m_alias_dict.find(alias_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001923 if (pos != m_alias_dict.end())
1924 return (CommandAlias *)pos->second.get();
1925
1926 return nullptr;
1927}
1928
Zachary Turnera4496982016-10-05 21:14:38 +00001929bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001930
Zachary Turnera4496982016-10-05 21:14:38 +00001931bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001932
Zachary Turnera4496982016-10-05 21:14:38 +00001933bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001934
Zachary Turnera4496982016-10-05 21:14:38 +00001935bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001936
1937void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1938 const char *alias_name,
1939 Args &cmd_args,
1940 std::string &raw_input_string,
1941 CommandReturnObject &result) {
1942 OptionArgVectorSP option_arg_vector_sp =
1943 GetAlias(alias_name)->GetOptionArguments();
1944
1945 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1946
1947 // Make sure that the alias name is the 0th element in cmd_args
1948 std::string alias_name_str = alias_name;
1949 if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)
Zachary Turner5c725f32016-09-19 21:56:59 +00001950 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001951
1952 Args new_args(alias_cmd_obj->GetCommandName());
1953 if (new_args.GetArgumentCount() == 2)
1954 new_args.Shift();
1955
1956 if (option_arg_vector_sp.get()) {
1957 if (wants_raw_input) {
1958 // We have a command that both has command options and takes raw input.
1959 // Make *sure* it has a
1960 // " -- " in the right place in the raw_input_string.
1961 size_t pos = raw_input_string.find(" -- ");
1962 if (pos == std::string::npos) {
1963 // None found; assume it goes at the beginning of the raw input string
1964 raw_input_string.insert(0, " -- ");
1965 }
1966 }
1967
1968 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1969 const size_t old_size = cmd_args.GetArgumentCount();
1970 std::vector<bool> used(old_size + 1, false);
1971
1972 used[0] = true;
1973
Zachary Turner5c28c662016-10-03 23:20:36 +00001974 int value_type;
1975 std::string option;
1976 std::string value;
1977 for (const auto &option_entry : *option_arg_vector) {
1978 std::tie(option, value_type, value) = option_entry;
1979 if (option == "<argument>") {
1980 if (!wants_raw_input || (value != "--")) {
1981 // Since we inserted this above, make sure we don't insert it twice
1982 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001983 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001984 continue;
1985 }
1986
1987 if (value_type != OptionParser::eOptionalArgument)
1988 new_args.AppendArgument(option);
1989
1990 if (value == "<no-argument>")
1991 continue;
1992
1993 int index = GetOptionArgumentPosition(value.c_str());
1994 if (index == 0) {
1995 // value was NOT a positional argument; must be a real value
1996 if (value_type != OptionParser::eOptionalArgument)
1997 new_args.AppendArgument(value);
1998 else {
1999 char buffer[255];
2000 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2001 value.c_str());
2002 new_args.AppendArgument(llvm::StringRef(buffer));
2003 }
2004
2005 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
2006 result.AppendErrorWithFormat("Not enough arguments provided; you "
2007 "need at least %d arguments to use "
2008 "this alias.\n",
2009 index);
2010 result.SetStatus(eReturnStatusFailed);
2011 return;
2012 } else {
2013 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2014 size_t strpos =
2015 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
2016 if (strpos != std::string::npos) {
2017 raw_input_string = raw_input_string.erase(
2018 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2019 }
2020
2021 if (value_type != OptionParser::eOptionalArgument)
2022 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2023 else {
2024 char buffer[255];
2025 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2026 cmd_args.GetArgumentAtIndex(index));
2027 new_args.AppendArgument(buffer);
2028 }
2029 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002030 }
2031 }
2032
2033 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j) {
2034 if (!used[j] && !wants_raw_input)
Zachary Turner5c28c662016-10-03 23:20:36 +00002035 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(j));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002036 }
2037
2038 cmd_args.Clear();
2039 cmd_args.SetArguments(new_args.GetArgumentCount(),
2040 new_args.GetConstArgumentVector());
2041 } else {
2042 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2043 // This alias was not created with any options; nothing further needs to be
2044 // done, unless it is a command that
2045 // wants raw input, in which case we need to clear the rest of the data from
2046 // cmd_args, since its in the raw
2047 // input string.
2048 if (wants_raw_input) {
2049 cmd_args.Clear();
2050 cmd_args.SetArguments(new_args.GetArgumentCount(),
2051 new_args.GetConstArgumentVector());
2052 }
2053 return;
2054 }
2055
2056 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2057 return;
2058}
2059
2060int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2061 int position = 0; // Any string that isn't an argument position, i.e. '%'
2062 // followed by an integer, gets a position
2063 // of zero.
2064
2065 const char *cptr = in_string;
2066
2067 // Does it start with '%'
2068 if (cptr[0] == '%') {
2069 ++cptr;
2070
2071 // Is the rest of it entirely digits?
2072 if (isdigit(cptr[0])) {
2073 const char *start = cptr;
2074 while (isdigit(cptr[0]))
2075 ++cptr;
2076
2077 // We've gotten to the end of the digits; are we at the end of the string?
2078 if (cptr[0] == '\0')
2079 position = atoi(start);
2080 }
2081 }
2082
2083 return position;
2084}
2085
2086void CommandInterpreter::SourceInitFile(bool in_cwd,
2087 CommandReturnObject &result) {
2088 FileSpec init_file;
2089 if (in_cwd) {
2090 ExecutionContext exe_ctx(GetExecutionContext());
2091 Target *target = exe_ctx.GetTargetPtr();
2092 if (target) {
2093 // In the current working directory we don't load any program specific
2094 // .lldbinit files, we only look for a ".lldbinit" file.
2095 if (m_skip_lldbinit_files)
2096 return;
2097
2098 LoadCWDlldbinitFile should_load =
2099 target->TargetProperties::GetLoadCWDlldbinitFile();
2100 if (should_load == eLoadCWDlldbinitWarn) {
2101 FileSpec dot_lldb(".lldbinit", true);
2102 llvm::SmallString<64> home_dir_path;
2103 llvm::sys::path::home_directory(home_dir_path);
2104 FileSpec homedir_dot_lldb(home_dir_path.c_str(), false);
2105 homedir_dot_lldb.AppendPathComponent(".lldbinit");
2106 homedir_dot_lldb.ResolvePath();
2107 if (dot_lldb.Exists() &&
2108 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2109 result.AppendErrorWithFormat(
2110 "There is a .lldbinit file in the current directory which is not "
2111 "being read.\n"
2112 "To silence this warning without sourcing in the local "
2113 ".lldbinit,\n"
2114 "add the following to the lldbinit file in your home directory:\n"
2115 " settings set target.load-cwd-lldbinit false\n"
2116 "To allow lldb to source .lldbinit files in the current working "
2117 "directory,\n"
2118 "set the value of this variable to true. Only do so if you "
2119 "understand and\n"
2120 "accept the security risk.");
2121 result.SetStatus(eReturnStatusFailed);
2122 return;
2123 }
2124 } else if (should_load == eLoadCWDlldbinitTrue) {
2125 init_file.SetFile("./.lldbinit", true);
2126 }
2127 }
2128 } else {
2129 // If we aren't looking in the current working directory we are looking
2130 // in the home directory. We will first see if there is an application
2131 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2132 // "-" and the name of the program. If this file doesn't exist, we fall
2133 // back to just the "~/.lldbinit" file. We also obey any requests to not
2134 // load the init files.
2135 llvm::SmallString<64> home_dir_path;
2136 llvm::sys::path::home_directory(home_dir_path);
2137 FileSpec profilePath(home_dir_path.c_str(), false);
2138 profilePath.AppendPathComponent(".lldbinit");
2139 std::string init_file_path = profilePath.GetPath();
2140
2141 if (m_skip_app_init_files == false) {
2142 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2143 const char *program_name = program_file_spec.GetFilename().AsCString();
2144
2145 if (program_name) {
2146 char program_init_file_name[PATH_MAX];
2147 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2148 "%s-%s", init_file_path.c_str(), program_name);
2149 init_file.SetFile(program_init_file_name, true);
2150 if (!init_file.Exists())
2151 init_file.Clear();
2152 }
2153 }
2154
2155 if (!init_file && !m_skip_lldbinit_files)
2156 init_file.SetFile(init_file_path.c_str(), false);
2157 }
2158
2159 // If the file exists, tell HandleCommand to 'source' it; this will do the
2160 // actual broadcasting
2161 // of the commands back to any appropriate listener (see
2162 // CommandObjectSource::Execute for more details).
2163
2164 if (init_file.Exists()) {
2165 const bool saved_batch = SetBatchCommandMode(true);
2166 CommandInterpreterRunOptions options;
2167 options.SetSilent(true);
2168 options.SetStopOnError(false);
2169 options.SetStopOnContinue(true);
2170
2171 HandleCommandsFromFile(init_file,
2172 nullptr, // Execution context
2173 options, result);
2174 SetBatchCommandMode(saved_batch);
2175 } else {
2176 // nothing to be done if the file doesn't exist
2177 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2178 }
2179}
2180
2181const char *CommandInterpreter::GetCommandPrefix() {
2182 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2183 return prefix == NULL ? "" : prefix;
2184}
2185
2186PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2187 PlatformSP platform_sp;
2188 if (prefer_target_platform) {
2189 ExecutionContext exe_ctx(GetExecutionContext());
2190 Target *target = exe_ctx.GetTargetPtr();
2191 if (target)
2192 platform_sp = target->GetPlatform();
2193 }
2194
2195 if (!platform_sp)
2196 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2197 return platform_sp;
2198}
2199
2200void CommandInterpreter::HandleCommands(const StringList &commands,
2201 ExecutionContext *override_context,
2202 CommandInterpreterRunOptions &options,
2203 CommandReturnObject &result) {
2204 size_t num_lines = commands.GetSize();
2205
2206 // If we are going to continue past a "continue" then we need to run the
2207 // commands synchronously.
2208 // Make sure you reset this value anywhere you return from the function.
2209
2210 bool old_async_execution = m_debugger.GetAsyncExecution();
2211
2212 // If we've been given an execution context, set it at the start, but don't
2213 // keep resetting it or we will
2214 // cause series of commands that change the context, then do an operation that
2215 // relies on that context to fail.
2216
2217 if (override_context != nullptr)
2218 UpdateExecutionContext(override_context);
2219
2220 if (!options.GetStopOnContinue()) {
2221 m_debugger.SetAsyncExecution(false);
2222 }
2223
2224 for (size_t idx = 0; idx < num_lines; idx++) {
2225 const char *cmd = commands.GetStringAtIndex(idx);
2226 if (cmd[0] == '\0')
2227 continue;
2228
2229 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002230 // TODO: Add Stream support.
2231 result.AppendMessageWithFormat("%s %s\n",
2232 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002233 }
2234
2235 CommandReturnObject tmp_result;
2236 // If override_context is not NULL, pass no_context_switching = true for
2237 // HandleCommand() since we updated our context already.
2238
2239 // We might call into a regex or alias command, in which case the
2240 // add_to_history will get lost. This
2241 // m_command_source_depth dingus is the way we turn off adding to the
2242 // history in that case, so set it up here.
2243 if (!options.GetAddToHistory())
2244 m_command_source_depth++;
2245 bool success =
2246 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2247 nullptr, /* override_context */
2248 true, /* repeat_on_empty_command */
2249 override_context != nullptr /* no_context_switching */);
2250 if (!options.GetAddToHistory())
2251 m_command_source_depth--;
2252
2253 if (options.GetPrintResults()) {
2254 if (tmp_result.Succeeded())
2255 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
2256 }
2257
2258 if (!success || !tmp_result.Succeeded()) {
2259 const char *error_msg = tmp_result.GetErrorData();
2260 if (error_msg == nullptr || error_msg[0] == '\0')
2261 error_msg = "<unknown error>.\n";
2262 if (options.GetStopOnError()) {
2263 result.AppendErrorWithFormat(
2264 "Aborting reading of commands after command #%" PRIu64
2265 ": '%s' failed with %s",
2266 (uint64_t)idx, cmd, error_msg);
2267 result.SetStatus(eReturnStatusFailed);
2268 m_debugger.SetAsyncExecution(old_async_execution);
2269 return;
2270 } else if (options.GetPrintResults()) {
2271 result.AppendMessageWithFormat("Command #%" PRIu64
2272 " '%s' failed with %s",
2273 (uint64_t)idx + 1, cmd, error_msg);
2274 }
2275 }
2276
2277 if (result.GetImmediateOutputStream())
2278 result.GetImmediateOutputStream()->Flush();
2279
2280 if (result.GetImmediateErrorStream())
2281 result.GetImmediateErrorStream()->Flush();
2282
2283 // N.B. Can't depend on DidChangeProcessState, because the state coming into
2284 // the command execution
2285 // could be running (for instance in Breakpoint Commands.
2286 // So we check the return value to see if it is has running in it.
2287 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2288 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2289 if (options.GetStopOnContinue()) {
2290 // If we caused the target to proceed, and we're going to stop in that
2291 // case, set the
2292 // status in our real result before returning. This is an error if the
2293 // continue was not the
2294 // last command in the set of commands to be run.
2295 if (idx != num_lines - 1)
2296 result.AppendErrorWithFormat(
2297 "Aborting reading of commands after command #%" PRIu64
2298 ": '%s' continued the target.\n",
2299 (uint64_t)idx + 1, cmd);
2300 else
2301 result.AppendMessageWithFormat("Command #%" PRIu64
2302 " '%s' continued the target.\n",
2303 (uint64_t)idx + 1, cmd);
2304
2305 result.SetStatus(tmp_result.GetStatus());
2306 m_debugger.SetAsyncExecution(old_async_execution);
2307
2308 return;
2309 }
2310 }
2311
2312 // Also check for "stop on crash here:
2313 bool should_stop = false;
2314 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2315 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2316 if (target_sp) {
2317 ProcessSP process_sp(target_sp->GetProcessSP());
2318 if (process_sp) {
2319 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2320 StopReason reason = thread_sp->GetStopReason();
2321 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2322 reason == eStopReasonInstrumentation) {
2323 should_stop = true;
2324 break;
2325 }
2326 }
2327 }
2328 }
2329 if (should_stop) {
2330 if (idx != num_lines - 1)
2331 result.AppendErrorWithFormat(
2332 "Aborting reading of commands after command #%" PRIu64
2333 ": '%s' stopped with a signal or exception.\n",
2334 (uint64_t)idx + 1, cmd);
2335 else
2336 result.AppendMessageWithFormat(
2337 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2338 (uint64_t)idx + 1, cmd);
2339
2340 result.SetStatus(tmp_result.GetStatus());
2341 m_debugger.SetAsyncExecution(old_async_execution);
2342
2343 return;
2344 }
2345 }
2346 }
2347
2348 result.SetStatus(eReturnStatusSuccessFinishResult);
2349 m_debugger.SetAsyncExecution(old_async_execution);
2350
2351 return;
2352}
2353
2354// Make flags that we can pass into the IOHandler so our delegates can do the
2355// right thing
2356enum {
2357 eHandleCommandFlagStopOnContinue = (1u << 0),
2358 eHandleCommandFlagStopOnError = (1u << 1),
2359 eHandleCommandFlagEchoCommand = (1u << 2),
2360 eHandleCommandFlagPrintResult = (1u << 3),
2361 eHandleCommandFlagStopOnCrash = (1u << 4)
2362};
2363
2364void CommandInterpreter::HandleCommandsFromFile(
2365 FileSpec &cmd_file, ExecutionContext *context,
2366 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2367 if (cmd_file.Exists()) {
2368 StreamFileSP input_file_sp(new StreamFile());
2369
2370 std::string cmd_file_path = cmd_file.GetPath();
2371 Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(),
2372 File::eOpenOptionRead);
2373
2374 if (error.Success()) {
2375 Debugger &debugger = GetDebugger();
2376
2377 uint32_t flags = 0;
2378
2379 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2380 if (m_command_source_flags.empty()) {
2381 // Stop on continue by default
2382 flags |= eHandleCommandFlagStopOnContinue;
2383 } else if (m_command_source_flags.back() &
2384 eHandleCommandFlagStopOnContinue) {
2385 flags |= eHandleCommandFlagStopOnContinue;
2386 }
2387 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2388 flags |= eHandleCommandFlagStopOnContinue;
2389 }
2390
2391 if (options.m_stop_on_error == eLazyBoolCalculate) {
2392 if (m_command_source_flags.empty()) {
2393 if (GetStopCmdSourceOnError())
2394 flags |= eHandleCommandFlagStopOnError;
2395 } else if (m_command_source_flags.back() &
2396 eHandleCommandFlagStopOnError) {
2397 flags |= eHandleCommandFlagStopOnError;
2398 }
2399 } else if (options.m_stop_on_error == eLazyBoolYes) {
2400 flags |= eHandleCommandFlagStopOnError;
2401 }
2402
2403 if (options.GetStopOnCrash()) {
2404 if (m_command_source_flags.empty()) {
2405 // Echo command by default
2406 flags |= eHandleCommandFlagStopOnCrash;
2407 } else if (m_command_source_flags.back() &
2408 eHandleCommandFlagStopOnCrash) {
2409 flags |= eHandleCommandFlagStopOnCrash;
2410 }
2411 }
2412
2413 if (options.m_echo_commands == eLazyBoolCalculate) {
2414 if (m_command_source_flags.empty()) {
2415 // Echo command by default
2416 flags |= eHandleCommandFlagEchoCommand;
2417 } else if (m_command_source_flags.back() &
2418 eHandleCommandFlagEchoCommand) {
2419 flags |= eHandleCommandFlagEchoCommand;
2420 }
2421 } else if (options.m_echo_commands == eLazyBoolYes) {
2422 flags |= eHandleCommandFlagEchoCommand;
2423 }
2424
2425 if (options.m_print_results == eLazyBoolCalculate) {
2426 if (m_command_source_flags.empty()) {
2427 // Print output by default
2428 flags |= eHandleCommandFlagPrintResult;
2429 } else if (m_command_source_flags.back() &
2430 eHandleCommandFlagPrintResult) {
2431 flags |= eHandleCommandFlagPrintResult;
2432 }
2433 } else if (options.m_print_results == eLazyBoolYes) {
2434 flags |= eHandleCommandFlagPrintResult;
2435 }
2436
2437 if (flags & eHandleCommandFlagPrintResult) {
2438 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2439 cmd_file_path.c_str());
2440 }
2441
2442 // Used for inheriting the right settings when "command source" might have
2443 // nested "command source" commands
2444 lldb::StreamFileSP empty_stream_sp;
2445 m_command_source_flags.push_back(flags);
2446 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2447 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2448 empty_stream_sp, // Pass in an empty stream so we inherit the top
2449 // input reader output stream
2450 empty_stream_sp, // Pass in an empty stream so we inherit the top
2451 // input reader error stream
2452 flags,
2453 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2454 // or written
Zachary Turner514d8cd2016-09-23 18:06:53 +00002455 debugger.GetPrompt(), llvm::StringRef(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00002456 false, // Not multi-line
2457 debugger.GetUseColor(), 0, *this));
2458 const bool old_async_execution = debugger.GetAsyncExecution();
2459
2460 // Set synchronous execution if we are not stopping on continue
2461 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2462 debugger.SetAsyncExecution(false);
2463
2464 m_command_source_depth++;
2465
2466 debugger.RunIOHandler(io_handler_sp);
2467 if (!m_command_source_flags.empty())
2468 m_command_source_flags.pop_back();
2469 m_command_source_depth--;
2470 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2471 debugger.SetAsyncExecution(old_async_execution);
2472 } else {
2473 result.AppendErrorWithFormat(
2474 "error: an error occurred read file '%s': %s\n",
2475 cmd_file_path.c_str(), error.AsCString());
2476 result.SetStatus(eReturnStatusFailed);
2477 }
2478
2479 } else {
2480 result.AppendErrorWithFormat(
2481 "Error reading commands from file %s - file not found.\n",
2482 cmd_file.GetFilename().AsCString("<Unknown>"));
2483 result.SetStatus(eReturnStatusFailed);
2484 return;
2485 }
2486}
2487
2488ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
2489 if (m_script_interpreter_sp)
2490 return m_script_interpreter_sp.get();
2491
2492 if (!can_create)
2493 return nullptr;
2494
2495 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2496 m_script_interpreter_sp =
2497 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2498 return m_script_interpreter_sp.get();
2499}
2500
2501bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2502
2503void CommandInterpreter::SetSynchronous(bool value) {
2504 m_synchronous_execution = value;
2505}
2506
2507void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2508 const char *prefix,
2509 const char *help_text) {
2510 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2511 if (prefix == NULL)
2512 prefix = "";
2513
2514 size_t prefix_width = strlen(prefix);
2515 size_t line_width_max = max_columns - prefix_width;
2516 const char *help_text_end = help_text + strlen(help_text);
2517 const char *line_start = help_text;
2518 if (line_width_max < 16)
2519 line_width_max = help_text_end - help_text + prefix_width;
2520
2521 strm.IndentMore(prefix_width);
2522 while (line_start < help_text_end) {
2523 // Break each line at the first newline or last space/tab before
2524 // the maximum number of characters that fit on a line. Lines with no
2525 // natural break are left unbroken to wrap.
2526 const char *line_end = help_text_end;
2527 const char *line_scan = line_start;
2528 const char *line_scan_end = help_text_end;
2529 while (line_scan < line_scan_end) {
2530 char next = *line_scan;
2531 if (next == '\t' || next == ' ') {
2532 line_end = line_scan;
2533 line_scan_end = line_start + line_width_max;
2534 } else if (next == '\n' || next == '\0') {
2535 line_end = line_scan;
2536 break;
2537 }
2538 ++line_scan;
2539 }
2540
2541 // Prefix the first line, indent subsequent lines to line up
2542 if (line_start == help_text)
2543 strm.Write(prefix, prefix_width);
2544 else
2545 strm.Indent();
2546 strm.Write(line_start, line_end - line_start);
2547 strm.EOL();
2548
2549 // When a line breaks at whitespace consume it before continuing
2550 line_start = line_end;
2551 char next = *line_start;
2552 if (next == '\n')
2553 ++line_start;
2554 else
2555 while (next == ' ' || next == '\t')
2556 next = *(++line_start);
2557 }
2558 strm.IndentLess(prefix_width);
2559}
2560
2561void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2562 const char *word_text,
2563 const char *separator,
2564 const char *help_text,
2565 size_t max_word_len) {
2566 StreamString prefix_stream;
2567 prefix_stream.Printf(" %-*s %s ", (int)max_word_len, word_text, separator);
2568 OutputFormattedHelpText(strm, prefix_stream.GetData(), help_text);
2569}
2570
2571void CommandInterpreter::OutputHelpText(Stream &strm, const char *word_text,
2572 const char *separator,
2573 const char *help_text,
2574 uint32_t max_word_len) {
2575 int indent_size = max_word_len + strlen(separator) + 2;
2576
2577 strm.IndentMore(indent_size);
2578
2579 StreamString text_strm;
2580 text_strm.Printf("%-*s %s %s", max_word_len, word_text, separator, help_text);
2581
2582 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2583
2584 size_t len = text_strm.GetSize();
2585 const char *text = text_strm.GetData();
2586
2587 uint32_t chars_left = max_columns;
2588
2589 for (uint32_t i = 0; i < len; i++) {
2590 if ((text[i] == ' ' && ::strchr((text + i + 1), ' ') &&
Zachary Turner5a8ad4592016-10-05 17:07:34 +00002591 chars_left < static_cast<uint32_t>(::strchr((text + i + 1), ' ') -
2592 (text + i))) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002593 text[i] == '\n') {
2594 chars_left = max_columns - indent_size;
2595 strm.EOL();
2596 strm.Indent();
2597 } else {
2598 strm.PutChar(text[i]);
2599 chars_left--;
2600 }
2601 }
2602
2603 strm.EOL();
2604 strm.IndentLess(indent_size);
2605}
2606
2607void CommandInterpreter::FindCommandsForApropos(
2608 const char *search_word, StringList &commands_found,
2609 StringList &commands_help, CommandObject::CommandMap &command_map) {
2610 CommandObject::CommandMap::const_iterator pos;
2611
2612 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
2613 const char *command_name = pos->first.c_str();
2614 CommandObject *cmd_obj = pos->second.get();
2615
2616 const bool search_short_help = true;
2617 const bool search_long_help = false;
2618 const bool search_syntax = false;
2619 const bool search_options = false;
2620 if (strcasestr(command_name, search_word) ||
2621 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2622 search_long_help, search_syntax,
2623 search_options)) {
2624 commands_found.AppendString(cmd_obj->GetCommandName());
2625 commands_help.AppendString(cmd_obj->GetHelp());
2626 }
2627
2628 if (cmd_obj->IsMultiwordObject()) {
2629 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2630 FindCommandsForApropos(search_word, commands_found, commands_help,
2631 cmd_multiword->GetSubcommandDictionary());
2632 }
2633 }
2634}
2635
2636void CommandInterpreter::FindCommandsForApropos(const char *search_word,
2637 StringList &commands_found,
2638 StringList &commands_help,
2639 bool search_builtin_commands,
2640 bool search_user_commands,
2641 bool search_alias_commands) {
2642 CommandObject::CommandMap::const_iterator pos;
2643
2644 if (search_builtin_commands)
2645 FindCommandsForApropos(search_word, commands_found, commands_help,
2646 m_command_dict);
2647
2648 if (search_user_commands)
2649 FindCommandsForApropos(search_word, commands_found, commands_help,
2650 m_user_dict);
2651
2652 if (search_alias_commands)
2653 FindCommandsForApropos(search_word, commands_found, commands_help,
2654 m_alias_dict);
2655}
2656
2657void CommandInterpreter::UpdateExecutionContext(
2658 ExecutionContext *override_context) {
2659 if (override_context != nullptr) {
2660 m_exe_ctx_ref = *override_context;
2661 } else {
2662 const bool adopt_selected = true;
2663 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2664 adopt_selected);
2665 }
2666}
2667
2668size_t CommandInterpreter::GetProcessOutput() {
2669 // The process has stuff waiting for stderr; get it and write it out to the
2670 // appropriate place.
2671 char stdio_buffer[1024];
2672 size_t len;
2673 size_t total_bytes = 0;
2674 Error error;
2675 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2676 if (target_sp) {
2677 ProcessSP process_sp(target_sp->GetProcessSP());
2678 if (process_sp) {
2679 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2680 error)) > 0) {
2681 size_t bytes_written = len;
2682 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2683 total_bytes += len;
2684 }
2685 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2686 error)) > 0) {
2687 size_t bytes_written = len;
2688 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2689 total_bytes += len;
2690 }
2691 }
2692 }
2693 return total_bytes;
2694}
2695
2696void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2697 std::string &line) {
2698 const bool is_interactive = io_handler.GetIsInteractive();
2699 if (is_interactive == false) {
2700 // When we are not interactive, don't execute blank lines. This will happen
2701 // sourcing a commands file. We don't want blank lines to repeat the
2702 // previous
2703 // command and cause any errors to occur (like redefining an alias, get an
2704 // error
2705 // and stop parsing the commands file).
2706 if (line.empty())
2707 return;
2708
2709 // When using a non-interactive file handle (like when sourcing commands
2710 // from a file)
2711 // we need to echo the command out so we don't just see the command output
2712 // and no
2713 // command...
2714 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2715 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2716 line.c_str());
2717 }
2718
2719 lldb_private::CommandReturnObject result;
2720 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2721
2722 // Now emit the command output text from the command we just executed
2723 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2724 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2725 GetProcessOutput();
2726
2727 if (!result.GetImmediateOutputStream()) {
2728 const char *output = result.GetOutputData();
2729 if (output && output[0])
2730 io_handler.GetOutputStreamFile()->PutCString(output);
2731 }
2732
2733 // Now emit the command error text from the command we just executed
2734 if (!result.GetImmediateErrorStream()) {
2735 const char *error = result.GetErrorData();
2736 if (error && error[0])
2737 io_handler.GetErrorStreamFile()->PutCString(error);
2738 }
2739 }
2740
2741 switch (result.GetStatus()) {
2742 case eReturnStatusInvalid:
2743 case eReturnStatusSuccessFinishNoResult:
2744 case eReturnStatusSuccessFinishResult:
2745 case eReturnStatusStarted:
2746 break;
2747
2748 case eReturnStatusSuccessContinuingNoResult:
2749 case eReturnStatusSuccessContinuingResult:
2750 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2751 io_handler.SetIsDone(true);
2752 break;
2753
2754 case eReturnStatusFailed:
2755 m_num_errors++;
2756 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2757 io_handler.SetIsDone(true);
2758 break;
2759
2760 case eReturnStatusQuit:
2761 m_quit_requested = true;
2762 io_handler.SetIsDone(true);
2763 break;
2764 }
2765
2766 // Finally, if we're going to stop on crash, check that here:
2767 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2768 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2769 bool should_stop = false;
2770 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2771 if (target_sp) {
2772 ProcessSP process_sp(target_sp->GetProcessSP());
2773 if (process_sp) {
2774 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2775 StopReason reason = thread_sp->GetStopReason();
2776 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2777 reason == eStopReasonInstrumentation) &&
2778 !result.GetAbnormalStopWasExpected()) {
2779 should_stop = true;
2780 break;
2781 }
2782 }
2783 }
2784 }
2785 if (should_stop) {
2786 io_handler.SetIsDone(true);
2787 m_stopped_for_crash = true;
2788 }
2789 }
2790}
2791
2792bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2793 ExecutionContext exe_ctx(GetExecutionContext());
2794 Process *process = exe_ctx.GetProcessPtr();
2795
2796 if (process) {
2797 StateType state = process->GetState();
2798 if (StateIsRunningState(state)) {
2799 process->Halt();
2800 return true; // Don't do any updating when we are running
2801 }
2802 }
2803
2804 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2805 if (script_interpreter) {
2806 if (script_interpreter->Interrupt())
2807 return true;
2808 }
2809 return false;
2810}
2811
2812void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2813 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2814 void *baton) {
2815 Debugger &debugger = GetDebugger();
2816 IOHandlerSP io_handler_sp(
2817 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2818 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002819 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2820 llvm::StringRef(), // Continuation prompt
2821 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002822 debugger.GetUseColor(),
2823 0, // Don't show line numbers
2824 delegate)); // IOHandlerDelegate
2825
2826 if (io_handler_sp) {
2827 io_handler_sp->SetUserData(baton);
2828 if (asynchronously)
2829 debugger.PushIOHandler(io_handler_sp);
2830 else
2831 debugger.RunIOHandler(io_handler_sp);
2832 }
2833}
2834
2835void CommandInterpreter::GetPythonCommandsFromIOHandler(
2836 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2837 void *baton) {
2838 Debugger &debugger = GetDebugger();
2839 IOHandlerSP io_handler_sp(
2840 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2841 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002842 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2843 llvm::StringRef(), // Continuation prompt
2844 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002845 debugger.GetUseColor(),
2846 0, // Don't show line numbers
2847 delegate)); // IOHandlerDelegate
2848
2849 if (io_handler_sp) {
2850 io_handler_sp->SetUserData(baton);
2851 if (asynchronously)
2852 debugger.PushIOHandler(io_handler_sp);
2853 else
2854 debugger.RunIOHandler(io_handler_sp);
2855 }
2856}
2857
2858bool CommandInterpreter::IsActive() {
2859 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2860}
2861
2862lldb::IOHandlerSP
2863CommandInterpreter::GetIOHandler(bool force_create,
2864 CommandInterpreterRunOptions *options) {
2865 // Always re-create the IOHandlerEditline in case the input
2866 // changed. The old instance might have had a non-interactive
2867 // input and now it does or vice versa.
2868 if (force_create || !m_command_io_handler_sp) {
2869 // Always re-create the IOHandlerEditline in case the input
2870 // changed. The old instance might have had a non-interactive
2871 // input and now it does or vice versa.
2872 uint32_t flags = 0;
2873
2874 if (options) {
2875 if (options->m_stop_on_continue == eLazyBoolYes)
2876 flags |= eHandleCommandFlagStopOnContinue;
2877 if (options->m_stop_on_error == eLazyBoolYes)
2878 flags |= eHandleCommandFlagStopOnError;
2879 if (options->m_stop_on_crash == eLazyBoolYes)
2880 flags |= eHandleCommandFlagStopOnCrash;
2881 if (options->m_echo_commands != eLazyBoolNo)
2882 flags |= eHandleCommandFlagEchoCommand;
2883 if (options->m_print_results != eLazyBoolNo)
2884 flags |= eHandleCommandFlagPrintResult;
2885 } else {
2886 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2887 }
2888
2889 m_command_io_handler_sp.reset(new IOHandlerEditline(
2890 m_debugger, IOHandler::Type::CommandInterpreter,
2891 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2892 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002893 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002894 false, // Don't enable multiple line input, just single line commands
2895 m_debugger.GetUseColor(),
2896 0, // Don't show line numbers
2897 *this));
2898 }
2899 return m_command_io_handler_sp;
2900}
2901
2902void CommandInterpreter::RunCommandInterpreter(
2903 bool auto_handle_events, bool spawn_thread,
2904 CommandInterpreterRunOptions &options) {
2905 // Always re-create the command interpreter when we run it in case
2906 // any file handles have changed.
2907 bool force_create = true;
2908 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2909 m_stopped_for_crash = false;
2910
2911 if (auto_handle_events)
2912 m_debugger.StartEventHandlerThread();
2913
2914 if (spawn_thread) {
2915 m_debugger.StartIOHandlerThread();
2916 } else {
2917 m_debugger.ExecuteIOHandlers();
2918
2919 if (auto_handle_events)
2920 m_debugger.StopEventHandlerThread();
2921 }
2922}
2923
2924CommandObject *
2925CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2926 CommandReturnObject &result) {
2927 std::string scratch_command(command_line); // working copy so we don't modify
2928 // command_line unless we succeed
2929 CommandObject *cmd_obj = nullptr;
2930 StreamString revised_command_line;
2931 bool wants_raw_input = false;
2932 size_t actual_cmd_name_len = 0;
2933 std::string next_word;
2934 StringList matches;
2935 bool done = false;
2936 while (!done) {
2937 char quote_char = '\0';
2938 std::string suffix;
2939 ExtractCommand(scratch_command, next_word, suffix, quote_char);
2940 if (cmd_obj == nullptr) {
2941 std::string full_name;
2942 bool is_alias = GetAliasFullName(next_word.c_str(), full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00002943 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002944 bool is_real_command =
2945 (is_alias == false) ||
2946 (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
2947 if (!is_real_command) {
2948 matches.Clear();
2949 std::string alias_result;
2950 cmd_obj = BuildAliasResult(full_name.c_str(), scratch_command,
2951 alias_result, result);
2952 revised_command_line.Printf("%s", alias_result.c_str());
2953 if (cmd_obj) {
2954 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00002955 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002956 }
2957 } else {
2958 if (!cmd_obj)
Zachary Turnera4496982016-10-05 21:14:38 +00002959 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002960 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00002961 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
2962 actual_cmd_name_len += cmd_name.size();
2963 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002964 wants_raw_input = cmd_obj->WantsRawCommandString();
2965 } else {
2966 revised_command_line.Printf("%s", next_word.c_str());
2967 }
2968 }
2969 } else {
2970 if (cmd_obj->IsMultiwordObject()) {
2971 CommandObject *sub_cmd_obj =
2972 cmd_obj->GetSubcommandObject(next_word.c_str());
2973 if (sub_cmd_obj) {
2974 // The subcommand's name includes the parent command's name,
2975 // so restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00002976 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
2977 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002978 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00002979 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002980 cmd_obj = sub_cmd_obj;
2981 wants_raw_input = cmd_obj->WantsRawCommandString();
2982 } else {
2983 if (quote_char)
2984 revised_command_line.Printf(" %c%s%s%c", quote_char,
2985 next_word.c_str(), suffix.c_str(),
2986 quote_char);
2987 else
2988 revised_command_line.Printf(" %s%s", next_word.c_str(),
2989 suffix.c_str());
2990 done = true;
2991 }
2992 } else {
2993 if (quote_char)
2994 revised_command_line.Printf(" %c%s%s%c", quote_char,
2995 next_word.c_str(), suffix.c_str(),
2996 quote_char);
2997 else
2998 revised_command_line.Printf(" %s%s", next_word.c_str(),
2999 suffix.c_str());
3000 done = true;
3001 }
3002 }
3003
3004 if (cmd_obj == nullptr) {
3005 const size_t num_matches = matches.GetSize();
3006 if (matches.GetSize() > 1) {
3007 StreamString error_msg;
3008 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3009 next_word.c_str());
3010
3011 for (uint32_t i = 0; i < num_matches; ++i) {
3012 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3013 }
3014 result.AppendRawError(error_msg.GetString().c_str());
3015 } else {
3016 // We didn't have only one match, otherwise we wouldn't get here.
3017 assert(num_matches == 0);
3018 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3019 next_word.c_str());
3020 }
3021 result.SetStatus(eReturnStatusFailed);
3022 return nullptr;
3023 }
3024
3025 if (cmd_obj->IsMultiwordObject()) {
3026 if (!suffix.empty()) {
3027 result.AppendErrorWithFormat(
3028 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3029 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003030 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003031 next_word.empty() ? "" : next_word.c_str(),
3032 next_word.empty() ? " -- " : " ", suffix.c_str());
3033 result.SetStatus(eReturnStatusFailed);
3034 return nullptr;
3035 }
3036 } else {
3037 // If we found a normal command, we are done
3038 done = true;
3039 if (!suffix.empty()) {
3040 switch (suffix[0]) {
3041 case '/':
3042 // GDB format suffixes
3043 {
3044 Options *command_options = cmd_obj->GetOptions();
3045 if (command_options &&
3046 command_options->SupportsLongOption("gdb-format")) {
3047 std::string gdb_format_option("--gdb-format=");
3048 gdb_format_option += (suffix.c_str() + 1);
3049
3050 bool inserted = false;
3051 std::string &cmd = revised_command_line.GetString();
3052 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3053 if (arg_terminator_idx != std::string::npos) {
3054 // Insert the gdb format option before the "--" that terminates
3055 // options
3056 gdb_format_option.append(1, ' ');
3057 cmd.insert(arg_terminator_idx, gdb_format_option);
3058 inserted = true;
3059 }
3060
3061 if (!inserted)
3062 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3063
3064 if (wants_raw_input &&
3065 FindArgumentTerminator(cmd) == std::string::npos)
3066 revised_command_line.PutCString(" --");
3067 } else {
3068 result.AppendErrorWithFormat(
3069 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003070 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003071 result.SetStatus(eReturnStatusFailed);
3072 return nullptr;
3073 }
3074 }
3075 break;
3076
3077 default:
3078 result.AppendErrorWithFormat(
3079 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3080 result.SetStatus(eReturnStatusFailed);
3081 return nullptr;
3082 }
3083 }
3084 }
3085 if (scratch_command.empty())
3086 done = true;
3087 }
3088
3089 if (!scratch_command.empty())
3090 revised_command_line.Printf(" %s", scratch_command.c_str());
3091
3092 if (cmd_obj != NULL)
3093 command_line = revised_command_line.GetData();
3094
3095 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003096}