blob: fa0560aae852efdf4385523fff04826d9f721483 [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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000909bool CommandInterpreter::AddUserCommand(std::string name,
910 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()) {
917 const char *name_cstr = name.c_str();
Caroline Tice844d2302010-12-09 22:52:49 +0000918
Kate Stoneb9c1b512016-09-06 20:57:50 +0000919 // do not allow replacement of internal commands
920 if (CommandExists(name_cstr)) {
921 if (can_replace == false)
922 return false;
923 if (m_command_dict[name]->IsRemovable() == false)
Greg Clayton5a314712011-10-14 07:41:33 +0000924 return false;
925 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000926
Kate Stoneb9c1b512016-09-06 20:57:50 +0000927 if (UserCommandExists(name_cstr)) {
928 if (can_replace == false)
929 return false;
930 if (m_user_dict[name]->IsRemovable() == false)
931 return false;
Caroline Tice844d2302010-12-09 22:52:49 +0000932 }
933
Kate Stoneb9c1b512016-09-06 20:57:50 +0000934 m_user_dict[name] = cmd_sp;
935 return true;
936 }
937 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000938}
939
Zachary Turnera4496982016-10-05 21:14:38 +0000940CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
941 bool include_aliases) const {
942 Args cmd_words(cmd_str); // Break up the command string into words, in case
Kate Stoneb9c1b512016-09-06 20:57:50 +0000943 // it's a multi-word command.
944 CommandObjectSP ret_val; // Possibly empty return value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000945
Zachary Turnera4496982016-10-05 21:14:38 +0000946 if (cmd_str.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000947 return ret_val;
948
949 if (cmd_words.GetArgumentCount() == 1)
Zachary Turnera4496982016-10-05 21:14:38 +0000950 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000951 else {
952 // We have a multi-word command (seemingly), so we need to do more work.
953 // First, get the cmd_obj_sp for the first word in the command.
Zachary Turnera4496982016-10-05 21:14:38 +0000954 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000955 include_aliases, true, nullptr);
956 if (cmd_obj_sp.get() != nullptr) {
957 // Loop through the rest of the words in the command (everything passed in
958 // was supposed to be part of a
959 // command name), and find the appropriate sub-command SP for each command
960 // word....
961 size_t end = cmd_words.GetArgumentCount();
962 for (size_t j = 1; j < end; ++j) {
963 if (cmd_obj_sp->IsMultiwordObject()) {
964 cmd_obj_sp =
965 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
966 if (cmd_obj_sp.get() == nullptr)
967 // The sub-command name was invalid. Fail and return the empty
968 // 'ret_val'.
969 return ret_val;
970 } else
971 // We have more words in the command name, but we don't have a
Zachary Turnera4496982016-10-05 21:14:38 +0000972 // multiword object. Fail and return empty 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000973 return ret_val;
974 }
975 // We successfully looped through all the command words and got valid
Zachary Turnera4496982016-10-05 21:14:38 +0000976 // command objects for them. Assign the last object retrieved to
977 // 'ret_val'.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978 ret_val = cmd_obj_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000979 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980 }
981 return ret_val;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000982}
983
Zachary Turnera4496982016-10-05 21:14:38 +0000984CommandObject *CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
985 StringList *matches) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000986 CommandObject *command_obj =
Zachary Turnera4496982016-10-05 21:14:38 +0000987 GetCommandSP(cmd_str, false, true, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000988
Kate Stoneb9c1b512016-09-06 20:57:50 +0000989 // If we didn't find an exact match to the command string in the commands,
990 // look in
991 // the aliases.
992
993 if (command_obj)
994 return command_obj;
995
Zachary Turnera4496982016-10-05 21:14:38 +0000996 command_obj = GetCommandSP(cmd_str, true, true, matches).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000997
998 if (command_obj)
999 return command_obj;
1000
1001 // If there wasn't an exact match then look for an inexact one in just the
1002 // commands
Zachary Turnera4496982016-10-05 21:14:38 +00001003 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004
1005 // Finally, if there wasn't an inexact match among the commands, look for an
1006 // inexact
1007 // match in both the commands and aliases.
1008
1009 if (command_obj) {
1010 if (matches)
1011 matches->AppendString(command_obj->GetCommandName());
1012 return command_obj;
1013 }
1014
Zachary Turnera4496982016-10-05 21:14:38 +00001015 return GetCommandSP(cmd_str, true, false, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001016}
1017
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018bool CommandInterpreter::CommandExists(const char *cmd) {
1019 return m_command_dict.find(cmd) != m_command_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001020}
1021
Kate Stoneb9c1b512016-09-06 20:57:50 +00001022bool CommandInterpreter::GetAliasFullName(const char *cmd,
1023 std::string &full_name) {
1024 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1025 if (exact_match) {
1026 full_name.assign(cmd);
1027 return exact_match;
1028 } else {
1029 StringList matches;
1030 size_t num_alias_matches;
1031 num_alias_matches =
1032 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1033 if (num_alias_matches == 1) {
1034 // Make sure this isn't shadowing a command in the regular command space:
1035 StringList regular_matches;
1036 const bool include_aliases = false;
1037 const bool exact = false;
1038 CommandObjectSP cmd_obj_sp(
1039 GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1040 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1041 return false;
1042 else {
1043 full_name.assign(matches.GetStringAtIndex(0));
1044 return true;
1045 }
1046 } else
1047 return false;
1048 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001049}
1050
Kate Stoneb9c1b512016-09-06 20:57:50 +00001051bool CommandInterpreter::AliasExists(const char *cmd) {
1052 return m_alias_dict.find(cmd) != m_alias_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001053}
1054
Kate Stoneb9c1b512016-09-06 20:57:50 +00001055bool CommandInterpreter::UserCommandExists(const char *cmd) {
1056 return m_user_dict.find(cmd) != m_user_dict.end();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001057}
1058
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059CommandAlias *
1060CommandInterpreter::AddAlias(const char *alias_name,
1061 lldb::CommandObjectSP &command_obj_sp,
1062 const char *args_string) {
1063 if (command_obj_sp.get())
1064 assert((this == &command_obj_sp->GetCommandInterpreter()) &&
1065 "tried to add a CommandObject from a different interpreter");
1066
1067 std::unique_ptr<CommandAlias> command_alias_up(
1068 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1069
1070 if (command_alias_up && command_alias_up->IsValid()) {
1071 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1072 return command_alias_up.release();
1073 }
1074
1075 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001076}
1077
Kate Stoneb9c1b512016-09-06 20:57:50 +00001078bool CommandInterpreter::RemoveAlias(const char *alias_name) {
1079 auto pos = m_alias_dict.find(alias_name);
1080 if (pos != m_alias_dict.end()) {
1081 m_alias_dict.erase(pos);
1082 return true;
1083 }
1084 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001085}
1086
Kate Stoneb9c1b512016-09-06 20:57:50 +00001087bool CommandInterpreter::RemoveCommand(const char *cmd) {
1088 auto pos = m_command_dict.find(cmd);
1089 if (pos != m_command_dict.end()) {
1090 if (pos->second->IsRemovable()) {
1091 // Only regular expression objects or python commands are removable
1092 m_command_dict.erase(pos);
1093 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001094 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001095 }
1096 return false;
1097}
1098bool CommandInterpreter::RemoveUser(const char *alias_name) {
1099 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1100 if (pos != m_user_dict.end()) {
1101 m_user_dict.erase(pos);
1102 return true;
1103 }
1104 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001105}
1106
Kate Stoneb9c1b512016-09-06 20:57:50 +00001107void CommandInterpreter::GetHelp(CommandReturnObject &result,
1108 uint32_t cmd_types) {
1109 const char *help_prologue = GetDebugger().GetIOHandlerHelpPrologue();
1110 if (help_prologue != NULL) {
1111 OutputFormattedHelpText(result.GetOutputStream(), NULL, help_prologue);
1112 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001113
Kate Stoneb9c1b512016-09-06 20:57:50 +00001114 CommandObject::CommandMap::const_iterator pos;
1115 size_t max_len = FindLongestCommandWord(m_command_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116
Kate Stoneb9c1b512016-09-06 20:57:50 +00001117 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1118 result.AppendMessage("Debugger commands:");
1119 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001120
Kate Stoneb9c1b512016-09-06 20:57:50 +00001121 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1122 if (!(cmd_types & eCommandTypesHidden) &&
1123 (pos->first.compare(0, 1, "_") == 0))
1124 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001125
Kate Stoneb9c1b512016-09-06 20:57:50 +00001126 OutputFormattedHelpText(result.GetOutputStream(), pos->first.c_str(),
1127 "--", pos->second->GetHelp(), max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001128 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001129 result.AppendMessage("");
1130 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001131
Kate Stoneb9c1b512016-09-06 20:57:50 +00001132 if (!m_alias_dict.empty() &&
1133 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1134 result.AppendMessageWithFormat(
1135 "Current command abbreviations "
1136 "(type '%shelp command alias' for more info):\n",
1137 GetCommandPrefix());
1138 result.AppendMessage("");
1139 max_len = FindLongestCommandWord(m_alias_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001140
Kate Stoneb9c1b512016-09-06 20:57:50 +00001141 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1142 ++alias_pos) {
1143 OutputFormattedHelpText(result.GetOutputStream(),
1144 alias_pos->first.c_str(), "--",
1145 alias_pos->second->GetHelp(), max_len);
Jim Ingham16e0c682011-08-12 23:34:31 +00001146 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001147 result.AppendMessage("");
1148 }
Greg Clayton14a35512011-09-11 00:01:44 +00001149
Kate Stoneb9c1b512016-09-06 20:57:50 +00001150 if (!m_user_dict.empty() &&
1151 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1152 result.AppendMessage("Current user-defined commands:");
1153 result.AppendMessage("");
1154 max_len = FindLongestCommandWord(m_user_dict);
1155 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
1156 OutputFormattedHelpText(result.GetOutputStream(), pos->first.c_str(),
1157 "--", pos->second->GetHelp(), max_len);
Greg Clayton14a35512011-09-11 00:01:44 +00001158 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001159 result.AppendMessage("");
1160 }
Greg Clayton14a35512011-09-11 00:01:44 +00001161
Kate Stoneb9c1b512016-09-06 20:57:50 +00001162 result.AppendMessageWithFormat(
1163 "For more information on any command, type '%shelp <command-name>'.\n",
1164 GetCommandPrefix());
Greg Clayton44d93782014-01-27 23:43:24 +00001165}
1166
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001167CommandObject *
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168CommandInterpreter::GetCommandObjectForCommand(std::string &command_string) {
1169 // This function finds the final, lowest-level, alias-resolved command object
1170 // whose 'Execute' function will
1171 // eventually be invoked by the given command line.
1172
1173 CommandObject *cmd_obj = nullptr;
1174 size_t start = command_string.find_first_not_of(k_white_space);
1175 size_t end = 0;
1176 bool done = false;
1177 while (!done) {
1178 if (start != std::string::npos) {
1179 // Get the next word from command_string.
1180 end = command_string.find_first_of(k_white_space, start);
1181 if (end == std::string::npos)
1182 end = command_string.size();
1183 std::string cmd_word = command_string.substr(start, end - start);
1184
1185 if (cmd_obj == nullptr)
1186 // Since cmd_obj is NULL we are on our first time through this loop.
1187 // Check to see if cmd_word is a valid
1188 // command or alias.
Zachary Turnera4496982016-10-05 21:14:38 +00001189 cmd_obj = GetCommandObject(cmd_word);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190 else if (cmd_obj->IsMultiwordObject()) {
1191 // Our current object is a multi-word object; see if the cmd_word is a
1192 // valid sub-command for our object.
1193 CommandObject *sub_cmd_obj =
1194 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1195 if (sub_cmd_obj)
1196 cmd_obj = sub_cmd_obj;
1197 else // cmd_word was not a valid sub-command word, so we are done
1198 done = true;
1199 } else
1200 // We have a cmd_obj and it is not a multi-word object, so we are done.
1201 done = true;
1202
1203 // If we didn't find a valid command object, or our command object is not
1204 // a multi-word object, or
1205 // we are at the end of the command_string, then we are done. Otherwise,
1206 // find the start of the
1207 // next word.
1208
1209 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1210 end >= command_string.size())
1211 done = true;
1212 else
1213 start = command_string.find_first_not_of(k_white_space, end);
1214 } else
1215 // Unable to find any more words.
1216 done = true;
1217 }
1218
1219 if (end == command_string.size())
1220 command_string.clear();
1221 else
1222 command_string = command_string.substr(end);
1223
1224 return cmd_obj;
1225}
1226
1227static const char *k_valid_command_chars =
1228 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1229static void StripLeadingSpaces(std::string &s) {
1230 if (!s.empty()) {
1231 size_t pos = s.find_first_not_of(k_white_space);
1232 if (pos == std::string::npos)
1233 s.clear();
1234 else if (pos == 0)
1235 return;
1236 s.erase(0, pos);
1237 }
1238}
1239
1240static size_t FindArgumentTerminator(const std::string &s) {
1241 const size_t s_len = s.size();
1242 size_t offset = 0;
1243 while (offset < s_len) {
1244 size_t pos = s.find("--", offset);
1245 if (pos == std::string::npos)
1246 break;
1247 if (pos > 0) {
1248 if (isspace(s[pos - 1])) {
1249 // Check if the string ends "\s--" (where \s is a space character)
1250 // or if we have "\s--\s".
1251 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1252 return pos;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001253 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001254 }
1255 }
1256 offset = pos + 2;
1257 }
1258 return std::string::npos;
1259}
1260
1261static bool ExtractCommand(std::string &command_string, std::string &command,
1262 std::string &suffix, char &quote_char) {
1263 command.clear();
1264 suffix.clear();
1265 StripLeadingSpaces(command_string);
1266
1267 bool result = false;
1268 quote_char = '\0';
1269
1270 if (!command_string.empty()) {
1271 const char first_char = command_string[0];
1272 if (first_char == '\'' || first_char == '"') {
1273 quote_char = first_char;
1274 const size_t end_quote_pos = command_string.find(quote_char, 1);
1275 if (end_quote_pos == std::string::npos) {
1276 command.swap(command_string);
1277 command_string.erase();
1278 } else {
1279 command.assign(command_string, 1, end_quote_pos - 1);
1280 if (end_quote_pos + 1 < command_string.size())
1281 command_string.erase(0, command_string.find_first_not_of(
1282 k_white_space, end_quote_pos + 1));
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001283 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001284 command_string.erase();
1285 }
1286 } else {
1287 const size_t first_space_pos =
1288 command_string.find_first_of(k_white_space);
1289 if (first_space_pos == std::string::npos) {
1290 command.swap(command_string);
1291 command_string.erase();
1292 } else {
1293 command.assign(command_string, 0, first_space_pos);
1294 command_string.erase(0, command_string.find_first_not_of(
1295 k_white_space, first_space_pos));
1296 }
1297 }
1298 result = true;
1299 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001300
Kate Stoneb9c1b512016-09-06 20:57:50 +00001301 if (!command.empty()) {
1302 // actual commands can't start with '-' or '_'
1303 if (command[0] != '-' && command[0] != '_') {
1304 size_t pos = command.find_first_not_of(k_valid_command_chars);
1305 if (pos > 0 && pos != std::string::npos) {
1306 suffix.assign(command.begin() + pos, command.end());
1307 command.erase(pos);
1308 }
1309 }
1310 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001311
Kate Stoneb9c1b512016-09-06 20:57:50 +00001312 return result;
1313}
1314
1315CommandObject *CommandInterpreter::BuildAliasResult(
1316 const char *alias_name, std::string &raw_input_string,
1317 std::string &alias_result, CommandReturnObject &result) {
1318 CommandObject *alias_cmd_obj = nullptr;
1319 Args cmd_args(raw_input_string);
1320 alias_cmd_obj = GetCommandObject(alias_name);
1321 StreamString result_str;
1322
Zachary Turner5c28c662016-10-03 23:20:36 +00001323 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1324 alias_result.clear();
1325 return alias_cmd_obj;
1326 }
1327 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1328 ((CommandAlias *)alias_cmd_obj)->Desugar();
1329 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1330 alias_cmd_obj = desugared.first.get();
1331 std::string alias_name_str = alias_name;
1332 if ((cmd_args.GetArgumentCount() == 0) ||
1333 (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0))
1334 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001335
Zachary Turnera4496982016-10-05 21:14:38 +00001336 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001337
Zachary Turner5c28c662016-10-03 23:20:36 +00001338 if (!option_arg_vector_sp.get()) {
1339 alias_result = result_str.GetData();
1340 return alias_cmd_obj;
1341 }
1342 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001343
Zachary Turner5c28c662016-10-03 23:20:36 +00001344 int value_type;
1345 std::string option;
1346 std::string value;
1347 for (const auto &entry : *option_arg_vector) {
1348 std::tie(option, value_type, value) = entry;
1349 if (option == "<argument>") {
1350 result_str.Printf(" %s", value.c_str());
1351 continue;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001352 }
1353
Zachary Turner5c28c662016-10-03 23:20:36 +00001354 result_str.Printf(" %s", option.c_str());
1355 if (value_type == OptionParser::eNoArgument)
1356 continue;
1357
1358 if (value_type != OptionParser::eOptionalArgument)
1359 result_str.Printf(" ");
1360 int index = GetOptionArgumentPosition(value.c_str());
1361 if (index == 0)
1362 result_str.Printf("%s", value.c_str());
1363 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1364
1365 result.AppendErrorWithFormat("Not enough arguments provided; you "
1366 "need at least %d arguments to use "
1367 "this alias.\n",
1368 index);
1369 result.SetStatus(eReturnStatusFailed);
1370 return nullptr;
Zachary Turnerf9fd8cb2016-10-04 01:34:39 +00001371 } else {
1372 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1373 if (strpos != std::string::npos)
1374 raw_input_string = raw_input_string.erase(
1375 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1376 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
Zachary Turner5c28c662016-10-03 23:20:36 +00001377 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001378 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001379
1380 alias_result = result_str.GetData();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001381 return alias_cmd_obj;
1382}
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001383
Kate Stoneb9c1b512016-09-06 20:57:50 +00001384Error CommandInterpreter::PreprocessCommand(std::string &command) {
1385 // The command preprocessor needs to do things to the command
1386 // line before any parsing of arguments or anything else is done.
1387 // The only current stuff that gets preprocessed is anything enclosed
1388 // in backtick ('`') characters is evaluated as an expression and
1389 // the result of the expression must be a scalar that can be substituted
1390 // into the command. An example would be:
1391 // (lldb) memory read `$rsp + 20`
1392 Error error; // Error for any expressions that might not evaluate
1393 size_t start_backtick;
1394 size_t pos = 0;
1395 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1396 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
1397 // The backtick was preceded by a '\' character, remove the slash
1398 // and don't treat the backtick as the start of an expression
1399 command.erase(start_backtick - 1, 1);
1400 // No need to add one to start_backtick since we just deleted a char
1401 pos = start_backtick;
1402 } else {
1403 const size_t expr_content_start = start_backtick + 1;
1404 const size_t end_backtick = command.find('`', expr_content_start);
1405 if (end_backtick == std::string::npos)
1406 return error;
1407 else if (end_backtick == expr_content_start) {
1408 // Empty expression (two backticks in a row)
1409 command.erase(start_backtick, 2);
1410 } else {
1411 std::string expr_str(command, expr_content_start,
1412 end_backtick - expr_content_start);
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001413
Kate Stoneb9c1b512016-09-06 20:57:50 +00001414 ExecutionContext exe_ctx(GetExecutionContext());
1415 Target *target = exe_ctx.GetTargetPtr();
1416 // Get a dummy target to allow for calculator mode while processing
1417 // backticks.
1418 // This also helps break the infinite loop caused when target is null.
1419 if (!target)
1420 target = m_debugger.GetDummyTarget();
1421 if (target) {
1422 ValueObjectSP expr_result_valobj_sp;
1423
1424 EvaluateExpressionOptions options;
1425 options.SetCoerceToId(false);
1426 options.SetUnwindOnError(true);
1427 options.SetIgnoreBreakpoints(true);
1428 options.SetKeepInMemory(false);
1429 options.SetTryAllThreads(true);
1430 options.SetTimeoutUsec(0);
1431
1432 ExpressionResults expr_result = target->EvaluateExpression(
1433 expr_str.c_str(), exe_ctx.GetFramePtr(), expr_result_valobj_sp,
1434 options);
1435
1436 if (expr_result == eExpressionCompleted) {
1437 Scalar scalar;
1438 if (expr_result_valobj_sp)
1439 expr_result_valobj_sp =
1440 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1441 expr_result_valobj_sp->GetDynamicValueType(), true);
1442 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1443 command.erase(start_backtick, end_backtick - start_backtick + 1);
1444 StreamString value_strm;
1445 const bool show_type = false;
1446 scalar.GetValue(&value_strm, show_type);
1447 size_t value_string_size = value_strm.GetSize();
1448 if (value_string_size) {
1449 command.insert(start_backtick, value_strm.GetData(),
1450 value_string_size);
1451 pos = start_backtick + value_string_size;
1452 continue;
1453 } else {
1454 error.SetErrorStringWithFormat("expression value didn't result "
1455 "in a scalar value for the "
1456 "expression '%s'",
1457 expr_str.c_str());
1458 }
1459 } else {
1460 error.SetErrorStringWithFormat("expression value didn't result "
1461 "in a scalar value for the "
1462 "expression '%s'",
1463 expr_str.c_str());
1464 }
1465 } else {
1466 if (expr_result_valobj_sp)
1467 error = expr_result_valobj_sp->GetError();
1468 if (error.Success()) {
1469
1470 switch (expr_result) {
1471 case eExpressionSetupError:
1472 error.SetErrorStringWithFormat(
1473 "expression setup error for the expression '%s'",
1474 expr_str.c_str());
1475 break;
1476 case eExpressionParseError:
1477 error.SetErrorStringWithFormat(
1478 "expression parse error for the expression '%s'",
1479 expr_str.c_str());
1480 break;
1481 case eExpressionResultUnavailable:
1482 error.SetErrorStringWithFormat(
1483 "expression error fetching result for the expression '%s'",
1484 expr_str.c_str());
1485 break;
1486 case eExpressionCompleted:
1487 break;
1488 case eExpressionDiscarded:
1489 error.SetErrorStringWithFormat(
1490 "expression discarded for the expression '%s'",
1491 expr_str.c_str());
1492 break;
1493 case eExpressionInterrupted:
1494 error.SetErrorStringWithFormat(
1495 "expression interrupted for the expression '%s'",
1496 expr_str.c_str());
1497 break;
1498 case eExpressionHitBreakpoint:
1499 error.SetErrorStringWithFormat(
1500 "expression hit breakpoint for the expression '%s'",
1501 expr_str.c_str());
1502 break;
1503 case eExpressionTimedOut:
1504 error.SetErrorStringWithFormat(
1505 "expression timed out for the expression '%s'",
1506 expr_str.c_str());
1507 break;
1508 case eExpressionStoppedForDebug:
1509 error.SetErrorStringWithFormat("expression stop at entry point "
1510 "for debugging for the "
1511 "expression '%s'",
1512 expr_str.c_str());
1513 break;
1514 }
1515 }
1516 }
1517 }
1518 }
1519 if (error.Fail())
1520 break;
1521 }
1522 }
1523 return error;
1524}
1525
1526bool CommandInterpreter::HandleCommand(const char *command_line,
1527 LazyBool lazy_add_to_history,
1528 CommandReturnObject &result,
1529 ExecutionContext *override_context,
1530 bool repeat_on_empty_command,
1531 bool no_context_switching)
1532
1533{
1534
1535 std::string command_string(command_line);
1536 std::string original_command_string(command_line);
1537
1538 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
1539 Host::SetCrashDescriptionWithFormat("HandleCommand(command = \"%s\")",
1540 command_line);
1541
1542 // Make a scoped cleanup object that will clear the crash description string
1543 // on exit of this function.
1544 lldb_utility::CleanUp<const char *> crash_description_cleanup(
1545 nullptr, Host::SetCrashDescription);
1546
1547 if (log)
1548 log->Printf("Processing command: %s", command_line);
1549
1550 Timer scoped_timer(LLVM_PRETTY_FUNCTION, "Handling command: %s.",
1551 command_line);
1552
1553 if (!no_context_switching)
1554 UpdateExecutionContext(override_context);
1555
1556 bool add_to_history;
1557 if (lazy_add_to_history == eLazyBoolCalculate)
1558 add_to_history = (m_command_source_depth == 0);
1559 else
1560 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1561
1562 bool empty_command = false;
1563 bool comment_command = false;
1564 if (command_string.empty())
1565 empty_command = true;
1566 else {
1567 const char *k_space_characters = "\t\n\v\f\r ";
1568
1569 size_t non_space = command_string.find_first_not_of(k_space_characters);
1570 // Check for empty line or comment line (lines whose first
1571 // non-space character is the comment character for this interpreter)
1572 if (non_space == std::string::npos)
1573 empty_command = true;
1574 else if (command_string[non_space] == m_comment_char)
1575 comment_command = true;
1576 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
1577 const char *history_string =
1578 m_command_history.FindString(command_string.c_str() + non_space);
1579 if (history_string == nullptr) {
1580 result.AppendErrorWithFormat("Could not find entry: %s in history",
1581 command_string.c_str());
1582 result.SetStatus(eReturnStatusFailed);
1583 return false;
1584 }
1585 add_to_history = false;
1586 command_string = history_string;
1587 original_command_string = history_string;
1588 }
1589 }
1590
1591 if (empty_command) {
1592 if (repeat_on_empty_command) {
1593 if (m_command_history.IsEmpty()) {
1594 result.AppendError("empty command");
1595 result.SetStatus(eReturnStatusFailed);
1596 return false;
1597 } else {
1598 command_line = m_repeat_command.c_str();
1599 command_string = command_line;
1600 original_command_string = command_line;
1601 if (m_repeat_command.empty()) {
1602 result.AppendErrorWithFormat("No auto repeat.\n");
1603 result.SetStatus(eReturnStatusFailed);
1604 return false;
1605 }
1606 }
1607 add_to_history = false;
1608 } else {
1609 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1610 return true;
1611 }
1612 } else if (comment_command) {
1613 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1614 return true;
1615 }
1616
1617 Error error(PreprocessCommand(command_string));
1618
1619 if (error.Fail()) {
1620 result.AppendError(error.AsCString());
1621 result.SetStatus(eReturnStatusFailed);
1622 return false;
1623 }
1624
1625 // Phase 1.
1626
1627 // Before we do ANY kind of argument processing, we need to figure out what
1628 // the real/final command object is for the specified command. This gets
1629 // complicated by the fact that the user could have specified an alias, and,
1630 // in translating the alias, there may also be command options and/or even
1631 // data (including raw text strings) that need to be found and inserted into
1632 // the command line as part of the translation. So this first step is plain
1633 // look-up and replacement, resulting in:
1634 // 1. the command object whose Execute method will actually be called
1635 // 2. a revised command string, with all substitutions and replacements
1636 // taken care of
1637 // From 1 above, we can determine whether the Execute function wants raw
1638 // input or not.
1639
1640 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1641
1642 // Although the user may have abbreviated the command, the command_string now
1643 // has the command expanded to the full name. For example, if the input
1644 // was "br s -n main", command_string is now "breakpoint set -n main".
Kate Stoneb9c1b512016-09-06 20:57:50 +00001645 if (log) {
Zachary Turnera4496982016-10-05 21:14:38 +00001646 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1647 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001648 log->Printf("HandleCommand, (revised) command_string: '%s'",
1649 command_string.c_str());
1650 const bool wants_raw_input =
1651 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1652 log->Printf("HandleCommand, wants_raw_input:'%s'",
1653 wants_raw_input ? "True" : "False");
1654 }
1655
1656 // Phase 2.
1657 // Take care of things like setting up the history command & calling the
1658 // appropriate Execute method on the
1659 // CommandObject, with the appropriate arguments.
1660
1661 if (cmd_obj != nullptr) {
1662 if (add_to_history) {
1663 Args command_args(command_string);
1664 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1665 if (repeat_command != nullptr)
1666 m_repeat_command.assign(repeat_command);
1667 else
1668 m_repeat_command.assign(original_command_string.c_str());
1669
1670 m_command_history.AppendString(original_command_string);
1671 }
1672
1673 std::string remainder;
Zachary Turnera4496982016-10-05 21:14:38 +00001674 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001675 if (actual_cmd_name_len < command_string.length())
1676 remainder = command_string.substr(actual_cmd_name_len);
1677
1678 // Remove any initial spaces
1679 size_t pos = remainder.find_first_not_of(k_white_space);
1680 if (pos != 0 && pos != std::string::npos)
1681 remainder.erase(0, pos);
1682
1683 if (log)
1684 log->Printf(
1685 "HandleCommand, command line after removing command name(s): '%s'",
1686 remainder.c_str());
1687
1688 cmd_obj->Execute(remainder.c_str(), result);
1689 } else {
1690 // We didn't find the first command object, so complete the first argument.
1691 Args command_args(command_string);
1692 StringList matches;
1693 int num_matches;
1694 int cursor_index = 0;
1695 int cursor_char_position = strlen(command_args.GetArgumentAtIndex(0));
1696 bool word_complete;
1697 num_matches = HandleCompletionMatches(command_args, cursor_index,
1698 cursor_char_position, 0, -1,
1699 word_complete, matches);
1700
1701 if (num_matches > 0) {
1702 std::string error_msg;
1703 error_msg.assign("ambiguous command '");
1704 error_msg.append(command_args.GetArgumentAtIndex(0));
1705 error_msg.append("'.");
1706
1707 error_msg.append(" Possible completions:");
1708 for (int i = 0; i < num_matches; i++) {
1709 error_msg.append("\n\t");
1710 error_msg.append(matches.GetStringAtIndex(i));
1711 }
1712 error_msg.append("\n");
1713 result.AppendRawError(error_msg.c_str());
1714 } else
1715 result.AppendErrorWithFormat("Unrecognized command '%s'.\n",
1716 command_args.GetArgumentAtIndex(0));
1717
1718 result.SetStatus(eReturnStatusFailed);
1719 }
1720
1721 if (log)
1722 log->Printf("HandleCommand, command %s",
1723 (result.Succeeded() ? "succeeded" : "did not succeed"));
1724
1725 return result.Succeeded();
1726}
1727
1728int CommandInterpreter::HandleCompletionMatches(
1729 Args &parsed_line, int &cursor_index, int &cursor_char_position,
1730 int match_start_point, int max_return_elements, bool &word_complete,
1731 StringList &matches) {
1732 int num_command_matches = 0;
1733 bool look_for_subcommand = false;
1734
1735 // For any of the command completions a unique match will be a complete word.
1736 word_complete = true;
1737
1738 if (cursor_index == -1) {
1739 // We got nothing on the command line, so return the list of commands
1740 bool include_aliases = true;
1741 num_command_matches =
1742 GetCommandNamesMatchingPartialString("", include_aliases, matches);
1743 } else if (cursor_index == 0) {
1744 // The cursor is in the first argument, so just do a lookup in the
1745 // dictionary.
1746 CommandObject *cmd_obj =
1747 GetCommandObject(parsed_line.GetArgumentAtIndex(0), &matches);
1748 num_command_matches = matches.GetSize();
1749
1750 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
1751 matches.GetStringAtIndex(0) != nullptr &&
1752 strcmp(parsed_line.GetArgumentAtIndex(0),
1753 matches.GetStringAtIndex(0)) == 0) {
1754 if (parsed_line.GetArgumentCount() == 1) {
1755 word_complete = true;
1756 } else {
1757 look_for_subcommand = true;
1758 num_command_matches = 0;
1759 matches.DeleteStringAtIndex(0);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001760 parsed_line.AppendArgument(llvm::StringRef());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001761 cursor_index++;
1762 cursor_char_position = 0;
1763 }
1764 }
1765 }
1766
1767 if (cursor_index > 0 || look_for_subcommand) {
1768 // We are completing further on into a commands arguments, so find the
1769 // command and tell it
1770 // to complete the command.
1771 // First see if there is a matching initial command:
1772 CommandObject *command_object =
1773 GetCommandObject(parsed_line.GetArgumentAtIndex(0));
1774 if (command_object == nullptr) {
1775 return 0;
1776 } else {
1777 parsed_line.Shift();
1778 cursor_index--;
1779 num_command_matches = command_object->HandleCompletion(
1780 parsed_line, cursor_index, cursor_char_position, match_start_point,
1781 max_return_elements, word_complete, matches);
1782 }
1783 }
1784
1785 return num_command_matches;
1786}
1787
1788int CommandInterpreter::HandleCompletion(
1789 const char *current_line, const char *cursor, const char *last_char,
1790 int match_start_point, int max_return_elements, StringList &matches) {
1791 // We parse the argument up to the cursor, so the last argument in parsed_line
1792 // is
1793 // the one containing the cursor, and the cursor is after the last character.
1794
1795 Args parsed_line(llvm::StringRef(current_line, last_char - current_line));
1796 Args partial_parsed_line(
1797 llvm::StringRef(current_line, cursor - current_line));
1798
1799 // Don't complete comments, and if the line we are completing is just the
1800 // history repeat character,
1801 // substitute the appropriate history line.
1802 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1803 if (first_arg) {
1804 if (first_arg[0] == m_comment_char)
1805 return 0;
1806 else if (first_arg[0] == CommandHistory::g_repeat_char) {
1807 const char *history_string = m_command_history.FindString(first_arg);
1808 if (history_string != nullptr) {
1809 matches.Clear();
1810 matches.InsertStringAtIndex(0, history_string);
1811 return -2;
1812 } else
1813 return 0;
1814 }
1815 }
1816
1817 int num_args = partial_parsed_line.GetArgumentCount();
1818 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1819 int cursor_char_position;
1820
1821 if (cursor_index == -1)
1822 cursor_char_position = 0;
1823 else
1824 cursor_char_position =
1825 strlen(partial_parsed_line.GetArgumentAtIndex(cursor_index));
1826
1827 if (cursor > current_line && cursor[-1] == ' ') {
1828 // We are just after a space. If we are in an argument, then we will
1829 // continue
1830 // parsing, but if we are between arguments, then we have to complete
1831 // whatever the next
1832 // element would be.
1833 // We can distinguish the two cases because if we are in an argument (e.g.
1834 // because the space is
1835 // protected by a quote) then the space will also be in the parsed
1836 // argument...
1837
1838 const char *current_elem =
1839 partial_parsed_line.GetArgumentAtIndex(cursor_index);
1840 if (cursor_char_position == 0 ||
1841 current_elem[cursor_char_position - 1] != ' ') {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001842 parsed_line.InsertArgumentAtIndex(cursor_index + 1, llvm::StringRef(),
1843 '\0');
Kate Stoneb9c1b512016-09-06 20:57:50 +00001844 cursor_index++;
1845 cursor_char_position = 0;
1846 }
1847 }
1848
1849 int num_command_matches;
1850
1851 matches.Clear();
1852
1853 // Only max_return_elements == -1 is supported at present:
1854 assert(max_return_elements == -1);
1855 bool word_complete;
1856 num_command_matches = HandleCompletionMatches(
1857 parsed_line, cursor_index, cursor_char_position, match_start_point,
1858 max_return_elements, word_complete, matches);
1859
1860 if (num_command_matches <= 0)
1861 return num_command_matches;
1862
1863 if (num_args == 0) {
1864 // If we got an empty string, insert nothing.
1865 matches.InsertStringAtIndex(0, "");
1866 } else {
1867 // Now figure out if there is a common substring, and if so put that in
1868 // element 0, otherwise
1869 // put an empty string in element 0.
1870 std::string command_partial_str;
1871 if (cursor_index >= 0)
1872 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1873 parsed_line.GetArgumentAtIndex(cursor_index) +
1874 cursor_char_position);
1875
1876 std::string common_prefix;
1877 matches.LongestCommonPrefix(common_prefix);
1878 const size_t partial_name_len = command_partial_str.size();
1879 common_prefix.erase(0, partial_name_len);
1880
1881 // If we matched a unique single command, add a space...
1882 // Only do this if the completer told us this was a complete word,
1883 // however...
1884 if (num_command_matches == 1 && word_complete) {
1885 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1886 common_prefix =
1887 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1888 if (quote_char != '\0')
1889 common_prefix.push_back(quote_char);
1890 common_prefix.push_back(' ');
1891 }
1892 matches.InsertStringAtIndex(0, common_prefix.c_str());
1893 }
1894 return num_command_matches;
1895}
1896
1897CommandInterpreter::~CommandInterpreter() {}
1898
Zachary Turner514d8cd2016-09-23 18:06:53 +00001899void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001900 EventSP prompt_change_event_sp(
1901 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1902 ;
1903 BroadcastEvent(prompt_change_event_sp);
1904 if (m_command_io_handler_sp)
1905 m_command_io_handler_sp->SetPrompt(new_prompt);
1906}
1907
1908bool CommandInterpreter::Confirm(const char *message, bool default_answer) {
1909 // Check AutoConfirm first:
1910 if (m_debugger.GetAutoConfirm())
1911 return default_answer;
1912
1913 IOHandlerConfirm *confirm =
1914 new IOHandlerConfirm(m_debugger, message, default_answer);
1915 IOHandlerSP io_handler_sp(confirm);
1916 m_debugger.RunIOHandler(io_handler_sp);
1917 return confirm->GetResponse();
1918}
1919
1920CommandAlias *CommandInterpreter::GetAlias(const char *alias_name) {
1921 OptionArgVectorSP ret_val;
1922
1923 std::string alias(alias_name);
1924
1925 auto pos = m_alias_dict.find(alias);
1926 if (pos != m_alias_dict.end())
1927 return (CommandAlias *)pos->second.get();
1928
1929 return nullptr;
1930}
1931
Zachary Turnera4496982016-10-05 21:14:38 +00001932bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001933
Zachary Turnera4496982016-10-05 21:14:38 +00001934bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001935
Zachary Turnera4496982016-10-05 21:14:38 +00001936bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001937
Zachary Turnera4496982016-10-05 21:14:38 +00001938bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001939
1940void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1941 const char *alias_name,
1942 Args &cmd_args,
1943 std::string &raw_input_string,
1944 CommandReturnObject &result) {
1945 OptionArgVectorSP option_arg_vector_sp =
1946 GetAlias(alias_name)->GetOptionArguments();
1947
1948 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1949
1950 // Make sure that the alias name is the 0th element in cmd_args
1951 std::string alias_name_str = alias_name;
1952 if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)
Zachary Turner5c725f32016-09-19 21:56:59 +00001953 cmd_args.Unshift(alias_name_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001954
1955 Args new_args(alias_cmd_obj->GetCommandName());
1956 if (new_args.GetArgumentCount() == 2)
1957 new_args.Shift();
1958
1959 if (option_arg_vector_sp.get()) {
1960 if (wants_raw_input) {
1961 // We have a command that both has command options and takes raw input.
1962 // Make *sure* it has a
1963 // " -- " in the right place in the raw_input_string.
1964 size_t pos = raw_input_string.find(" -- ");
1965 if (pos == std::string::npos) {
1966 // None found; assume it goes at the beginning of the raw input string
1967 raw_input_string.insert(0, " -- ");
1968 }
1969 }
1970
1971 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1972 const size_t old_size = cmd_args.GetArgumentCount();
1973 std::vector<bool> used(old_size + 1, false);
1974
1975 used[0] = true;
1976
Zachary Turner5c28c662016-10-03 23:20:36 +00001977 int value_type;
1978 std::string option;
1979 std::string value;
1980 for (const auto &option_entry : *option_arg_vector) {
1981 std::tie(option, value_type, value) = option_entry;
1982 if (option == "<argument>") {
1983 if (!wants_raw_input || (value != "--")) {
1984 // Since we inserted this above, make sure we don't insert it twice
1985 new_args.AppendArgument(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001986 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001987 continue;
1988 }
1989
1990 if (value_type != OptionParser::eOptionalArgument)
1991 new_args.AppendArgument(option);
1992
1993 if (value == "<no-argument>")
1994 continue;
1995
1996 int index = GetOptionArgumentPosition(value.c_str());
1997 if (index == 0) {
1998 // value was NOT a positional argument; must be a real value
1999 if (value_type != OptionParser::eOptionalArgument)
2000 new_args.AppendArgument(value);
2001 else {
2002 char buffer[255];
2003 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2004 value.c_str());
2005 new_args.AppendArgument(llvm::StringRef(buffer));
2006 }
2007
2008 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
2009 result.AppendErrorWithFormat("Not enough arguments provided; you "
2010 "need at least %d arguments to use "
2011 "this alias.\n",
2012 index);
2013 result.SetStatus(eReturnStatusFailed);
2014 return;
2015 } else {
2016 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2017 size_t strpos =
2018 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
2019 if (strpos != std::string::npos) {
2020 raw_input_string = raw_input_string.erase(
2021 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2022 }
2023
2024 if (value_type != OptionParser::eOptionalArgument)
2025 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2026 else {
2027 char buffer[255];
2028 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2029 cmd_args.GetArgumentAtIndex(index));
2030 new_args.AppendArgument(buffer);
2031 }
2032 used[index] = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002033 }
2034 }
2035
2036 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j) {
2037 if (!used[j] && !wants_raw_input)
Zachary Turner5c28c662016-10-03 23:20:36 +00002038 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(j));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002039 }
2040
2041 cmd_args.Clear();
2042 cmd_args.SetArguments(new_args.GetArgumentCount(),
2043 new_args.GetConstArgumentVector());
2044 } else {
2045 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2046 // This alias was not created with any options; nothing further needs to be
2047 // done, unless it is a command that
2048 // wants raw input, in which case we need to clear the rest of the data from
2049 // cmd_args, since its in the raw
2050 // input string.
2051 if (wants_raw_input) {
2052 cmd_args.Clear();
2053 cmd_args.SetArguments(new_args.GetArgumentCount(),
2054 new_args.GetConstArgumentVector());
2055 }
2056 return;
2057 }
2058
2059 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2060 return;
2061}
2062
2063int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2064 int position = 0; // Any string that isn't an argument position, i.e. '%'
2065 // followed by an integer, gets a position
2066 // of zero.
2067
2068 const char *cptr = in_string;
2069
2070 // Does it start with '%'
2071 if (cptr[0] == '%') {
2072 ++cptr;
2073
2074 // Is the rest of it entirely digits?
2075 if (isdigit(cptr[0])) {
2076 const char *start = cptr;
2077 while (isdigit(cptr[0]))
2078 ++cptr;
2079
2080 // We've gotten to the end of the digits; are we at the end of the string?
2081 if (cptr[0] == '\0')
2082 position = atoi(start);
2083 }
2084 }
2085
2086 return position;
2087}
2088
2089void CommandInterpreter::SourceInitFile(bool in_cwd,
2090 CommandReturnObject &result) {
2091 FileSpec init_file;
2092 if (in_cwd) {
2093 ExecutionContext exe_ctx(GetExecutionContext());
2094 Target *target = exe_ctx.GetTargetPtr();
2095 if (target) {
2096 // In the current working directory we don't load any program specific
2097 // .lldbinit files, we only look for a ".lldbinit" file.
2098 if (m_skip_lldbinit_files)
2099 return;
2100
2101 LoadCWDlldbinitFile should_load =
2102 target->TargetProperties::GetLoadCWDlldbinitFile();
2103 if (should_load == eLoadCWDlldbinitWarn) {
2104 FileSpec dot_lldb(".lldbinit", true);
2105 llvm::SmallString<64> home_dir_path;
2106 llvm::sys::path::home_directory(home_dir_path);
2107 FileSpec homedir_dot_lldb(home_dir_path.c_str(), false);
2108 homedir_dot_lldb.AppendPathComponent(".lldbinit");
2109 homedir_dot_lldb.ResolvePath();
2110 if (dot_lldb.Exists() &&
2111 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2112 result.AppendErrorWithFormat(
2113 "There is a .lldbinit file in the current directory which is not "
2114 "being read.\n"
2115 "To silence this warning without sourcing in the local "
2116 ".lldbinit,\n"
2117 "add the following to the lldbinit file in your home directory:\n"
2118 " settings set target.load-cwd-lldbinit false\n"
2119 "To allow lldb to source .lldbinit files in the current working "
2120 "directory,\n"
2121 "set the value of this variable to true. Only do so if you "
2122 "understand and\n"
2123 "accept the security risk.");
2124 result.SetStatus(eReturnStatusFailed);
2125 return;
2126 }
2127 } else if (should_load == eLoadCWDlldbinitTrue) {
2128 init_file.SetFile("./.lldbinit", true);
2129 }
2130 }
2131 } else {
2132 // If we aren't looking in the current working directory we are looking
2133 // in the home directory. We will first see if there is an application
2134 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2135 // "-" and the name of the program. If this file doesn't exist, we fall
2136 // back to just the "~/.lldbinit" file. We also obey any requests to not
2137 // load the init files.
2138 llvm::SmallString<64> home_dir_path;
2139 llvm::sys::path::home_directory(home_dir_path);
2140 FileSpec profilePath(home_dir_path.c_str(), false);
2141 profilePath.AppendPathComponent(".lldbinit");
2142 std::string init_file_path = profilePath.GetPath();
2143
2144 if (m_skip_app_init_files == false) {
2145 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2146 const char *program_name = program_file_spec.GetFilename().AsCString();
2147
2148 if (program_name) {
2149 char program_init_file_name[PATH_MAX];
2150 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2151 "%s-%s", init_file_path.c_str(), program_name);
2152 init_file.SetFile(program_init_file_name, true);
2153 if (!init_file.Exists())
2154 init_file.Clear();
2155 }
2156 }
2157
2158 if (!init_file && !m_skip_lldbinit_files)
2159 init_file.SetFile(init_file_path.c_str(), false);
2160 }
2161
2162 // If the file exists, tell HandleCommand to 'source' it; this will do the
2163 // actual broadcasting
2164 // of the commands back to any appropriate listener (see
2165 // CommandObjectSource::Execute for more details).
2166
2167 if (init_file.Exists()) {
2168 const bool saved_batch = SetBatchCommandMode(true);
2169 CommandInterpreterRunOptions options;
2170 options.SetSilent(true);
2171 options.SetStopOnError(false);
2172 options.SetStopOnContinue(true);
2173
2174 HandleCommandsFromFile(init_file,
2175 nullptr, // Execution context
2176 options, result);
2177 SetBatchCommandMode(saved_batch);
2178 } else {
2179 // nothing to be done if the file doesn't exist
2180 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2181 }
2182}
2183
2184const char *CommandInterpreter::GetCommandPrefix() {
2185 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2186 return prefix == NULL ? "" : prefix;
2187}
2188
2189PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2190 PlatformSP platform_sp;
2191 if (prefer_target_platform) {
2192 ExecutionContext exe_ctx(GetExecutionContext());
2193 Target *target = exe_ctx.GetTargetPtr();
2194 if (target)
2195 platform_sp = target->GetPlatform();
2196 }
2197
2198 if (!platform_sp)
2199 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2200 return platform_sp;
2201}
2202
2203void CommandInterpreter::HandleCommands(const StringList &commands,
2204 ExecutionContext *override_context,
2205 CommandInterpreterRunOptions &options,
2206 CommandReturnObject &result) {
2207 size_t num_lines = commands.GetSize();
2208
2209 // If we are going to continue past a "continue" then we need to run the
2210 // commands synchronously.
2211 // Make sure you reset this value anywhere you return from the function.
2212
2213 bool old_async_execution = m_debugger.GetAsyncExecution();
2214
2215 // If we've been given an execution context, set it at the start, but don't
2216 // keep resetting it or we will
2217 // cause series of commands that change the context, then do an operation that
2218 // relies on that context to fail.
2219
2220 if (override_context != nullptr)
2221 UpdateExecutionContext(override_context);
2222
2223 if (!options.GetStopOnContinue()) {
2224 m_debugger.SetAsyncExecution(false);
2225 }
2226
2227 for (size_t idx = 0; idx < num_lines; idx++) {
2228 const char *cmd = commands.GetStringAtIndex(idx);
2229 if (cmd[0] == '\0')
2230 continue;
2231
2232 if (options.GetEchoCommands()) {
Zachary Turner514d8cd2016-09-23 18:06:53 +00002233 // TODO: Add Stream support.
2234 result.AppendMessageWithFormat("%s %s\n",
2235 m_debugger.GetPrompt().str().c_str(), cmd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002236 }
2237
2238 CommandReturnObject tmp_result;
2239 // If override_context is not NULL, pass no_context_switching = true for
2240 // HandleCommand() since we updated our context already.
2241
2242 // We might call into a regex or alias command, in which case the
2243 // add_to_history will get lost. This
2244 // m_command_source_depth dingus is the way we turn off adding to the
2245 // history in that case, so set it up here.
2246 if (!options.GetAddToHistory())
2247 m_command_source_depth++;
2248 bool success =
2249 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2250 nullptr, /* override_context */
2251 true, /* repeat_on_empty_command */
2252 override_context != nullptr /* no_context_switching */);
2253 if (!options.GetAddToHistory())
2254 m_command_source_depth--;
2255
2256 if (options.GetPrintResults()) {
2257 if (tmp_result.Succeeded())
2258 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
2259 }
2260
2261 if (!success || !tmp_result.Succeeded()) {
2262 const char *error_msg = tmp_result.GetErrorData();
2263 if (error_msg == nullptr || error_msg[0] == '\0')
2264 error_msg = "<unknown error>.\n";
2265 if (options.GetStopOnError()) {
2266 result.AppendErrorWithFormat(
2267 "Aborting reading of commands after command #%" PRIu64
2268 ": '%s' failed with %s",
2269 (uint64_t)idx, cmd, error_msg);
2270 result.SetStatus(eReturnStatusFailed);
2271 m_debugger.SetAsyncExecution(old_async_execution);
2272 return;
2273 } else if (options.GetPrintResults()) {
2274 result.AppendMessageWithFormat("Command #%" PRIu64
2275 " '%s' failed with %s",
2276 (uint64_t)idx + 1, cmd, error_msg);
2277 }
2278 }
2279
2280 if (result.GetImmediateOutputStream())
2281 result.GetImmediateOutputStream()->Flush();
2282
2283 if (result.GetImmediateErrorStream())
2284 result.GetImmediateErrorStream()->Flush();
2285
2286 // N.B. Can't depend on DidChangeProcessState, because the state coming into
2287 // the command execution
2288 // could be running (for instance in Breakpoint Commands.
2289 // So we check the return value to see if it is has running in it.
2290 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2291 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2292 if (options.GetStopOnContinue()) {
2293 // If we caused the target to proceed, and we're going to stop in that
2294 // case, set the
2295 // status in our real result before returning. This is an error if the
2296 // continue was not the
2297 // last command in the set of commands to be run.
2298 if (idx != num_lines - 1)
2299 result.AppendErrorWithFormat(
2300 "Aborting reading of commands after command #%" PRIu64
2301 ": '%s' continued the target.\n",
2302 (uint64_t)idx + 1, cmd);
2303 else
2304 result.AppendMessageWithFormat("Command #%" PRIu64
2305 " '%s' continued the target.\n",
2306 (uint64_t)idx + 1, cmd);
2307
2308 result.SetStatus(tmp_result.GetStatus());
2309 m_debugger.SetAsyncExecution(old_async_execution);
2310
2311 return;
2312 }
2313 }
2314
2315 // Also check for "stop on crash here:
2316 bool should_stop = false;
2317 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2318 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2319 if (target_sp) {
2320 ProcessSP process_sp(target_sp->GetProcessSP());
2321 if (process_sp) {
2322 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2323 StopReason reason = thread_sp->GetStopReason();
2324 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2325 reason == eStopReasonInstrumentation) {
2326 should_stop = true;
2327 break;
2328 }
2329 }
2330 }
2331 }
2332 if (should_stop) {
2333 if (idx != num_lines - 1)
2334 result.AppendErrorWithFormat(
2335 "Aborting reading of commands after command #%" PRIu64
2336 ": '%s' stopped with a signal or exception.\n",
2337 (uint64_t)idx + 1, cmd);
2338 else
2339 result.AppendMessageWithFormat(
2340 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2341 (uint64_t)idx + 1, cmd);
2342
2343 result.SetStatus(tmp_result.GetStatus());
2344 m_debugger.SetAsyncExecution(old_async_execution);
2345
2346 return;
2347 }
2348 }
2349 }
2350
2351 result.SetStatus(eReturnStatusSuccessFinishResult);
2352 m_debugger.SetAsyncExecution(old_async_execution);
2353
2354 return;
2355}
2356
2357// Make flags that we can pass into the IOHandler so our delegates can do the
2358// right thing
2359enum {
2360 eHandleCommandFlagStopOnContinue = (1u << 0),
2361 eHandleCommandFlagStopOnError = (1u << 1),
2362 eHandleCommandFlagEchoCommand = (1u << 2),
2363 eHandleCommandFlagPrintResult = (1u << 3),
2364 eHandleCommandFlagStopOnCrash = (1u << 4)
2365};
2366
2367void CommandInterpreter::HandleCommandsFromFile(
2368 FileSpec &cmd_file, ExecutionContext *context,
2369 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2370 if (cmd_file.Exists()) {
2371 StreamFileSP input_file_sp(new StreamFile());
2372
2373 std::string cmd_file_path = cmd_file.GetPath();
2374 Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(),
2375 File::eOpenOptionRead);
2376
2377 if (error.Success()) {
2378 Debugger &debugger = GetDebugger();
2379
2380 uint32_t flags = 0;
2381
2382 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2383 if (m_command_source_flags.empty()) {
2384 // Stop on continue by default
2385 flags |= eHandleCommandFlagStopOnContinue;
2386 } else if (m_command_source_flags.back() &
2387 eHandleCommandFlagStopOnContinue) {
2388 flags |= eHandleCommandFlagStopOnContinue;
2389 }
2390 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2391 flags |= eHandleCommandFlagStopOnContinue;
2392 }
2393
2394 if (options.m_stop_on_error == eLazyBoolCalculate) {
2395 if (m_command_source_flags.empty()) {
2396 if (GetStopCmdSourceOnError())
2397 flags |= eHandleCommandFlagStopOnError;
2398 } else if (m_command_source_flags.back() &
2399 eHandleCommandFlagStopOnError) {
2400 flags |= eHandleCommandFlagStopOnError;
2401 }
2402 } else if (options.m_stop_on_error == eLazyBoolYes) {
2403 flags |= eHandleCommandFlagStopOnError;
2404 }
2405
2406 if (options.GetStopOnCrash()) {
2407 if (m_command_source_flags.empty()) {
2408 // Echo command by default
2409 flags |= eHandleCommandFlagStopOnCrash;
2410 } else if (m_command_source_flags.back() &
2411 eHandleCommandFlagStopOnCrash) {
2412 flags |= eHandleCommandFlagStopOnCrash;
2413 }
2414 }
2415
2416 if (options.m_echo_commands == eLazyBoolCalculate) {
2417 if (m_command_source_flags.empty()) {
2418 // Echo command by default
2419 flags |= eHandleCommandFlagEchoCommand;
2420 } else if (m_command_source_flags.back() &
2421 eHandleCommandFlagEchoCommand) {
2422 flags |= eHandleCommandFlagEchoCommand;
2423 }
2424 } else if (options.m_echo_commands == eLazyBoolYes) {
2425 flags |= eHandleCommandFlagEchoCommand;
2426 }
2427
2428 if (options.m_print_results == eLazyBoolCalculate) {
2429 if (m_command_source_flags.empty()) {
2430 // Print output by default
2431 flags |= eHandleCommandFlagPrintResult;
2432 } else if (m_command_source_flags.back() &
2433 eHandleCommandFlagPrintResult) {
2434 flags |= eHandleCommandFlagPrintResult;
2435 }
2436 } else if (options.m_print_results == eLazyBoolYes) {
2437 flags |= eHandleCommandFlagPrintResult;
2438 }
2439
2440 if (flags & eHandleCommandFlagPrintResult) {
2441 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2442 cmd_file_path.c_str());
2443 }
2444
2445 // Used for inheriting the right settings when "command source" might have
2446 // nested "command source" commands
2447 lldb::StreamFileSP empty_stream_sp;
2448 m_command_source_flags.push_back(flags);
2449 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2450 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2451 empty_stream_sp, // Pass in an empty stream so we inherit the top
2452 // input reader output stream
2453 empty_stream_sp, // Pass in an empty stream so we inherit the top
2454 // input reader error stream
2455 flags,
2456 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2457 // or written
Zachary Turner514d8cd2016-09-23 18:06:53 +00002458 debugger.GetPrompt(), llvm::StringRef(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00002459 false, // Not multi-line
2460 debugger.GetUseColor(), 0, *this));
2461 const bool old_async_execution = debugger.GetAsyncExecution();
2462
2463 // Set synchronous execution if we are not stopping on continue
2464 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2465 debugger.SetAsyncExecution(false);
2466
2467 m_command_source_depth++;
2468
2469 debugger.RunIOHandler(io_handler_sp);
2470 if (!m_command_source_flags.empty())
2471 m_command_source_flags.pop_back();
2472 m_command_source_depth--;
2473 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2474 debugger.SetAsyncExecution(old_async_execution);
2475 } else {
2476 result.AppendErrorWithFormat(
2477 "error: an error occurred read file '%s': %s\n",
2478 cmd_file_path.c_str(), error.AsCString());
2479 result.SetStatus(eReturnStatusFailed);
2480 }
2481
2482 } else {
2483 result.AppendErrorWithFormat(
2484 "Error reading commands from file %s - file not found.\n",
2485 cmd_file.GetFilename().AsCString("<Unknown>"));
2486 result.SetStatus(eReturnStatusFailed);
2487 return;
2488 }
2489}
2490
2491ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
2492 if (m_script_interpreter_sp)
2493 return m_script_interpreter_sp.get();
2494
2495 if (!can_create)
2496 return nullptr;
2497
2498 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2499 m_script_interpreter_sp =
2500 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2501 return m_script_interpreter_sp.get();
2502}
2503
2504bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2505
2506void CommandInterpreter::SetSynchronous(bool value) {
2507 m_synchronous_execution = value;
2508}
2509
2510void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2511 const char *prefix,
2512 const char *help_text) {
2513 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2514 if (prefix == NULL)
2515 prefix = "";
2516
2517 size_t prefix_width = strlen(prefix);
2518 size_t line_width_max = max_columns - prefix_width;
2519 const char *help_text_end = help_text + strlen(help_text);
2520 const char *line_start = help_text;
2521 if (line_width_max < 16)
2522 line_width_max = help_text_end - help_text + prefix_width;
2523
2524 strm.IndentMore(prefix_width);
2525 while (line_start < help_text_end) {
2526 // Break each line at the first newline or last space/tab before
2527 // the maximum number of characters that fit on a line. Lines with no
2528 // natural break are left unbroken to wrap.
2529 const char *line_end = help_text_end;
2530 const char *line_scan = line_start;
2531 const char *line_scan_end = help_text_end;
2532 while (line_scan < line_scan_end) {
2533 char next = *line_scan;
2534 if (next == '\t' || next == ' ') {
2535 line_end = line_scan;
2536 line_scan_end = line_start + line_width_max;
2537 } else if (next == '\n' || next == '\0') {
2538 line_end = line_scan;
2539 break;
2540 }
2541 ++line_scan;
2542 }
2543
2544 // Prefix the first line, indent subsequent lines to line up
2545 if (line_start == help_text)
2546 strm.Write(prefix, prefix_width);
2547 else
2548 strm.Indent();
2549 strm.Write(line_start, line_end - line_start);
2550 strm.EOL();
2551
2552 // When a line breaks at whitespace consume it before continuing
2553 line_start = line_end;
2554 char next = *line_start;
2555 if (next == '\n')
2556 ++line_start;
2557 else
2558 while (next == ' ' || next == '\t')
2559 next = *(++line_start);
2560 }
2561 strm.IndentLess(prefix_width);
2562}
2563
2564void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2565 const char *word_text,
2566 const char *separator,
2567 const char *help_text,
2568 size_t max_word_len) {
2569 StreamString prefix_stream;
2570 prefix_stream.Printf(" %-*s %s ", (int)max_word_len, word_text, separator);
2571 OutputFormattedHelpText(strm, prefix_stream.GetData(), help_text);
2572}
2573
2574void CommandInterpreter::OutputHelpText(Stream &strm, const char *word_text,
2575 const char *separator,
2576 const char *help_text,
2577 uint32_t max_word_len) {
2578 int indent_size = max_word_len + strlen(separator) + 2;
2579
2580 strm.IndentMore(indent_size);
2581
2582 StreamString text_strm;
2583 text_strm.Printf("%-*s %s %s", max_word_len, word_text, separator, help_text);
2584
2585 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2586
2587 size_t len = text_strm.GetSize();
2588 const char *text = text_strm.GetData();
2589
2590 uint32_t chars_left = max_columns;
2591
2592 for (uint32_t i = 0; i < len; i++) {
2593 if ((text[i] == ' ' && ::strchr((text + i + 1), ' ') &&
Zachary Turner5a8ad4592016-10-05 17:07:34 +00002594 chars_left < static_cast<uint32_t>(::strchr((text + i + 1), ' ') -
2595 (text + i))) ||
Kate Stoneb9c1b512016-09-06 20:57:50 +00002596 text[i] == '\n') {
2597 chars_left = max_columns - indent_size;
2598 strm.EOL();
2599 strm.Indent();
2600 } else {
2601 strm.PutChar(text[i]);
2602 chars_left--;
2603 }
2604 }
2605
2606 strm.EOL();
2607 strm.IndentLess(indent_size);
2608}
2609
2610void CommandInterpreter::FindCommandsForApropos(
2611 const char *search_word, StringList &commands_found,
2612 StringList &commands_help, CommandObject::CommandMap &command_map) {
2613 CommandObject::CommandMap::const_iterator pos;
2614
2615 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
2616 const char *command_name = pos->first.c_str();
2617 CommandObject *cmd_obj = pos->second.get();
2618
2619 const bool search_short_help = true;
2620 const bool search_long_help = false;
2621 const bool search_syntax = false;
2622 const bool search_options = false;
2623 if (strcasestr(command_name, search_word) ||
2624 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2625 search_long_help, search_syntax,
2626 search_options)) {
2627 commands_found.AppendString(cmd_obj->GetCommandName());
2628 commands_help.AppendString(cmd_obj->GetHelp());
2629 }
2630
2631 if (cmd_obj->IsMultiwordObject()) {
2632 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2633 FindCommandsForApropos(search_word, commands_found, commands_help,
2634 cmd_multiword->GetSubcommandDictionary());
2635 }
2636 }
2637}
2638
2639void CommandInterpreter::FindCommandsForApropos(const char *search_word,
2640 StringList &commands_found,
2641 StringList &commands_help,
2642 bool search_builtin_commands,
2643 bool search_user_commands,
2644 bool search_alias_commands) {
2645 CommandObject::CommandMap::const_iterator pos;
2646
2647 if (search_builtin_commands)
2648 FindCommandsForApropos(search_word, commands_found, commands_help,
2649 m_command_dict);
2650
2651 if (search_user_commands)
2652 FindCommandsForApropos(search_word, commands_found, commands_help,
2653 m_user_dict);
2654
2655 if (search_alias_commands)
2656 FindCommandsForApropos(search_word, commands_found, commands_help,
2657 m_alias_dict);
2658}
2659
2660void CommandInterpreter::UpdateExecutionContext(
2661 ExecutionContext *override_context) {
2662 if (override_context != nullptr) {
2663 m_exe_ctx_ref = *override_context;
2664 } else {
2665 const bool adopt_selected = true;
2666 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2667 adopt_selected);
2668 }
2669}
2670
2671size_t CommandInterpreter::GetProcessOutput() {
2672 // The process has stuff waiting for stderr; get it and write it out to the
2673 // appropriate place.
2674 char stdio_buffer[1024];
2675 size_t len;
2676 size_t total_bytes = 0;
2677 Error error;
2678 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2679 if (target_sp) {
2680 ProcessSP process_sp(target_sp->GetProcessSP());
2681 if (process_sp) {
2682 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2683 error)) > 0) {
2684 size_t bytes_written = len;
2685 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2686 total_bytes += len;
2687 }
2688 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2689 error)) > 0) {
2690 size_t bytes_written = len;
2691 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2692 total_bytes += len;
2693 }
2694 }
2695 }
2696 return total_bytes;
2697}
2698
2699void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2700 std::string &line) {
2701 const bool is_interactive = io_handler.GetIsInteractive();
2702 if (is_interactive == false) {
2703 // When we are not interactive, don't execute blank lines. This will happen
2704 // sourcing a commands file. We don't want blank lines to repeat the
2705 // previous
2706 // command and cause any errors to occur (like redefining an alias, get an
2707 // error
2708 // and stop parsing the commands file).
2709 if (line.empty())
2710 return;
2711
2712 // When using a non-interactive file handle (like when sourcing commands
2713 // from a file)
2714 // we need to echo the command out so we don't just see the command output
2715 // and no
2716 // command...
2717 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2718 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2719 line.c_str());
2720 }
2721
2722 lldb_private::CommandReturnObject result;
2723 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2724
2725 // Now emit the command output text from the command we just executed
2726 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2727 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2728 GetProcessOutput();
2729
2730 if (!result.GetImmediateOutputStream()) {
2731 const char *output = result.GetOutputData();
2732 if (output && output[0])
2733 io_handler.GetOutputStreamFile()->PutCString(output);
2734 }
2735
2736 // Now emit the command error text from the command we just executed
2737 if (!result.GetImmediateErrorStream()) {
2738 const char *error = result.GetErrorData();
2739 if (error && error[0])
2740 io_handler.GetErrorStreamFile()->PutCString(error);
2741 }
2742 }
2743
2744 switch (result.GetStatus()) {
2745 case eReturnStatusInvalid:
2746 case eReturnStatusSuccessFinishNoResult:
2747 case eReturnStatusSuccessFinishResult:
2748 case eReturnStatusStarted:
2749 break;
2750
2751 case eReturnStatusSuccessContinuingNoResult:
2752 case eReturnStatusSuccessContinuingResult:
2753 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2754 io_handler.SetIsDone(true);
2755 break;
2756
2757 case eReturnStatusFailed:
2758 m_num_errors++;
2759 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2760 io_handler.SetIsDone(true);
2761 break;
2762
2763 case eReturnStatusQuit:
2764 m_quit_requested = true;
2765 io_handler.SetIsDone(true);
2766 break;
2767 }
2768
2769 // Finally, if we're going to stop on crash, check that here:
2770 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2771 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2772 bool should_stop = false;
2773 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2774 if (target_sp) {
2775 ProcessSP process_sp(target_sp->GetProcessSP());
2776 if (process_sp) {
2777 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2778 StopReason reason = thread_sp->GetStopReason();
2779 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2780 reason == eStopReasonInstrumentation) &&
2781 !result.GetAbnormalStopWasExpected()) {
2782 should_stop = true;
2783 break;
2784 }
2785 }
2786 }
2787 }
2788 if (should_stop) {
2789 io_handler.SetIsDone(true);
2790 m_stopped_for_crash = true;
2791 }
2792 }
2793}
2794
2795bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2796 ExecutionContext exe_ctx(GetExecutionContext());
2797 Process *process = exe_ctx.GetProcessPtr();
2798
2799 if (process) {
2800 StateType state = process->GetState();
2801 if (StateIsRunningState(state)) {
2802 process->Halt();
2803 return true; // Don't do any updating when we are running
2804 }
2805 }
2806
2807 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2808 if (script_interpreter) {
2809 if (script_interpreter->Interrupt())
2810 return true;
2811 }
2812 return false;
2813}
2814
2815void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2816 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2817 void *baton) {
2818 Debugger &debugger = GetDebugger();
2819 IOHandlerSP io_handler_sp(
2820 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2821 "lldb", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002822 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2823 llvm::StringRef(), // Continuation prompt
2824 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002825 debugger.GetUseColor(),
2826 0, // Don't show line numbers
2827 delegate)); // IOHandlerDelegate
2828
2829 if (io_handler_sp) {
2830 io_handler_sp->SetUserData(baton);
2831 if (asynchronously)
2832 debugger.PushIOHandler(io_handler_sp);
2833 else
2834 debugger.RunIOHandler(io_handler_sp);
2835 }
2836}
2837
2838void CommandInterpreter::GetPythonCommandsFromIOHandler(
2839 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2840 void *baton) {
2841 Debugger &debugger = GetDebugger();
2842 IOHandlerSP io_handler_sp(
2843 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2844 "lldb-python", // Name of input reader for history
Zachary Turner514d8cd2016-09-23 18:06:53 +00002845 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2846 llvm::StringRef(), // Continuation prompt
2847 true, // Get multiple lines
Kate Stoneb9c1b512016-09-06 20:57:50 +00002848 debugger.GetUseColor(),
2849 0, // Don't show line numbers
2850 delegate)); // IOHandlerDelegate
2851
2852 if (io_handler_sp) {
2853 io_handler_sp->SetUserData(baton);
2854 if (asynchronously)
2855 debugger.PushIOHandler(io_handler_sp);
2856 else
2857 debugger.RunIOHandler(io_handler_sp);
2858 }
2859}
2860
2861bool CommandInterpreter::IsActive() {
2862 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2863}
2864
2865lldb::IOHandlerSP
2866CommandInterpreter::GetIOHandler(bool force_create,
2867 CommandInterpreterRunOptions *options) {
2868 // Always re-create the IOHandlerEditline in case the input
2869 // changed. The old instance might have had a non-interactive
2870 // input and now it does or vice versa.
2871 if (force_create || !m_command_io_handler_sp) {
2872 // Always re-create the IOHandlerEditline in case the input
2873 // changed. The old instance might have had a non-interactive
2874 // input and now it does or vice versa.
2875 uint32_t flags = 0;
2876
2877 if (options) {
2878 if (options->m_stop_on_continue == eLazyBoolYes)
2879 flags |= eHandleCommandFlagStopOnContinue;
2880 if (options->m_stop_on_error == eLazyBoolYes)
2881 flags |= eHandleCommandFlagStopOnError;
2882 if (options->m_stop_on_crash == eLazyBoolYes)
2883 flags |= eHandleCommandFlagStopOnCrash;
2884 if (options->m_echo_commands != eLazyBoolNo)
2885 flags |= eHandleCommandFlagEchoCommand;
2886 if (options->m_print_results != eLazyBoolNo)
2887 flags |= eHandleCommandFlagPrintResult;
2888 } else {
2889 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2890 }
2891
2892 m_command_io_handler_sp.reset(new IOHandlerEditline(
2893 m_debugger, IOHandler::Type::CommandInterpreter,
2894 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2895 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
Zachary Turner514d8cd2016-09-23 18:06:53 +00002896 llvm::StringRef(), // Continuation prompt
Kate Stoneb9c1b512016-09-06 20:57:50 +00002897 false, // Don't enable multiple line input, just single line commands
2898 m_debugger.GetUseColor(),
2899 0, // Don't show line numbers
2900 *this));
2901 }
2902 return m_command_io_handler_sp;
2903}
2904
2905void CommandInterpreter::RunCommandInterpreter(
2906 bool auto_handle_events, bool spawn_thread,
2907 CommandInterpreterRunOptions &options) {
2908 // Always re-create the command interpreter when we run it in case
2909 // any file handles have changed.
2910 bool force_create = true;
2911 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2912 m_stopped_for_crash = false;
2913
2914 if (auto_handle_events)
2915 m_debugger.StartEventHandlerThread();
2916
2917 if (spawn_thread) {
2918 m_debugger.StartIOHandlerThread();
2919 } else {
2920 m_debugger.ExecuteIOHandlers();
2921
2922 if (auto_handle_events)
2923 m_debugger.StopEventHandlerThread();
2924 }
2925}
2926
2927CommandObject *
2928CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2929 CommandReturnObject &result) {
2930 std::string scratch_command(command_line); // working copy so we don't modify
2931 // command_line unless we succeed
2932 CommandObject *cmd_obj = nullptr;
2933 StreamString revised_command_line;
2934 bool wants_raw_input = false;
2935 size_t actual_cmd_name_len = 0;
2936 std::string next_word;
2937 StringList matches;
2938 bool done = false;
2939 while (!done) {
2940 char quote_char = '\0';
2941 std::string suffix;
2942 ExtractCommand(scratch_command, next_word, suffix, quote_char);
2943 if (cmd_obj == nullptr) {
2944 std::string full_name;
2945 bool is_alias = GetAliasFullName(next_word.c_str(), full_name);
Zachary Turnera4496982016-10-05 21:14:38 +00002946 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002947 bool is_real_command =
2948 (is_alias == false) ||
2949 (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
2950 if (!is_real_command) {
2951 matches.Clear();
2952 std::string alias_result;
2953 cmd_obj = BuildAliasResult(full_name.c_str(), scratch_command,
2954 alias_result, result);
2955 revised_command_line.Printf("%s", alias_result.c_str());
2956 if (cmd_obj) {
2957 wants_raw_input = cmd_obj->WantsRawCommandString();
Zachary Turnera4496982016-10-05 21:14:38 +00002958 actual_cmd_name_len = cmd_obj->GetCommandName().size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002959 }
2960 } else {
2961 if (!cmd_obj)
Zachary Turnera4496982016-10-05 21:14:38 +00002962 cmd_obj = GetCommandObject(next_word, &matches);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002963 if (cmd_obj) {
Zachary Turnera4496982016-10-05 21:14:38 +00002964 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
2965 actual_cmd_name_len += cmd_name.size();
2966 revised_command_line.Printf("%s", cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002967 wants_raw_input = cmd_obj->WantsRawCommandString();
2968 } else {
2969 revised_command_line.Printf("%s", next_word.c_str());
2970 }
2971 }
2972 } else {
2973 if (cmd_obj->IsMultiwordObject()) {
2974 CommandObject *sub_cmd_obj =
2975 cmd_obj->GetSubcommandObject(next_word.c_str());
2976 if (sub_cmd_obj) {
2977 // The subcommand's name includes the parent command's name,
2978 // so restart rather than append to the revised_command_line.
Zachary Turnera4496982016-10-05 21:14:38 +00002979 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
2980 actual_cmd_name_len = sub_cmd_name.size() + 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002981 revised_command_line.Clear();
Zachary Turnera4496982016-10-05 21:14:38 +00002982 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002983 cmd_obj = sub_cmd_obj;
2984 wants_raw_input = cmd_obj->WantsRawCommandString();
2985 } else {
2986 if (quote_char)
2987 revised_command_line.Printf(" %c%s%s%c", quote_char,
2988 next_word.c_str(), suffix.c_str(),
2989 quote_char);
2990 else
2991 revised_command_line.Printf(" %s%s", next_word.c_str(),
2992 suffix.c_str());
2993 done = true;
2994 }
2995 } else {
2996 if (quote_char)
2997 revised_command_line.Printf(" %c%s%s%c", quote_char,
2998 next_word.c_str(), suffix.c_str(),
2999 quote_char);
3000 else
3001 revised_command_line.Printf(" %s%s", next_word.c_str(),
3002 suffix.c_str());
3003 done = true;
3004 }
3005 }
3006
3007 if (cmd_obj == nullptr) {
3008 const size_t num_matches = matches.GetSize();
3009 if (matches.GetSize() > 1) {
3010 StreamString error_msg;
3011 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3012 next_word.c_str());
3013
3014 for (uint32_t i = 0; i < num_matches; ++i) {
3015 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3016 }
3017 result.AppendRawError(error_msg.GetString().c_str());
3018 } else {
3019 // We didn't have only one match, otherwise we wouldn't get here.
3020 assert(num_matches == 0);
3021 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3022 next_word.c_str());
3023 }
3024 result.SetStatus(eReturnStatusFailed);
3025 return nullptr;
3026 }
3027
3028 if (cmd_obj->IsMultiwordObject()) {
3029 if (!suffix.empty()) {
3030 result.AppendErrorWithFormat(
3031 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3032 "might be invalid).\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003033 cmd_obj->GetCommandName().str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003034 next_word.empty() ? "" : next_word.c_str(),
3035 next_word.empty() ? " -- " : " ", suffix.c_str());
3036 result.SetStatus(eReturnStatusFailed);
3037 return nullptr;
3038 }
3039 } else {
3040 // If we found a normal command, we are done
3041 done = true;
3042 if (!suffix.empty()) {
3043 switch (suffix[0]) {
3044 case '/':
3045 // GDB format suffixes
3046 {
3047 Options *command_options = cmd_obj->GetOptions();
3048 if (command_options &&
3049 command_options->SupportsLongOption("gdb-format")) {
3050 std::string gdb_format_option("--gdb-format=");
3051 gdb_format_option += (suffix.c_str() + 1);
3052
3053 bool inserted = false;
3054 std::string &cmd = revised_command_line.GetString();
3055 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3056 if (arg_terminator_idx != std::string::npos) {
3057 // Insert the gdb format option before the "--" that terminates
3058 // options
3059 gdb_format_option.append(1, ' ');
3060 cmd.insert(arg_terminator_idx, gdb_format_option);
3061 inserted = true;
3062 }
3063
3064 if (!inserted)
3065 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3066
3067 if (wants_raw_input &&
3068 FindArgumentTerminator(cmd) == std::string::npos)
3069 revised_command_line.PutCString(" --");
3070 } else {
3071 result.AppendErrorWithFormat(
3072 "the '%s' command doesn't support the --gdb-format option\n",
Zachary Turnera4496982016-10-05 21:14:38 +00003073 cmd_obj->GetCommandName().str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003074 result.SetStatus(eReturnStatusFailed);
3075 return nullptr;
3076 }
3077 }
3078 break;
3079
3080 default:
3081 result.AppendErrorWithFormat(
3082 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3083 result.SetStatus(eReturnStatusFailed);
3084 return nullptr;
3085 }
3086 }
3087 }
3088 if (scratch_command.empty())
3089 done = true;
3090 }
3091
3092 if (!scratch_command.empty())
3093 revised_command_line.Printf(" %s", scratch_command.c_str());
3094
3095 if (cmd_obj != NULL)
3096 command_line = revised_command_line.GetData();
3097
3098 return cmd_obj;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003099}