File: | tools/lldb/source/Interpreter/CommandInterpreter.cpp |
Warning: | line 1789, column 9 Value stored to 'num_command_matches' is never read |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===-- 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 | |
10 | #include <stdlib.h> |
11 | #include <string> |
12 | #include <vector> |
13 | |
14 | #include "CommandObjectScript.h" |
15 | #include "lldb/Interpreter/CommandObjectRegexCommand.h" |
16 | |
17 | #include "Commands/CommandObjectApropos.h" |
18 | #include "Commands/CommandObjectBreakpoint.h" |
19 | #include "Commands/CommandObjectBugreport.h" |
20 | #include "Commands/CommandObjectCommands.h" |
21 | #include "Commands/CommandObjectDisassemble.h" |
22 | #include "Commands/CommandObjectExpression.h" |
23 | #include "Commands/CommandObjectFrame.h" |
24 | #include "Commands/CommandObjectGUI.h" |
25 | #include "Commands/CommandObjectHelp.h" |
26 | #include "Commands/CommandObjectLanguage.h" |
27 | #include "Commands/CommandObjectLog.h" |
28 | #include "Commands/CommandObjectMemory.h" |
29 | #include "Commands/CommandObjectPlatform.h" |
30 | #include "Commands/CommandObjectPlugin.h" |
31 | #include "Commands/CommandObjectProcess.h" |
32 | #include "Commands/CommandObjectQuit.h" |
33 | #include "Commands/CommandObjectRegister.h" |
34 | #include "Commands/CommandObjectSettings.h" |
35 | #include "Commands/CommandObjectSource.h" |
36 | #include "Commands/CommandObjectStats.h" |
37 | #include "Commands/CommandObjectTarget.h" |
38 | #include "Commands/CommandObjectThread.h" |
39 | #include "Commands/CommandObjectType.h" |
40 | #include "Commands/CommandObjectVersion.h" |
41 | #include "Commands/CommandObjectWatchpoint.h" |
42 | |
43 | #include "lldb/Core/Debugger.h" |
44 | #include "lldb/Core/PluginManager.h" |
45 | #include "lldb/Core/StreamFile.h" |
46 | #include "lldb/Utility/Log.h" |
47 | #include "lldb/Utility/State.h" |
48 | #include "lldb/Utility/Stream.h" |
49 | #include "lldb/Utility/Timer.h" |
50 | |
51 | #ifndef LLDB_DISABLE_LIBEDIT |
52 | #include "lldb/Host/Editline.h" |
53 | #endif |
54 | #include "lldb/Host/Host.h" |
55 | #include "lldb/Host/HostInfo.h" |
56 | |
57 | #include "lldb/Interpreter/CommandCompletions.h" |
58 | #include "lldb/Interpreter/CommandInterpreter.h" |
59 | #include "lldb/Interpreter/CommandReturnObject.h" |
60 | #include "lldb/Interpreter/OptionValueProperties.h" |
61 | #include "lldb/Interpreter/Options.h" |
62 | #include "lldb/Interpreter/Property.h" |
63 | #include "lldb/Utility/Args.h" |
64 | |
65 | #include "lldb/Target/Process.h" |
66 | #include "lldb/Target/TargetList.h" |
67 | #include "lldb/Target/Thread.h" |
68 | |
69 | #include "llvm/ADT/STLExtras.h" |
70 | #include "llvm/ADT/SmallString.h" |
71 | #include "llvm/Support/Path.h" |
72 | #include "llvm/Support/PrettyStackTrace.h" |
73 | |
74 | using namespace lldb; |
75 | using namespace lldb_private; |
76 | |
77 | static const char *k_white_space = " \t\v"; |
78 | |
79 | static constexpr bool NoGlobalSetting = true; |
80 | static constexpr uintptr_t DefaultValueTrue = true; |
81 | static constexpr uintptr_t DefaultValueFalse = false; |
82 | static constexpr const char *NoCStrDefault = nullptr; |
83 | |
84 | static constexpr PropertyDefinition g_properties[] = { |
85 | {"expand-regex-aliases", OptionValue::eTypeBoolean, NoGlobalSetting, |
86 | DefaultValueFalse, NoCStrDefault, {}, |
87 | "If true, regular expression alias commands will show the " |
88 | "expanded command that will be executed. This can be used to " |
89 | "debug new regular expression alias commands."}, |
90 | {"prompt-on-quit", OptionValue::eTypeBoolean, NoGlobalSetting, |
91 | DefaultValueTrue, NoCStrDefault, {}, |
92 | "If true, LLDB will prompt you before quitting if there are any live " |
93 | "processes being debugged. If false, LLDB will quit without asking in any " |
94 | "case."}, |
95 | {"stop-command-source-on-error", OptionValue::eTypeBoolean, NoGlobalSetting, |
96 | DefaultValueTrue, NoCStrDefault, {}, |
97 | "If true, LLDB will stop running a 'command source' " |
98 | "script upon encountering an error."}, |
99 | {"space-repl-prompts", OptionValue::eTypeBoolean, NoGlobalSetting, |
100 | DefaultValueFalse, NoCStrDefault, {}, |
101 | "If true, blank lines will be printed between between REPL submissions."}, |
102 | {"echo-commands", OptionValue::eTypeBoolean, NoGlobalSetting, |
103 | DefaultValueTrue, NoCStrDefault, {}, |
104 | "If true, commands will be echoed before they are evaluated."}, |
105 | {"echo-comment-commands", OptionValue::eTypeBoolean, NoGlobalSetting, |
106 | DefaultValueTrue, NoCStrDefault, {}, |
107 | "If true, commands will be echoed even if they are pure comment lines."}}; |
108 | |
109 | enum { |
110 | ePropertyExpandRegexAliases = 0, |
111 | ePropertyPromptOnQuit = 1, |
112 | ePropertyStopCmdSourceOnError = 2, |
113 | eSpaceReplPrompts = 3, |
114 | eEchoCommands = 4, |
115 | eEchoCommentCommands = 5 |
116 | }; |
117 | |
118 | ConstString &CommandInterpreter::GetStaticBroadcasterClass() { |
119 | static ConstString class_name("lldb.commandInterpreter"); |
120 | return class_name; |
121 | } |
122 | |
123 | CommandInterpreter::CommandInterpreter(Debugger &debugger, |
124 | ScriptLanguage script_language, |
125 | bool synchronous_execution) |
126 | : Broadcaster(debugger.GetBroadcasterManager(), |
127 | CommandInterpreter::GetStaticBroadcasterClass().AsCString()), |
128 | Properties(OptionValuePropertiesSP( |
129 | new OptionValueProperties(ConstString("interpreter")))), |
130 | IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand), |
131 | m_debugger(debugger), m_synchronous_execution(synchronous_execution), |
132 | m_skip_lldbinit_files(false), m_skip_app_init_files(false), |
133 | m_script_interpreter_sp(), m_command_io_handler_sp(), m_comment_char('#'), |
134 | m_batch_command_mode(false), m_truncation_warning(eNoTruncation), |
135 | m_command_source_depth(0), m_num_errors(0), m_quit_requested(false), |
136 | m_stopped_for_crash(false) { |
137 | debugger.SetScriptLanguage(script_language); |
138 | SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit"); |
139 | SetEventName(eBroadcastBitResetPrompt, "reset-prompt"); |
140 | SetEventName(eBroadcastBitQuitCommandReceived, "quit"); |
141 | CheckInWithManager(); |
142 | m_collection_sp->Initialize(g_properties); |
143 | } |
144 | |
145 | bool CommandInterpreter::GetExpandRegexAliases() const { |
146 | const uint32_t idx = ePropertyExpandRegexAliases; |
147 | return m_collection_sp->GetPropertyAtIndexAsBoolean( |
148 | nullptr, idx, g_properties[idx].default_uint_value != 0); |
149 | } |
150 | |
151 | bool CommandInterpreter::GetPromptOnQuit() const { |
152 | const uint32_t idx = ePropertyPromptOnQuit; |
153 | return m_collection_sp->GetPropertyAtIndexAsBoolean( |
154 | nullptr, idx, g_properties[idx].default_uint_value != 0); |
155 | } |
156 | |
157 | void CommandInterpreter::SetPromptOnQuit(bool b) { |
158 | const uint32_t idx = ePropertyPromptOnQuit; |
159 | m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); |
160 | } |
161 | |
162 | bool CommandInterpreter::GetEchoCommands() const { |
163 | const uint32_t idx = eEchoCommands; |
164 | return m_collection_sp->GetPropertyAtIndexAsBoolean( |
165 | nullptr, idx, g_properties[idx].default_uint_value != 0); |
166 | } |
167 | |
168 | void CommandInterpreter::SetEchoCommands(bool b) { |
169 | const uint32_t idx = eEchoCommands; |
170 | m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); |
171 | } |
172 | |
173 | bool CommandInterpreter::GetEchoCommentCommands() const { |
174 | const uint32_t idx = eEchoCommentCommands; |
175 | return m_collection_sp->GetPropertyAtIndexAsBoolean( |
176 | nullptr, idx, g_properties[idx].default_uint_value != 0); |
177 | } |
178 | |
179 | void CommandInterpreter::SetEchoCommentCommands(bool b) { |
180 | const uint32_t idx = eEchoCommentCommands; |
181 | m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); |
182 | } |
183 | |
184 | void CommandInterpreter::AllowExitCodeOnQuit(bool allow) { |
185 | m_allow_exit_code = allow; |
186 | if (!allow) |
187 | m_quit_exit_code.reset(); |
188 | } |
189 | |
190 | bool CommandInterpreter::SetQuitExitCode(int exit_code) { |
191 | if (!m_allow_exit_code) |
192 | return false; |
193 | m_quit_exit_code = exit_code; |
194 | return true; |
195 | } |
196 | |
197 | int CommandInterpreter::GetQuitExitCode(bool &exited) const { |
198 | exited = m_quit_exit_code.hasValue(); |
199 | if (exited) |
200 | return *m_quit_exit_code; |
201 | return 0; |
202 | } |
203 | |
204 | void CommandInterpreter::ResolveCommand(const char *command_line, |
205 | CommandReturnObject &result) { |
206 | std::string command = command_line; |
207 | if (ResolveCommandImpl(command, result) != nullptr) { |
208 | result.AppendMessageWithFormat("%s", command.c_str()); |
209 | result.SetStatus(eReturnStatusSuccessFinishResult); |
210 | } |
211 | } |
212 | |
213 | bool CommandInterpreter::GetStopCmdSourceOnError() const { |
214 | const uint32_t idx = ePropertyStopCmdSourceOnError; |
215 | return m_collection_sp->GetPropertyAtIndexAsBoolean( |
216 | nullptr, idx, g_properties[idx].default_uint_value != 0); |
217 | } |
218 | |
219 | bool CommandInterpreter::GetSpaceReplPrompts() const { |
220 | const uint32_t idx = eSpaceReplPrompts; |
221 | return m_collection_sp->GetPropertyAtIndexAsBoolean( |
222 | nullptr, idx, g_properties[idx].default_uint_value != 0); |
223 | } |
224 | |
225 | void CommandInterpreter::Initialize() { |
226 | static Timer::Category func_cat(LLVM_PRETTY_FUNCTION__PRETTY_FUNCTION__); |
227 | Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION__PRETTY_FUNCTION__); |
228 | |
229 | CommandReturnObject result; |
230 | |
231 | LoadCommandDictionary(); |
232 | |
233 | // An alias arguments vector to reuse - reset it before use... |
234 | OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector); |
235 | |
236 | // Set up some initial aliases. |
237 | CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false); |
238 | if (cmd_obj_sp) { |
239 | AddAlias("q", cmd_obj_sp); |
240 | AddAlias("exit", cmd_obj_sp); |
241 | } |
242 | |
243 | cmd_obj_sp = GetCommandSPExact("_regexp-attach", false); |
244 | if (cmd_obj_sp) |
245 | AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax()); |
246 | |
247 | cmd_obj_sp = GetCommandSPExact("process detach", false); |
248 | if (cmd_obj_sp) { |
249 | AddAlias("detach", cmd_obj_sp); |
250 | } |
251 | |
252 | cmd_obj_sp = GetCommandSPExact("process continue", false); |
253 | if (cmd_obj_sp) { |
254 | AddAlias("c", cmd_obj_sp); |
255 | AddAlias("continue", cmd_obj_sp); |
256 | } |
257 | |
258 | cmd_obj_sp = GetCommandSPExact("_regexp-break", false); |
259 | if (cmd_obj_sp) |
260 | AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax()); |
261 | |
262 | cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false); |
263 | if (cmd_obj_sp) |
264 | AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax()); |
265 | |
266 | cmd_obj_sp = GetCommandSPExact("thread step-inst", false); |
267 | if (cmd_obj_sp) { |
268 | AddAlias("stepi", cmd_obj_sp); |
269 | AddAlias("si", cmd_obj_sp); |
270 | } |
271 | |
272 | cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false); |
273 | if (cmd_obj_sp) { |
274 | AddAlias("nexti", cmd_obj_sp); |
275 | AddAlias("ni", cmd_obj_sp); |
276 | } |
277 | |
278 | cmd_obj_sp = GetCommandSPExact("thread step-in", false); |
279 | if (cmd_obj_sp) { |
280 | AddAlias("s", cmd_obj_sp); |
281 | AddAlias("step", cmd_obj_sp); |
282 | CommandAlias *sif_alias = AddAlias( |
283 | "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1"); |
284 | if (sif_alias) { |
285 | sif_alias->SetHelp("Step through the current block, stopping if you step " |
286 | "directly into a function whose name matches the " |
287 | "TargetFunctionName."); |
288 | sif_alias->SetSyntax("sif <TargetFunctionName>"); |
289 | } |
290 | } |
291 | |
292 | cmd_obj_sp = GetCommandSPExact("thread step-over", false); |
293 | if (cmd_obj_sp) { |
294 | AddAlias("n", cmd_obj_sp); |
295 | AddAlias("next", cmd_obj_sp); |
296 | } |
297 | |
298 | cmd_obj_sp = GetCommandSPExact("thread step-out", false); |
299 | if (cmd_obj_sp) { |
300 | AddAlias("finish", cmd_obj_sp); |
301 | } |
302 | |
303 | cmd_obj_sp = GetCommandSPExact("frame select", false); |
304 | if (cmd_obj_sp) { |
305 | AddAlias("f", cmd_obj_sp); |
306 | } |
307 | |
308 | cmd_obj_sp = GetCommandSPExact("thread select", false); |
309 | if (cmd_obj_sp) { |
310 | AddAlias("t", cmd_obj_sp); |
311 | } |
312 | |
313 | cmd_obj_sp = GetCommandSPExact("_regexp-jump", false); |
314 | if (cmd_obj_sp) { |
315 | AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax()); |
316 | AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax()); |
317 | } |
318 | |
319 | cmd_obj_sp = GetCommandSPExact("_regexp-list", false); |
320 | if (cmd_obj_sp) { |
321 | AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax()); |
322 | AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax()); |
323 | } |
324 | |
325 | cmd_obj_sp = GetCommandSPExact("_regexp-env", false); |
326 | if (cmd_obj_sp) |
327 | AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax()); |
328 | |
329 | cmd_obj_sp = GetCommandSPExact("memory read", false); |
330 | if (cmd_obj_sp) |
331 | AddAlias("x", cmd_obj_sp); |
332 | |
333 | cmd_obj_sp = GetCommandSPExact("_regexp-up", false); |
334 | if (cmd_obj_sp) |
335 | AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax()); |
336 | |
337 | cmd_obj_sp = GetCommandSPExact("_regexp-down", false); |
338 | if (cmd_obj_sp) |
339 | AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax()); |
340 | |
341 | cmd_obj_sp = GetCommandSPExact("_regexp-display", false); |
342 | if (cmd_obj_sp) |
343 | AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax()); |
344 | |
345 | cmd_obj_sp = GetCommandSPExact("disassemble", false); |
346 | if (cmd_obj_sp) |
347 | AddAlias("dis", cmd_obj_sp); |
348 | |
349 | cmd_obj_sp = GetCommandSPExact("disassemble", false); |
350 | if (cmd_obj_sp) |
351 | AddAlias("di", cmd_obj_sp); |
352 | |
353 | cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false); |
354 | if (cmd_obj_sp) |
355 | AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax()); |
356 | |
357 | cmd_obj_sp = GetCommandSPExact("_regexp-bt", false); |
358 | if (cmd_obj_sp) |
359 | AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax()); |
360 | |
361 | cmd_obj_sp = GetCommandSPExact("target create", false); |
362 | if (cmd_obj_sp) |
363 | AddAlias("file", cmd_obj_sp); |
364 | |
365 | cmd_obj_sp = GetCommandSPExact("target modules", false); |
366 | if (cmd_obj_sp) |
367 | AddAlias("image", cmd_obj_sp); |
368 | |
369 | alias_arguments_vector_sp.reset(new OptionArgVector); |
370 | |
371 | cmd_obj_sp = GetCommandSPExact("expression", false); |
372 | if (cmd_obj_sp) { |
373 | AddAlias("p", cmd_obj_sp, "--")->SetHelpLong(""); |
374 | AddAlias("print", cmd_obj_sp, "--")->SetHelpLong(""); |
375 | AddAlias("call", cmd_obj_sp, "--")->SetHelpLong(""); |
376 | if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) { |
377 | po->SetHelp("Evaluate an expression on the current thread. Displays any " |
378 | "returned value with formatting " |
379 | "controlled by the type's author."); |
380 | po->SetHelpLong(""); |
381 | } |
382 | AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong(""); |
383 | AddAlias("poarray", cmd_obj_sp, |
384 | "--object-description --element-count %1 --") |
385 | ->SetHelpLong(""); |
386 | } |
387 | |
388 | cmd_obj_sp = GetCommandSPExact("process kill", false); |
389 | if (cmd_obj_sp) { |
390 | AddAlias("kill", cmd_obj_sp); |
391 | } |
392 | |
393 | cmd_obj_sp = GetCommandSPExact("process launch", false); |
394 | if (cmd_obj_sp) { |
395 | alias_arguments_vector_sp.reset(new OptionArgVector); |
396 | #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) |
397 | AddAlias("r", cmd_obj_sp, "--"); |
398 | AddAlias("run", cmd_obj_sp, "--"); |
399 | #else |
400 | #if defined(__APPLE__) |
401 | std::string shell_option; |
402 | shell_option.append("--shell-expand-args"); |
403 | shell_option.append(" true"); |
404 | shell_option.append(" --"); |
405 | AddAlias("r", cmd_obj_sp, "--shell-expand-args true --"); |
406 | AddAlias("run", cmd_obj_sp, "--shell-expand-args true --"); |
407 | #else |
408 | StreamString defaultshell; |
409 | defaultshell.Printf("--shell=%s --", |
410 | HostInfo::GetDefaultShell().GetPath().c_str()); |
411 | AddAlias("r", cmd_obj_sp, defaultshell.GetString()); |
412 | AddAlias("run", cmd_obj_sp, defaultshell.GetString()); |
413 | #endif |
414 | #endif |
415 | } |
416 | |
417 | cmd_obj_sp = GetCommandSPExact("target symbols add", false); |
418 | if (cmd_obj_sp) { |
419 | AddAlias("add-dsym", cmd_obj_sp); |
420 | } |
421 | |
422 | cmd_obj_sp = GetCommandSPExact("breakpoint set", false); |
423 | if (cmd_obj_sp) { |
424 | AddAlias("rbreak", cmd_obj_sp, "--func-regex %1"); |
425 | } |
426 | |
427 | cmd_obj_sp = GetCommandSPExact("frame variable", false); |
428 | if (cmd_obj_sp) { |
429 | AddAlias("v", cmd_obj_sp); |
430 | AddAlias("var", cmd_obj_sp); |
431 | AddAlias("vo", cmd_obj_sp, "--object-description"); |
432 | } |
433 | |
434 | } |
435 | |
436 | void CommandInterpreter::Clear() { |
437 | m_command_io_handler_sp.reset(); |
438 | |
439 | if (m_script_interpreter_sp) |
440 | m_script_interpreter_sp->Clear(); |
441 | } |
442 | |
443 | const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) { |
444 | // This function has not yet been implemented. |
445 | |
446 | // Look for any embedded script command |
447 | // If found, |
448 | // get interpreter object from the command dictionary, |
449 | // call execute_one_command on it, |
450 | // get the results as a string, |
451 | // substitute that string for current stuff. |
452 | |
453 | return arg; |
454 | } |
455 | |
456 | void CommandInterpreter::LoadCommandDictionary() { |
457 | static Timer::Category func_cat(LLVM_PRETTY_FUNCTION__PRETTY_FUNCTION__); |
458 | Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION__PRETTY_FUNCTION__); |
459 | |
460 | lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage(); |
461 | |
462 | m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this)); |
463 | m_command_dict["breakpoint"] = |
464 | CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this)); |
465 | m_command_dict["bugreport"] = |
466 | CommandObjectSP(new CommandObjectMultiwordBugreport(*this)); |
467 | m_command_dict["command"] = |
468 | CommandObjectSP(new CommandObjectMultiwordCommands(*this)); |
469 | m_command_dict["disassemble"] = |
470 | CommandObjectSP(new CommandObjectDisassemble(*this)); |
471 | m_command_dict["expression"] = |
472 | CommandObjectSP(new CommandObjectExpression(*this)); |
473 | m_command_dict["frame"] = |
474 | CommandObjectSP(new CommandObjectMultiwordFrame(*this)); |
475 | m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this)); |
476 | m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this)); |
477 | m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this)); |
478 | m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this)); |
479 | m_command_dict["platform"] = |
480 | CommandObjectSP(new CommandObjectPlatform(*this)); |
481 | m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this)); |
482 | m_command_dict["process"] = |
483 | CommandObjectSP(new CommandObjectMultiwordProcess(*this)); |
484 | m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this)); |
485 | m_command_dict["register"] = |
486 | CommandObjectSP(new CommandObjectRegister(*this)); |
487 | m_command_dict["script"] = |
488 | CommandObjectSP(new CommandObjectScript(*this, script_language)); |
489 | m_command_dict["settings"] = |
490 | CommandObjectSP(new CommandObjectMultiwordSettings(*this)); |
491 | m_command_dict["source"] = |
492 | CommandObjectSP(new CommandObjectMultiwordSource(*this)); |
493 | m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this)); |
494 | m_command_dict["target"] = |
495 | CommandObjectSP(new CommandObjectMultiwordTarget(*this)); |
496 | m_command_dict["thread"] = |
497 | CommandObjectSP(new CommandObjectMultiwordThread(*this)); |
498 | m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this)); |
499 | m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this)); |
500 | m_command_dict["watchpoint"] = |
501 | CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this)); |
502 | m_command_dict["language"] = |
503 | CommandObjectSP(new CommandObjectLanguage(*this)); |
504 | |
505 | const char *break_regexes[][2] = { |
506 | {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", |
507 | "breakpoint set --file '%1' --line %2"}, |
508 | {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"}, |
509 | {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"}, |
510 | {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"}, |
511 | {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", |
512 | "breakpoint set --name '%1'"}, |
513 | {"^(-.*)$", "breakpoint set %1"}, |
514 | {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", |
515 | "breakpoint set --name '%2' --shlib '%1'"}, |
516 | {"^\\&(.*[^[:space:]])[[:space:]]*$", |
517 | "breakpoint set --name '%1' --skip-prologue=0"}, |
518 | {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$", |
519 | "breakpoint set --name '%1'"}}; |
520 | |
521 | size_t num_regexes = llvm::array_lengthof(break_regexes); |
522 | |
523 | std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap( |
524 | new CommandObjectRegexCommand( |
525 | *this, "_regexp-break", |
526 | "Set a breakpoint using one of several shorthand formats.", |
527 | "\n" |
528 | "_regexp-break <filename>:<linenum>\n" |
529 | " main.c:12 // Break at line 12 of " |
530 | "main.c\n\n" |
531 | "_regexp-break <linenum>\n" |
532 | " 12 // Break at line 12 of current " |
533 | "file\n\n" |
534 | "_regexp-break 0x<address>\n" |
535 | " 0x1234000 // Break at address " |
536 | "0x1234000\n\n" |
537 | "_regexp-break <name>\n" |
538 | " main // Break in 'main' after the " |
539 | "prologue\n\n" |
540 | "_regexp-break &<name>\n" |
541 | " &main // Break at first instruction " |
542 | "in 'main'\n\n" |
543 | "_regexp-break <module>`<name>\n" |
544 | " libc.so`malloc // Break in 'malloc' from " |
545 | "'libc.so'\n\n" |
546 | "_regexp-break /<source-regex>/\n" |
547 | " /break here/ // Break on source lines in " |
548 | "current file\n" |
549 | " // containing text 'break " |
550 | "here'.\n", |
551 | 2, CommandCompletions::eSymbolCompletion | |
552 | CommandCompletions::eSourceFileCompletion, |
553 | false)); |
554 | |
555 | if (break_regex_cmd_ap.get()) { |
556 | bool success = true; |
557 | for (size_t i = 0; i < num_regexes; i++) { |
558 | success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], |
559 | break_regexes[i][1]); |
560 | if (!success) |
561 | break; |
562 | } |
563 | success = |
564 | break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full"); |
565 | |
566 | if (success) { |
567 | CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release()); |
568 | m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp; |
569 | } |
570 | } |
571 | |
572 | std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap( |
573 | new CommandObjectRegexCommand( |
574 | *this, "_regexp-tbreak", |
575 | "Set a one-shot breakpoint using one of several shorthand formats.", |
576 | "\n" |
577 | "_regexp-break <filename>:<linenum>\n" |
578 | " main.c:12 // Break at line 12 of " |
579 | "main.c\n\n" |
580 | "_regexp-break <linenum>\n" |
581 | " 12 // Break at line 12 of current " |
582 | "file\n\n" |
583 | "_regexp-break 0x<address>\n" |
584 | " 0x1234000 // Break at address " |
585 | "0x1234000\n\n" |
586 | "_regexp-break <name>\n" |
587 | " main // Break in 'main' after the " |
588 | "prologue\n\n" |
589 | "_regexp-break &<name>\n" |
590 | " &main // Break at first instruction " |
591 | "in 'main'\n\n" |
592 | "_regexp-break <module>`<name>\n" |
593 | " libc.so`malloc // Break in 'malloc' from " |
594 | "'libc.so'\n\n" |
595 | "_regexp-break /<source-regex>/\n" |
596 | " /break here/ // Break on source lines in " |
597 | "current file\n" |
598 | " // containing text 'break " |
599 | "here'.\n", |
600 | 2, CommandCompletions::eSymbolCompletion | |
601 | CommandCompletions::eSourceFileCompletion, |
602 | false)); |
603 | |
604 | if (tbreak_regex_cmd_ap.get()) { |
605 | bool success = true; |
606 | for (size_t i = 0; i < num_regexes; i++) { |
607 | // If you add a resultant command string longer than 1024 characters be |
608 | // sure to increase the size of this buffer. |
609 | char buffer[1024]; |
610 | int num_printed = |
611 | snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1"); |
612 | lldbassert(num_printed < 1024)lldb_private::lldb_assert(static_cast<bool>(num_printed < 1024), "num_printed < 1024", __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 612); |
613 | UNUSED_IF_ASSERT_DISABLED(num_printed)((void)(num_printed)); |
614 | success = |
615 | tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer); |
616 | if (!success) |
617 | break; |
618 | } |
619 | success = |
620 | tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full"); |
621 | |
622 | if (success) { |
623 | CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release()); |
624 | m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] = |
625 | tbreak_regex_cmd_sp; |
626 | } |
627 | } |
628 | |
629 | std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap( |
630 | new CommandObjectRegexCommand( |
631 | *this, "_regexp-attach", "Attach to process by ID or name.", |
632 | "_regexp-attach <pid> | <process-name>", 2, 0, false)); |
633 | if (attach_regex_cmd_ap.get()) { |
634 | if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", |
635 | "process attach --pid %1") && |
636 | attach_regex_cmd_ap->AddRegexCommand( |
637 | "^(-.*|.* -.*)$", "process attach %1") && // Any options that are |
638 | // specified get passed to |
639 | // 'process attach' |
640 | attach_regex_cmd_ap->AddRegexCommand("^(.+)$", |
641 | "process attach --name '%1'") && |
642 | attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) { |
643 | CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release()); |
644 | m_command_dict[attach_regex_cmd_sp->GetCommandName()] = |
645 | attach_regex_cmd_sp; |
646 | } |
647 | } |
648 | |
649 | std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap( |
650 | new CommandObjectRegexCommand(*this, "_regexp-down", |
651 | "Select a newer stack frame. Defaults to " |
652 | "moving one frame, a numeric argument can " |
653 | "specify an arbitrary number.", |
654 | "_regexp-down [<count>]", 2, 0, false)); |
655 | if (down_regex_cmd_ap.get()) { |
656 | if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") && |
657 | down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", |
658 | "frame select -r -%1")) { |
659 | CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release()); |
660 | m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp; |
661 | } |
662 | } |
663 | |
664 | std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap( |
665 | new CommandObjectRegexCommand( |
666 | *this, "_regexp-up", |
667 | "Select an older stack frame. Defaults to moving one " |
668 | "frame, a numeric argument can specify an arbitrary number.", |
669 | "_regexp-up [<count>]", 2, 0, false)); |
670 | if (up_regex_cmd_ap.get()) { |
671 | if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") && |
672 | up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) { |
673 | CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release()); |
674 | m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp; |
675 | } |
676 | } |
677 | |
678 | std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap( |
679 | new CommandObjectRegexCommand( |
680 | *this, "_regexp-display", |
681 | "Evaluate an expression at every stop (see 'help target stop-hook'.)", |
682 | "_regexp-display expression", 2, 0, false)); |
683 | if (display_regex_cmd_ap.get()) { |
684 | if (display_regex_cmd_ap->AddRegexCommand( |
685 | "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) { |
686 | CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release()); |
687 | m_command_dict[display_regex_cmd_sp->GetCommandName()] = |
688 | display_regex_cmd_sp; |
689 | } |
690 | } |
691 | |
692 | std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap( |
693 | new CommandObjectRegexCommand( |
694 | *this, "_regexp-undisplay", "Stop displaying expression at every " |
695 | "stop (specified by stop-hook index.)", |
696 | "_regexp-undisplay stop-hook-number", 2, 0, false)); |
697 | if (undisplay_regex_cmd_ap.get()) { |
698 | if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", |
699 | "target stop-hook delete %1")) { |
700 | CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release()); |
701 | m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] = |
702 | undisplay_regex_cmd_sp; |
703 | } |
704 | } |
705 | |
706 | std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap( |
707 | new CommandObjectRegexCommand( |
708 | *this, "gdb-remote", "Connect to a process via remote GDB server. " |
709 | "If no host is specifed, localhost is assumed.", |
710 | "gdb-remote [<hostname>:]<portnum>", 2, 0, false)); |
711 | if (connect_gdb_remote_cmd_ap.get()) { |
712 | if (connect_gdb_remote_cmd_ap->AddRegexCommand( |
713 | "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$", |
714 | "process connect --plugin gdb-remote connect://%1:%2") && |
715 | connect_gdb_remote_cmd_ap->AddRegexCommand( |
716 | "^([[:digit:]]+)$", |
717 | "process connect --plugin gdb-remote connect://localhost:%1")) { |
718 | CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release()); |
719 | m_command_dict[command_sp->GetCommandName()] = command_sp; |
720 | } |
721 | } |
722 | |
723 | std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap( |
724 | new CommandObjectRegexCommand( |
725 | *this, "kdp-remote", "Connect to a process via remote KDP server. " |
726 | "If no UDP port is specified, port 41139 is " |
727 | "assumed.", |
728 | "kdp-remote <hostname>[:<portnum>]", 2, 0, false)); |
729 | if (connect_kdp_remote_cmd_ap.get()) { |
730 | if (connect_kdp_remote_cmd_ap->AddRegexCommand( |
731 | "^([^:]+:[[:digit:]]+)$", |
732 | "process connect --plugin kdp-remote udp://%1") && |
733 | connect_kdp_remote_cmd_ap->AddRegexCommand( |
734 | "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) { |
735 | CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release()); |
736 | m_command_dict[command_sp->GetCommandName()] = command_sp; |
737 | } |
738 | } |
739 | |
740 | std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap( |
741 | new CommandObjectRegexCommand( |
742 | *this, "_regexp-bt", |
743 | "Show the current thread's call stack. Any numeric argument " |
744 | "displays at most that many " |
745 | "frames. The argument 'all' displays all threads.", |
746 | "bt [<digit> | all]", 2, 0, false)); |
747 | if (bt_regex_cmd_ap.get()) { |
748 | // accept but don't document "bt -c <number>" -- before bt was a regex |
749 | // command if you wanted to backtrace three frames you would do "bt -c 3" |
750 | // but the intention is to have this emulate the gdb "bt" command and so |
751 | // now "bt 3" is the preferred form, in line with gdb. |
752 | if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", |
753 | "thread backtrace -c %1") && |
754 | bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", |
755 | "thread backtrace -c %1") && |
756 | bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") && |
757 | bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) { |
758 | CommandObjectSP command_sp(bt_regex_cmd_ap.release()); |
759 | m_command_dict[command_sp->GetCommandName()] = command_sp; |
760 | } |
761 | } |
762 | |
763 | std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap( |
764 | new CommandObjectRegexCommand( |
765 | *this, "_regexp-list", |
766 | "List relevant source code using one of several shorthand formats.", |
767 | "\n" |
768 | "_regexp-list <file>:<line> // List around specific file/line\n" |
769 | "_regexp-list <line> // List current file around specified " |
770 | "line\n" |
771 | "_regexp-list <function-name> // List specified function\n" |
772 | "_regexp-list 0x<address> // List around specified address\n" |
773 | "_regexp-list -[<count>] // List previous <count> lines\n" |
774 | "_regexp-list // List subsequent lines", |
775 | 2, CommandCompletions::eSourceFileCompletion, false)); |
776 | if (list_regex_cmd_ap.get()) { |
777 | if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", |
778 | "source list --line %1") && |
779 | list_regex_cmd_ap->AddRegexCommand( |
780 | "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]" |
781 | "]*$", |
782 | "source list --file '%1' --line %2") && |
783 | list_regex_cmd_ap->AddRegexCommand( |
784 | "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", |
785 | "source list --address %1") && |
786 | list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", |
787 | "source list --reverse") && |
788 | list_regex_cmd_ap->AddRegexCommand( |
789 | "^-([[:digit:]]+)[[:space:]]*$", |
790 | "source list --reverse --count %1") && |
791 | list_regex_cmd_ap->AddRegexCommand("^(.+)$", |
792 | "source list --name \"%1\"") && |
793 | list_regex_cmd_ap->AddRegexCommand("^$", "source list")) { |
794 | CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release()); |
795 | m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp; |
796 | } |
797 | } |
798 | |
799 | std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap( |
800 | new CommandObjectRegexCommand( |
801 | *this, "_regexp-env", |
802 | "Shorthand for viewing and setting environment variables.", |
803 | "\n" |
804 | "_regexp-env // Show enrivonment\n" |
805 | "_regexp-env <name>=<value> // Set an environment variable", |
806 | 2, 0, false)); |
807 | if (env_regex_cmd_ap.get()) { |
808 | if (env_regex_cmd_ap->AddRegexCommand("^$", |
809 | "settings show target.env-vars") && |
810 | env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", |
811 | "settings set target.env-vars %1")) { |
812 | CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release()); |
813 | m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp; |
814 | } |
815 | } |
816 | |
817 | std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap( |
818 | new CommandObjectRegexCommand( |
819 | *this, "_regexp-jump", "Set the program counter to a new address.", |
820 | "\n" |
821 | "_regexp-jump <line>\n" |
822 | "_regexp-jump +<line-offset> | -<line-offset>\n" |
823 | "_regexp-jump <file>:<line>\n" |
824 | "_regexp-jump *<addr>\n", |
825 | 2, 0, false)); |
826 | if (jump_regex_cmd_ap.get()) { |
827 | if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", |
828 | "thread jump --addr %1") && |
829 | jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", |
830 | "thread jump --line %1") && |
831 | jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", |
832 | "thread jump --file %1 --line %2") && |
833 | jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", |
834 | "thread jump --by %1")) { |
835 | CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release()); |
836 | m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp; |
837 | } |
838 | } |
839 | } |
840 | |
841 | int CommandInterpreter::GetCommandNamesMatchingPartialString( |
842 | const char *cmd_str, bool include_aliases, StringList &matches, |
843 | StringList &descriptions) { |
844 | AddNamesMatchingPartialString(m_command_dict, cmd_str, matches, |
845 | &descriptions); |
846 | |
847 | if (include_aliases) { |
848 | AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches, |
849 | &descriptions); |
850 | } |
851 | |
852 | return matches.GetSize(); |
853 | } |
854 | |
855 | CommandObjectSP |
856 | CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases, |
857 | bool exact, StringList *matches, |
858 | StringList *descriptions) const { |
859 | CommandObjectSP command_sp; |
860 | |
861 | std::string cmd = cmd_str; |
862 | |
863 | if (HasCommands()) { |
864 | auto pos = m_command_dict.find(cmd); |
865 | if (pos != m_command_dict.end()) |
866 | command_sp = pos->second; |
867 | } |
868 | |
869 | if (include_aliases && HasAliases()) { |
870 | auto alias_pos = m_alias_dict.find(cmd); |
871 | if (alias_pos != m_alias_dict.end()) |
872 | command_sp = alias_pos->second; |
873 | } |
874 | |
875 | if (HasUserCommands()) { |
876 | auto pos = m_user_dict.find(cmd); |
877 | if (pos != m_user_dict.end()) |
878 | command_sp = pos->second; |
879 | } |
880 | |
881 | if (!exact && !command_sp) { |
882 | // We will only get into here if we didn't find any exact matches. |
883 | |
884 | CommandObjectSP user_match_sp, alias_match_sp, real_match_sp; |
885 | |
886 | StringList local_matches; |
887 | if (matches == nullptr) |
888 | matches = &local_matches; |
889 | |
890 | unsigned int num_cmd_matches = 0; |
891 | unsigned int num_alias_matches = 0; |
892 | unsigned int num_user_matches = 0; |
893 | |
894 | // Look through the command dictionaries one by one, and if we get only one |
895 | // match from any of them in toto, then return that, otherwise return an |
896 | // empty CommandObjectSP and the list of matches. |
897 | |
898 | if (HasCommands()) { |
899 | num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str, |
900 | *matches, descriptions); |
901 | } |
902 | |
903 | if (num_cmd_matches == 1) { |
904 | cmd.assign(matches->GetStringAtIndex(0)); |
905 | auto pos = m_command_dict.find(cmd); |
906 | if (pos != m_command_dict.end()) |
907 | real_match_sp = pos->second; |
908 | } |
909 | |
910 | if (include_aliases && HasAliases()) { |
911 | num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str, |
912 | *matches, descriptions); |
913 | } |
914 | |
915 | if (num_alias_matches == 1) { |
916 | cmd.assign(matches->GetStringAtIndex(num_cmd_matches)); |
917 | auto alias_pos = m_alias_dict.find(cmd); |
918 | if (alias_pos != m_alias_dict.end()) |
919 | alias_match_sp = alias_pos->second; |
920 | } |
921 | |
922 | if (HasUserCommands()) { |
923 | num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str, |
924 | *matches, descriptions); |
925 | } |
926 | |
927 | if (num_user_matches == 1) { |
928 | cmd.assign( |
929 | matches->GetStringAtIndex(num_cmd_matches + num_alias_matches)); |
930 | |
931 | auto pos = m_user_dict.find(cmd); |
932 | if (pos != m_user_dict.end()) |
933 | user_match_sp = pos->second; |
934 | } |
935 | |
936 | // If we got exactly one match, return that, otherwise return the match |
937 | // list. |
938 | |
939 | if (num_user_matches + num_cmd_matches + num_alias_matches == 1) { |
940 | if (num_cmd_matches) |
941 | return real_match_sp; |
942 | else if (num_alias_matches) |
943 | return alias_match_sp; |
944 | else |
945 | return user_match_sp; |
946 | } |
947 | } else if (matches && command_sp) { |
948 | matches->AppendString(cmd_str); |
949 | if (descriptions) |
950 | descriptions->AppendString(command_sp->GetHelp()); |
951 | } |
952 | |
953 | return command_sp; |
954 | } |
955 | |
956 | bool CommandInterpreter::AddCommand(llvm::StringRef name, |
957 | const lldb::CommandObjectSP &cmd_sp, |
958 | bool can_replace) { |
959 | if (cmd_sp.get()) |
960 | lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&lldb_private::lldb_assert(static_cast<bool>((this == & cmd_sp->GetCommandInterpreter()) && "tried to add a CommandObject from a different interpreter" ), "(this == &cmd_sp->GetCommandInterpreter()) && \"tried to add a CommandObject from a different interpreter\"" , __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 961) |
961 | "tried to add a CommandObject from a different interpreter")lldb_private::lldb_assert(static_cast<bool>((this == & cmd_sp->GetCommandInterpreter()) && "tried to add a CommandObject from a different interpreter" ), "(this == &cmd_sp->GetCommandInterpreter()) && \"tried to add a CommandObject from a different interpreter\"" , __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 961); |
962 | |
963 | if (name.empty()) |
964 | return false; |
965 | |
966 | std::string name_sstr(name); |
967 | auto name_iter = m_command_dict.find(name_sstr); |
968 | if (name_iter != m_command_dict.end()) { |
969 | if (!can_replace || !name_iter->second->IsRemovable()) |
970 | return false; |
971 | name_iter->second = cmd_sp; |
972 | } else { |
973 | m_command_dict[name_sstr] = cmd_sp; |
974 | } |
975 | return true; |
976 | } |
977 | |
978 | bool CommandInterpreter::AddUserCommand(llvm::StringRef name, |
979 | const lldb::CommandObjectSP &cmd_sp, |
980 | bool can_replace) { |
981 | if (cmd_sp.get()) |
982 | lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&lldb_private::lldb_assert(static_cast<bool>((this == & cmd_sp->GetCommandInterpreter()) && "tried to add a CommandObject from a different interpreter" ), "(this == &cmd_sp->GetCommandInterpreter()) && \"tried to add a CommandObject from a different interpreter\"" , __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 983) |
983 | "tried to add a CommandObject from a different interpreter")lldb_private::lldb_assert(static_cast<bool>((this == & cmd_sp->GetCommandInterpreter()) && "tried to add a CommandObject from a different interpreter" ), "(this == &cmd_sp->GetCommandInterpreter()) && \"tried to add a CommandObject from a different interpreter\"" , __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 983); |
984 | |
985 | if (!name.empty()) { |
986 | // do not allow replacement of internal commands |
987 | if (CommandExists(name)) { |
988 | if (can_replace == false) |
989 | return false; |
990 | if (m_command_dict[name]->IsRemovable() == false) |
991 | return false; |
992 | } |
993 | |
994 | if (UserCommandExists(name)) { |
995 | if (can_replace == false) |
996 | return false; |
997 | if (m_user_dict[name]->IsRemovable() == false) |
998 | return false; |
999 | } |
1000 | |
1001 | m_user_dict[name] = cmd_sp; |
1002 | return true; |
1003 | } |
1004 | return false; |
1005 | } |
1006 | |
1007 | CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str, |
1008 | bool include_aliases) const { |
1009 | Args cmd_words(cmd_str); // Break up the command string into words, in case |
1010 | // it's a multi-word command. |
1011 | CommandObjectSP ret_val; // Possibly empty return value. |
1012 | |
1013 | if (cmd_str.empty()) |
1014 | return ret_val; |
1015 | |
1016 | if (cmd_words.GetArgumentCount() == 1) |
1017 | return GetCommandSP(cmd_str, include_aliases, true, nullptr); |
1018 | else { |
1019 | // We have a multi-word command (seemingly), so we need to do more work. |
1020 | // First, get the cmd_obj_sp for the first word in the command. |
1021 | CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)), |
1022 | include_aliases, true, nullptr); |
1023 | if (cmd_obj_sp.get() != nullptr) { |
1024 | // Loop through the rest of the words in the command (everything passed |
1025 | // in was supposed to be part of a command name), and find the |
1026 | // appropriate sub-command SP for each command word.... |
1027 | size_t end = cmd_words.GetArgumentCount(); |
1028 | for (size_t j = 1; j < end; ++j) { |
1029 | if (cmd_obj_sp->IsMultiwordObject()) { |
1030 | cmd_obj_sp = |
1031 | cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j)); |
1032 | if (cmd_obj_sp.get() == nullptr) |
1033 | // The sub-command name was invalid. Fail and return the empty |
1034 | // 'ret_val'. |
1035 | return ret_val; |
1036 | } else |
1037 | // We have more words in the command name, but we don't have a |
1038 | // multiword object. Fail and return empty 'ret_val'. |
1039 | return ret_val; |
1040 | } |
1041 | // We successfully looped through all the command words and got valid |
1042 | // command objects for them. Assign the last object retrieved to |
1043 | // 'ret_val'. |
1044 | ret_val = cmd_obj_sp; |
1045 | } |
1046 | } |
1047 | return ret_val; |
1048 | } |
1049 | |
1050 | CommandObject * |
1051 | CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str, |
1052 | StringList *matches, |
1053 | StringList *descriptions) const { |
1054 | CommandObject *command_obj = |
1055 | GetCommandSP(cmd_str, false, true, matches, descriptions).get(); |
1056 | |
1057 | // If we didn't find an exact match to the command string in the commands, |
1058 | // look in the aliases. |
1059 | |
1060 | if (command_obj) |
1061 | return command_obj; |
1062 | |
1063 | command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get(); |
1064 | |
1065 | if (command_obj) |
1066 | return command_obj; |
1067 | |
1068 | // If there wasn't an exact match then look for an inexact one in just the |
1069 | // commands |
1070 | command_obj = GetCommandSP(cmd_str, false, false, nullptr).get(); |
1071 | |
1072 | // Finally, if there wasn't an inexact match among the commands, look for an |
1073 | // inexact match in both the commands and aliases. |
1074 | |
1075 | if (command_obj) { |
1076 | if (matches) |
1077 | matches->AppendString(command_obj->GetCommandName()); |
1078 | if (descriptions) |
1079 | descriptions->AppendString(command_obj->GetHelp()); |
1080 | return command_obj; |
1081 | } |
1082 | |
1083 | return GetCommandSP(cmd_str, true, false, matches, descriptions).get(); |
1084 | } |
1085 | |
1086 | bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const { |
1087 | return m_command_dict.find(cmd) != m_command_dict.end(); |
1088 | } |
1089 | |
1090 | bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd, |
1091 | std::string &full_name) const { |
1092 | bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end()); |
1093 | if (exact_match) { |
1094 | full_name.assign(cmd); |
1095 | return exact_match; |
1096 | } else { |
1097 | StringList matches; |
1098 | size_t num_alias_matches; |
1099 | num_alias_matches = |
1100 | AddNamesMatchingPartialString(m_alias_dict, cmd, matches); |
1101 | if (num_alias_matches == 1) { |
1102 | // Make sure this isn't shadowing a command in the regular command space: |
1103 | StringList regular_matches; |
1104 | const bool include_aliases = false; |
1105 | const bool exact = false; |
1106 | CommandObjectSP cmd_obj_sp( |
1107 | GetCommandSP(cmd, include_aliases, exact, ®ular_matches)); |
1108 | if (cmd_obj_sp || regular_matches.GetSize() > 0) |
1109 | return false; |
1110 | else { |
1111 | full_name.assign(matches.GetStringAtIndex(0)); |
1112 | return true; |
1113 | } |
1114 | } else |
1115 | return false; |
1116 | } |
1117 | } |
1118 | |
1119 | bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const { |
1120 | return m_alias_dict.find(cmd) != m_alias_dict.end(); |
1121 | } |
1122 | |
1123 | bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const { |
1124 | return m_user_dict.find(cmd) != m_user_dict.end(); |
1125 | } |
1126 | |
1127 | CommandAlias * |
1128 | CommandInterpreter::AddAlias(llvm::StringRef alias_name, |
1129 | lldb::CommandObjectSP &command_obj_sp, |
1130 | llvm::StringRef args_string) { |
1131 | if (command_obj_sp.get()) |
1132 | lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&lldb_private::lldb_assert(static_cast<bool>((this == & command_obj_sp->GetCommandInterpreter()) && "tried to add a CommandObject from a different interpreter" ), "(this == &command_obj_sp->GetCommandInterpreter()) && \"tried to add a CommandObject from a different interpreter\"" , __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 1133) |
1133 | "tried to add a CommandObject from a different interpreter")lldb_private::lldb_assert(static_cast<bool>((this == & command_obj_sp->GetCommandInterpreter()) && "tried to add a CommandObject from a different interpreter" ), "(this == &command_obj_sp->GetCommandInterpreter()) && \"tried to add a CommandObject from a different interpreter\"" , __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 1133); |
1134 | |
1135 | std::unique_ptr<CommandAlias> command_alias_up( |
1136 | new CommandAlias(*this, command_obj_sp, args_string, alias_name)); |
1137 | |
1138 | if (command_alias_up && command_alias_up->IsValid()) { |
1139 | m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get()); |
1140 | return command_alias_up.release(); |
1141 | } |
1142 | |
1143 | return nullptr; |
1144 | } |
1145 | |
1146 | bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) { |
1147 | auto pos = m_alias_dict.find(alias_name); |
1148 | if (pos != m_alias_dict.end()) { |
1149 | m_alias_dict.erase(pos); |
1150 | return true; |
1151 | } |
1152 | return false; |
1153 | } |
1154 | |
1155 | bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) { |
1156 | auto pos = m_command_dict.find(cmd); |
1157 | if (pos != m_command_dict.end()) { |
1158 | if (pos->second->IsRemovable()) { |
1159 | // Only regular expression objects or python commands are removable |
1160 | m_command_dict.erase(pos); |
1161 | return true; |
1162 | } |
1163 | } |
1164 | return false; |
1165 | } |
1166 | bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) { |
1167 | CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name); |
1168 | if (pos != m_user_dict.end()) { |
1169 | m_user_dict.erase(pos); |
1170 | return true; |
1171 | } |
1172 | return false; |
1173 | } |
1174 | |
1175 | void CommandInterpreter::GetHelp(CommandReturnObject &result, |
1176 | uint32_t cmd_types) { |
1177 | llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue()); |
1178 | if (!help_prologue.empty()) { |
1179 | OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(), |
1180 | help_prologue); |
1181 | } |
1182 | |
1183 | CommandObject::CommandMap::const_iterator pos; |
1184 | size_t max_len = FindLongestCommandWord(m_command_dict); |
1185 | |
1186 | if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) { |
1187 | result.AppendMessage("Debugger commands:"); |
1188 | result.AppendMessage(""); |
1189 | |
1190 | for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) { |
1191 | if (!(cmd_types & eCommandTypesHidden) && |
1192 | (pos->first.compare(0, 1, "_") == 0)) |
1193 | continue; |
1194 | |
1195 | OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--", |
1196 | pos->second->GetHelp(), max_len); |
1197 | } |
1198 | result.AppendMessage(""); |
1199 | } |
1200 | |
1201 | if (!m_alias_dict.empty() && |
1202 | ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) { |
1203 | result.AppendMessageWithFormat( |
1204 | "Current command abbreviations " |
1205 | "(type '%shelp command alias' for more info):\n", |
1206 | GetCommandPrefix()); |
1207 | result.AppendMessage(""); |
1208 | max_len = FindLongestCommandWord(m_alias_dict); |
1209 | |
1210 | for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end(); |
1211 | ++alias_pos) { |
1212 | OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--", |
1213 | alias_pos->second->GetHelp(), max_len); |
1214 | } |
1215 | result.AppendMessage(""); |
1216 | } |
1217 | |
1218 | if (!m_user_dict.empty() && |
1219 | ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) { |
1220 | result.AppendMessage("Current user-defined commands:"); |
1221 | result.AppendMessage(""); |
1222 | max_len = FindLongestCommandWord(m_user_dict); |
1223 | for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) { |
1224 | OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--", |
1225 | pos->second->GetHelp(), max_len); |
1226 | } |
1227 | result.AppendMessage(""); |
1228 | } |
1229 | |
1230 | result.AppendMessageWithFormat( |
1231 | "For more information on any command, type '%shelp <command-name>'.\n", |
1232 | GetCommandPrefix()); |
1233 | } |
1234 | |
1235 | CommandObject *CommandInterpreter::GetCommandObjectForCommand( |
1236 | llvm::StringRef &command_string) { |
1237 | // This function finds the final, lowest-level, alias-resolved command object |
1238 | // whose 'Execute' function will eventually be invoked by the given command |
1239 | // line. |
1240 | |
1241 | CommandObject *cmd_obj = nullptr; |
1242 | size_t start = command_string.find_first_not_of(k_white_space); |
1243 | size_t end = 0; |
1244 | bool done = false; |
1245 | while (!done) { |
1246 | if (start != std::string::npos) { |
1247 | // Get the next word from command_string. |
1248 | end = command_string.find_first_of(k_white_space, start); |
1249 | if (end == std::string::npos) |
1250 | end = command_string.size(); |
1251 | std::string cmd_word = command_string.substr(start, end - start); |
1252 | |
1253 | if (cmd_obj == nullptr) |
1254 | // Since cmd_obj is NULL we are on our first time through this loop. |
1255 | // Check to see if cmd_word is a valid command or alias. |
1256 | cmd_obj = GetCommandObject(cmd_word); |
1257 | else if (cmd_obj->IsMultiwordObject()) { |
1258 | // Our current object is a multi-word object; see if the cmd_word is a |
1259 | // valid sub-command for our object. |
1260 | CommandObject *sub_cmd_obj = |
1261 | cmd_obj->GetSubcommandObject(cmd_word.c_str()); |
1262 | if (sub_cmd_obj) |
1263 | cmd_obj = sub_cmd_obj; |
1264 | else // cmd_word was not a valid sub-command word, so we are done |
1265 | done = true; |
1266 | } else |
1267 | // We have a cmd_obj and it is not a multi-word object, so we are done. |
1268 | done = true; |
1269 | |
1270 | // If we didn't find a valid command object, or our command object is not |
1271 | // a multi-word object, or we are at the end of the command_string, then |
1272 | // we are done. Otherwise, find the start of the next word. |
1273 | |
1274 | if (!cmd_obj || !cmd_obj->IsMultiwordObject() || |
1275 | end >= command_string.size()) |
1276 | done = true; |
1277 | else |
1278 | start = command_string.find_first_not_of(k_white_space, end); |
1279 | } else |
1280 | // Unable to find any more words. |
1281 | done = true; |
1282 | } |
1283 | |
1284 | command_string = command_string.substr(end); |
1285 | return cmd_obj; |
1286 | } |
1287 | |
1288 | static const char *k_valid_command_chars = |
1289 | "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"; |
1290 | static void StripLeadingSpaces(std::string &s) { |
1291 | if (!s.empty()) { |
1292 | size_t pos = s.find_first_not_of(k_white_space); |
1293 | if (pos == std::string::npos) |
1294 | s.clear(); |
1295 | else if (pos == 0) |
1296 | return; |
1297 | s.erase(0, pos); |
1298 | } |
1299 | } |
1300 | |
1301 | static size_t FindArgumentTerminator(const std::string &s) { |
1302 | const size_t s_len = s.size(); |
1303 | size_t offset = 0; |
1304 | while (offset < s_len) { |
1305 | size_t pos = s.find("--", offset); |
1306 | if (pos == std::string::npos) |
1307 | break; |
1308 | if (pos > 0) { |
1309 | if (isspace(s[pos - 1])) { |
1310 | // Check if the string ends "\s--" (where \s is a space character) or |
1311 | // if we have "\s--\s". |
1312 | if ((pos + 2 >= s_len) || isspace(s[pos + 2])) { |
1313 | return pos; |
1314 | } |
1315 | } |
1316 | } |
1317 | offset = pos + 2; |
1318 | } |
1319 | return std::string::npos; |
1320 | } |
1321 | |
1322 | static bool ExtractCommand(std::string &command_string, std::string &command, |
1323 | std::string &suffix, char "e_char) { |
1324 | command.clear(); |
1325 | suffix.clear(); |
1326 | StripLeadingSpaces(command_string); |
1327 | |
1328 | bool result = false; |
1329 | quote_char = '\0'; |
1330 | |
1331 | if (!command_string.empty()) { |
1332 | const char first_char = command_string[0]; |
1333 | if (first_char == '\'' || first_char == '"') { |
1334 | quote_char = first_char; |
1335 | const size_t end_quote_pos = command_string.find(quote_char, 1); |
1336 | if (end_quote_pos == std::string::npos) { |
1337 | command.swap(command_string); |
1338 | command_string.erase(); |
1339 | } else { |
1340 | command.assign(command_string, 1, end_quote_pos - 1); |
1341 | if (end_quote_pos + 1 < command_string.size()) |
1342 | command_string.erase(0, command_string.find_first_not_of( |
1343 | k_white_space, end_quote_pos + 1)); |
1344 | else |
1345 | command_string.erase(); |
1346 | } |
1347 | } else { |
1348 | const size_t first_space_pos = |
1349 | command_string.find_first_of(k_white_space); |
1350 | if (first_space_pos == std::string::npos) { |
1351 | command.swap(command_string); |
1352 | command_string.erase(); |
1353 | } else { |
1354 | command.assign(command_string, 0, first_space_pos); |
1355 | command_string.erase(0, command_string.find_first_not_of( |
1356 | k_white_space, first_space_pos)); |
1357 | } |
1358 | } |
1359 | result = true; |
1360 | } |
1361 | |
1362 | if (!command.empty()) { |
1363 | // actual commands can't start with '-' or '_' |
1364 | if (command[0] != '-' && command[0] != '_') { |
1365 | size_t pos = command.find_first_not_of(k_valid_command_chars); |
1366 | if (pos > 0 && pos != std::string::npos) { |
1367 | suffix.assign(command.begin() + pos, command.end()); |
1368 | command.erase(pos); |
1369 | } |
1370 | } |
1371 | } |
1372 | |
1373 | return result; |
1374 | } |
1375 | |
1376 | CommandObject *CommandInterpreter::BuildAliasResult( |
1377 | llvm::StringRef alias_name, std::string &raw_input_string, |
1378 | std::string &alias_result, CommandReturnObject &result) { |
1379 | CommandObject *alias_cmd_obj = nullptr; |
1380 | Args cmd_args(raw_input_string); |
1381 | alias_cmd_obj = GetCommandObject(alias_name); |
1382 | StreamString result_str; |
1383 | |
1384 | if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) { |
1385 | alias_result.clear(); |
1386 | return alias_cmd_obj; |
1387 | } |
1388 | std::pair<CommandObjectSP, OptionArgVectorSP> desugared = |
1389 | ((CommandAlias *)alias_cmd_obj)->Desugar(); |
1390 | OptionArgVectorSP option_arg_vector_sp = desugared.second; |
1391 | alias_cmd_obj = desugared.first.get(); |
1392 | std::string alias_name_str = alias_name; |
1393 | if ((cmd_args.GetArgumentCount() == 0) || |
1394 | (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)) |
1395 | cmd_args.Unshift(alias_name_str); |
1396 | |
1397 | result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str()); |
1398 | |
1399 | if (!option_arg_vector_sp.get()) { |
1400 | alias_result = result_str.GetString(); |
1401 | return alias_cmd_obj; |
1402 | } |
1403 | OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); |
1404 | |
1405 | int value_type; |
1406 | std::string option; |
1407 | std::string value; |
1408 | for (const auto &entry : *option_arg_vector) { |
1409 | std::tie(option, value_type, value) = entry; |
1410 | if (option == "<argument>") { |
1411 | result_str.Printf(" %s", value.c_str()); |
1412 | continue; |
1413 | } |
1414 | |
1415 | result_str.Printf(" %s", option.c_str()); |
1416 | if (value_type == OptionParser::eNoArgument) |
1417 | continue; |
1418 | |
1419 | if (value_type != OptionParser::eOptionalArgument) |
1420 | result_str.Printf(" "); |
1421 | int index = GetOptionArgumentPosition(value.c_str()); |
1422 | if (index == 0) |
1423 | result_str.Printf("%s", value.c_str()); |
1424 | else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) { |
1425 | |
1426 | result.AppendErrorWithFormat("Not enough arguments provided; you " |
1427 | "need at least %d arguments to use " |
1428 | "this alias.\n", |
1429 | index); |
1430 | result.SetStatus(eReturnStatusFailed); |
1431 | return nullptr; |
1432 | } else { |
1433 | size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index)); |
1434 | if (strpos != std::string::npos) |
1435 | raw_input_string = raw_input_string.erase( |
1436 | strpos, strlen(cmd_args.GetArgumentAtIndex(index))); |
1437 | result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index)); |
1438 | } |
1439 | } |
1440 | |
1441 | alias_result = result_str.GetString(); |
1442 | return alias_cmd_obj; |
1443 | } |
1444 | |
1445 | Status CommandInterpreter::PreprocessCommand(std::string &command) { |
1446 | // The command preprocessor needs to do things to the command line before any |
1447 | // parsing of arguments or anything else is done. The only current stuff that |
1448 | // gets preprocessed is anything enclosed in backtick ('`') characters is |
1449 | // evaluated as an expression and the result of the expression must be a |
1450 | // scalar that can be substituted into the command. An example would be: |
1451 | // (lldb) memory read `$rsp + 20` |
1452 | Status error; // Status for any expressions that might not evaluate |
1453 | size_t start_backtick; |
1454 | size_t pos = 0; |
1455 | while ((start_backtick = command.find('`', pos)) != std::string::npos) { |
1456 | if (start_backtick > 0 && command[start_backtick - 1] == '\\') { |
1457 | // The backtick was preceded by a '\' character, remove the slash and |
1458 | // don't treat the backtick as the start of an expression |
1459 | command.erase(start_backtick - 1, 1); |
1460 | // No need to add one to start_backtick since we just deleted a char |
1461 | pos = start_backtick; |
1462 | } else { |
1463 | const size_t expr_content_start = start_backtick + 1; |
1464 | const size_t end_backtick = command.find('`', expr_content_start); |
1465 | if (end_backtick == std::string::npos) |
1466 | return error; |
1467 | else if (end_backtick == expr_content_start) { |
1468 | // Empty expression (two backticks in a row) |
1469 | command.erase(start_backtick, 2); |
1470 | } else { |
1471 | std::string expr_str(command, expr_content_start, |
1472 | end_backtick - expr_content_start); |
1473 | |
1474 | ExecutionContext exe_ctx(GetExecutionContext()); |
1475 | Target *target = exe_ctx.GetTargetPtr(); |
1476 | // Get a dummy target to allow for calculator mode while processing |
1477 | // backticks. This also helps break the infinite loop caused when |
1478 | // target is null. |
1479 | if (!target) |
1480 | target = m_debugger.GetDummyTarget(); |
1481 | if (target) { |
1482 | ValueObjectSP expr_result_valobj_sp; |
1483 | |
1484 | EvaluateExpressionOptions options; |
1485 | options.SetCoerceToId(false); |
1486 | options.SetUnwindOnError(true); |
1487 | options.SetIgnoreBreakpoints(true); |
1488 | options.SetKeepInMemory(false); |
1489 | options.SetTryAllThreads(true); |
1490 | options.SetTimeout(llvm::None); |
1491 | |
1492 | ExpressionResults expr_result = target->EvaluateExpression( |
1493 | expr_str.c_str(), exe_ctx.GetFramePtr(), expr_result_valobj_sp, |
1494 | options); |
1495 | |
1496 | if (expr_result == eExpressionCompleted) { |
1497 | Scalar scalar; |
1498 | if (expr_result_valobj_sp) |
1499 | expr_result_valobj_sp = |
1500 | expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable( |
1501 | expr_result_valobj_sp->GetDynamicValueType(), true); |
1502 | if (expr_result_valobj_sp->ResolveValue(scalar)) { |
1503 | command.erase(start_backtick, end_backtick - start_backtick + 1); |
1504 | StreamString value_strm; |
1505 | const bool show_type = false; |
1506 | scalar.GetValue(&value_strm, show_type); |
1507 | size_t value_string_size = value_strm.GetSize(); |
1508 | if (value_string_size) { |
1509 | command.insert(start_backtick, value_strm.GetString()); |
1510 | pos = start_backtick + value_string_size; |
1511 | continue; |
1512 | } else { |
1513 | error.SetErrorStringWithFormat("expression value didn't result " |
1514 | "in a scalar value for the " |
1515 | "expression '%s'", |
1516 | expr_str.c_str()); |
1517 | } |
1518 | } else { |
1519 | error.SetErrorStringWithFormat("expression value didn't result " |
1520 | "in a scalar value for the " |
1521 | "expression '%s'", |
1522 | expr_str.c_str()); |
1523 | } |
1524 | } else { |
1525 | if (expr_result_valobj_sp) |
1526 | error = expr_result_valobj_sp->GetError(); |
1527 | if (error.Success()) { |
1528 | |
1529 | switch (expr_result) { |
1530 | case eExpressionSetupError: |
1531 | error.SetErrorStringWithFormat( |
1532 | "expression setup error for the expression '%s'", |
1533 | expr_str.c_str()); |
1534 | break; |
1535 | case eExpressionParseError: |
1536 | error.SetErrorStringWithFormat( |
1537 | "expression parse error for the expression '%s'", |
1538 | expr_str.c_str()); |
1539 | break; |
1540 | case eExpressionResultUnavailable: |
1541 | error.SetErrorStringWithFormat( |
1542 | "expression error fetching result for the expression '%s'", |
1543 | expr_str.c_str()); |
1544 | break; |
1545 | case eExpressionCompleted: |
1546 | break; |
1547 | case eExpressionDiscarded: |
1548 | error.SetErrorStringWithFormat( |
1549 | "expression discarded for the expression '%s'", |
1550 | expr_str.c_str()); |
1551 | break; |
1552 | case eExpressionInterrupted: |
1553 | error.SetErrorStringWithFormat( |
1554 | "expression interrupted for the expression '%s'", |
1555 | expr_str.c_str()); |
1556 | break; |
1557 | case eExpressionHitBreakpoint: |
1558 | error.SetErrorStringWithFormat( |
1559 | "expression hit breakpoint for the expression '%s'", |
1560 | expr_str.c_str()); |
1561 | break; |
1562 | case eExpressionTimedOut: |
1563 | error.SetErrorStringWithFormat( |
1564 | "expression timed out for the expression '%s'", |
1565 | expr_str.c_str()); |
1566 | break; |
1567 | case eExpressionStoppedForDebug: |
1568 | error.SetErrorStringWithFormat("expression stop at entry point " |
1569 | "for debugging for the " |
1570 | "expression '%s'", |
1571 | expr_str.c_str()); |
1572 | break; |
1573 | } |
1574 | } |
1575 | } |
1576 | } |
1577 | } |
1578 | if (error.Fail()) |
1579 | break; |
1580 | } |
1581 | } |
1582 | return error; |
1583 | } |
1584 | |
1585 | bool CommandInterpreter::HandleCommand(const char *command_line, |
1586 | LazyBool lazy_add_to_history, |
1587 | CommandReturnObject &result, |
1588 | ExecutionContext *override_context, |
1589 | bool repeat_on_empty_command, |
1590 | bool no_context_switching) |
1591 | |
1592 | { |
1593 | |
1594 | std::string command_string(command_line); |
1595 | std::string original_command_string(command_line); |
1596 | |
1597 | Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS(1U << 18))); |
1598 | llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")", |
1599 | command_line); |
1600 | |
1601 | if (log) |
1602 | log->Printf("Processing command: %s", command_line); |
1603 | |
1604 | static Timer::Category func_cat(LLVM_PRETTY_FUNCTION__PRETTY_FUNCTION__); |
1605 | Timer scoped_timer(func_cat, "Handling command: %s.", command_line); |
1606 | |
1607 | if (!no_context_switching) |
1608 | UpdateExecutionContext(override_context); |
1609 | |
1610 | if (WasInterrupted()) { |
1611 | result.AppendError("interrupted"); |
1612 | result.SetStatus(eReturnStatusFailed); |
1613 | return false; |
1614 | } |
1615 | |
1616 | bool add_to_history; |
1617 | if (lazy_add_to_history == eLazyBoolCalculate) |
1618 | add_to_history = (m_command_source_depth == 0); |
1619 | else |
1620 | add_to_history = (lazy_add_to_history == eLazyBoolYes); |
1621 | |
1622 | bool empty_command = false; |
1623 | bool comment_command = false; |
1624 | if (command_string.empty()) |
1625 | empty_command = true; |
1626 | else { |
1627 | const char *k_space_characters = "\t\n\v\f\r "; |
1628 | |
1629 | size_t non_space = command_string.find_first_not_of(k_space_characters); |
1630 | // Check for empty line or comment line (lines whose first non-space |
1631 | // character is the comment character for this interpreter) |
1632 | if (non_space == std::string::npos) |
1633 | empty_command = true; |
1634 | else if (command_string[non_space] == m_comment_char) |
1635 | comment_command = true; |
1636 | else if (command_string[non_space] == CommandHistory::g_repeat_char) { |
1637 | llvm::StringRef search_str(command_string); |
1638 | search_str = search_str.drop_front(non_space); |
1639 | if (auto hist_str = m_command_history.FindString(search_str)) { |
1640 | add_to_history = false; |
1641 | command_string = *hist_str; |
1642 | original_command_string = *hist_str; |
1643 | } else { |
1644 | result.AppendErrorWithFormat("Could not find entry: %s in history", |
1645 | command_string.c_str()); |
1646 | result.SetStatus(eReturnStatusFailed); |
1647 | return false; |
1648 | } |
1649 | } |
1650 | } |
1651 | |
1652 | if (empty_command) { |
1653 | if (repeat_on_empty_command) { |
1654 | if (m_command_history.IsEmpty()) { |
1655 | result.AppendError("empty command"); |
1656 | result.SetStatus(eReturnStatusFailed); |
1657 | return false; |
1658 | } else { |
1659 | command_line = m_repeat_command.c_str(); |
1660 | command_string = command_line; |
1661 | original_command_string = command_line; |
1662 | if (m_repeat_command.empty()) { |
1663 | result.AppendErrorWithFormat("No auto repeat.\n"); |
1664 | result.SetStatus(eReturnStatusFailed); |
1665 | return false; |
1666 | } |
1667 | } |
1668 | add_to_history = false; |
1669 | } else { |
1670 | result.SetStatus(eReturnStatusSuccessFinishNoResult); |
1671 | return true; |
1672 | } |
1673 | } else if (comment_command) { |
1674 | result.SetStatus(eReturnStatusSuccessFinishNoResult); |
1675 | return true; |
1676 | } |
1677 | |
1678 | Status error(PreprocessCommand(command_string)); |
1679 | |
1680 | if (error.Fail()) { |
1681 | result.AppendError(error.AsCString()); |
1682 | result.SetStatus(eReturnStatusFailed); |
1683 | return false; |
1684 | } |
1685 | |
1686 | // Phase 1. |
1687 | |
1688 | // Before we do ANY kind of argument processing, we need to figure out what |
1689 | // the real/final command object is for the specified command. This gets |
1690 | // complicated by the fact that the user could have specified an alias, and, |
1691 | // in translating the alias, there may also be command options and/or even |
1692 | // data (including raw text strings) that need to be found and inserted into |
1693 | // the command line as part of the translation. So this first step is plain |
1694 | // look-up and replacement, resulting in: |
1695 | // 1. the command object whose Execute method will actually be called |
1696 | // 2. a revised command string, with all substitutions and replacements |
1697 | // taken care of |
1698 | // From 1 above, we can determine whether the Execute function wants raw |
1699 | // input or not. |
1700 | |
1701 | CommandObject *cmd_obj = ResolveCommandImpl(command_string, result); |
1702 | |
1703 | // Although the user may have abbreviated the command, the command_string now |
1704 | // has the command expanded to the full name. For example, if the input was |
1705 | // "br s -n main", command_string is now "breakpoint set -n main". |
1706 | if (log) { |
1707 | llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>"; |
1708 | log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str()); |
1709 | log->Printf("HandleCommand, (revised) command_string: '%s'", |
1710 | command_string.c_str()); |
1711 | const bool wants_raw_input = |
1712 | (cmd_obj != NULL__null) ? cmd_obj->WantsRawCommandString() : false; |
1713 | log->Printf("HandleCommand, wants_raw_input:'%s'", |
1714 | wants_raw_input ? "True" : "False"); |
1715 | } |
1716 | |
1717 | // Phase 2. |
1718 | // Take care of things like setting up the history command & calling the |
1719 | // appropriate Execute method on the CommandObject, with the appropriate |
1720 | // arguments. |
1721 | |
1722 | if (cmd_obj != nullptr) { |
1723 | if (add_to_history) { |
1724 | Args command_args(command_string); |
1725 | const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0); |
1726 | if (repeat_command != nullptr) |
1727 | m_repeat_command.assign(repeat_command); |
1728 | else |
1729 | m_repeat_command.assign(original_command_string); |
1730 | |
1731 | m_command_history.AppendString(original_command_string); |
1732 | } |
1733 | |
1734 | std::string remainder; |
1735 | const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size(); |
1736 | if (actual_cmd_name_len < command_string.length()) |
1737 | remainder = command_string.substr(actual_cmd_name_len); |
1738 | |
1739 | // Remove any initial spaces |
1740 | size_t pos = remainder.find_first_not_of(k_white_space); |
1741 | if (pos != 0 && pos != std::string::npos) |
1742 | remainder.erase(0, pos); |
1743 | |
1744 | if (log) |
1745 | log->Printf( |
1746 | "HandleCommand, command line after removing command name(s): '%s'", |
1747 | remainder.c_str()); |
1748 | |
1749 | cmd_obj->Execute(remainder.c_str(), result); |
1750 | } |
1751 | |
1752 | if (log) |
1753 | log->Printf("HandleCommand, command %s", |
1754 | (result.Succeeded() ? "succeeded" : "did not succeed")); |
1755 | |
1756 | return result.Succeeded(); |
1757 | } |
1758 | |
1759 | int CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) { |
1760 | int num_command_matches = 0; |
1761 | bool look_for_subcommand = false; |
1762 | |
1763 | // For any of the command completions a unique match will be a complete word. |
1764 | request.SetWordComplete(true); |
1765 | |
1766 | if (request.GetCursorIndex() == -1) { |
1767 | // We got nothing on the command line, so return the list of commands |
1768 | bool include_aliases = true; |
1769 | StringList new_matches, descriptions; |
1770 | num_command_matches = GetCommandNamesMatchingPartialString( |
1771 | "", include_aliases, new_matches, descriptions); |
1772 | request.AddCompletions(new_matches, descriptions); |
1773 | } else if (request.GetCursorIndex() == 0) { |
1774 | // The cursor is in the first argument, so just do a lookup in the |
1775 | // dictionary. |
1776 | StringList new_matches, new_descriptions; |
1777 | CommandObject *cmd_obj = |
1778 | GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0), |
1779 | &new_matches, &new_descriptions); |
1780 | |
1781 | if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() && |
1782 | new_matches.GetStringAtIndex(0) != nullptr && |
1783 | strcmp(request.GetParsedLine().GetArgumentAtIndex(0), |
1784 | new_matches.GetStringAtIndex(0)) == 0) { |
1785 | if (request.GetParsedLine().GetArgumentCount() == 1) { |
1786 | request.SetWordComplete(true); |
1787 | } else { |
1788 | look_for_subcommand = true; |
1789 | num_command_matches = 0; |
Value stored to 'num_command_matches' is never read | |
1790 | new_matches.DeleteStringAtIndex(0); |
1791 | new_descriptions.DeleteStringAtIndex(0); |
1792 | request.GetParsedLine().AppendArgument(llvm::StringRef()); |
1793 | request.SetCursorIndex(request.GetCursorIndex() + 1); |
1794 | request.SetCursorCharPosition(0); |
1795 | } |
1796 | } |
1797 | request.AddCompletions(new_matches, new_descriptions); |
1798 | num_command_matches = request.GetNumberOfMatches(); |
1799 | } |
1800 | |
1801 | if (request.GetCursorIndex() > 0 || look_for_subcommand) { |
1802 | // We are completing further on into a commands arguments, so find the |
1803 | // command and tell it to complete the command. First see if there is a |
1804 | // matching initial command: |
1805 | CommandObject *command_object = |
1806 | GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0)); |
1807 | if (command_object == nullptr) { |
1808 | return 0; |
1809 | } else { |
1810 | request.GetParsedLine().Shift(); |
1811 | request.SetCursorIndex(request.GetCursorIndex() - 1); |
1812 | num_command_matches = command_object->HandleCompletion(request); |
1813 | } |
1814 | } |
1815 | |
1816 | return num_command_matches; |
1817 | } |
1818 | |
1819 | int CommandInterpreter::HandleCompletion( |
1820 | const char *current_line, const char *cursor, const char *last_char, |
1821 | int match_start_point, int max_return_elements, StringList &matches, |
1822 | StringList &descriptions) { |
1823 | |
1824 | llvm::StringRef command_line(current_line, last_char - current_line); |
1825 | CompletionResult result; |
1826 | CompletionRequest request(command_line, cursor - current_line, |
1827 | match_start_point, max_return_elements, result); |
1828 | // Don't complete comments, and if the line we are completing is just the |
1829 | // history repeat character, substitute the appropriate history line. |
1830 | const char *first_arg = request.GetParsedLine().GetArgumentAtIndex(0); |
1831 | if (first_arg) { |
1832 | if (first_arg[0] == m_comment_char) |
1833 | return 0; |
1834 | else if (first_arg[0] == CommandHistory::g_repeat_char) { |
1835 | if (auto hist_str = m_command_history.FindString(first_arg)) { |
1836 | matches.InsertStringAtIndex(0, *hist_str); |
1837 | descriptions.InsertStringAtIndex(0, "Previous command history event"); |
1838 | return -2; |
1839 | } else |
1840 | return 0; |
1841 | } |
1842 | } |
1843 | |
1844 | // Only max_return_elements == -1 is supported at present: |
1845 | lldbassert(max_return_elements == -1)lldb_private::lldb_assert(static_cast<bool>(max_return_elements == -1), "max_return_elements == -1", __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 1845); |
1846 | |
1847 | int num_command_matches = HandleCompletionMatches(request); |
1848 | result.GetMatches(matches); |
1849 | result.GetDescriptions(descriptions); |
1850 | |
1851 | if (num_command_matches <= 0) |
1852 | return num_command_matches; |
1853 | |
1854 | if (request.GetParsedLine().GetArgumentCount() == 0) { |
1855 | // If we got an empty string, insert nothing. |
1856 | matches.InsertStringAtIndex(0, ""); |
1857 | descriptions.InsertStringAtIndex(0, ""); |
1858 | } else { |
1859 | // Now figure out if there is a common substring, and if so put that in |
1860 | // element 0, otherwise put an empty string in element 0. |
1861 | std::string command_partial_str = request.GetCursorArgumentPrefix().str(); |
1862 | |
1863 | std::string common_prefix; |
1864 | matches.LongestCommonPrefix(common_prefix); |
1865 | const size_t partial_name_len = command_partial_str.size(); |
1866 | common_prefix.erase(0, partial_name_len); |
1867 | |
1868 | // If we matched a unique single command, add a space... Only do this if |
1869 | // the completer told us this was a complete word, however... |
1870 | if (num_command_matches == 1 && request.GetWordComplete()) { |
1871 | char quote_char = request.GetParsedLine()[request.GetCursorIndex()].quote; |
1872 | common_prefix = |
1873 | Args::EscapeLLDBCommandArgument(common_prefix, quote_char); |
1874 | if (quote_char != '\0') |
1875 | common_prefix.push_back(quote_char); |
1876 | common_prefix.push_back(' '); |
1877 | } |
1878 | matches.InsertStringAtIndex(0, common_prefix.c_str()); |
1879 | descriptions.InsertStringAtIndex(0, ""); |
1880 | } |
1881 | return num_command_matches; |
1882 | } |
1883 | |
1884 | CommandInterpreter::~CommandInterpreter() {} |
1885 | |
1886 | void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) { |
1887 | EventSP prompt_change_event_sp( |
1888 | new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt))); |
1889 | ; |
1890 | BroadcastEvent(prompt_change_event_sp); |
1891 | if (m_command_io_handler_sp) |
1892 | m_command_io_handler_sp->SetPrompt(new_prompt); |
1893 | } |
1894 | |
1895 | bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) { |
1896 | // Check AutoConfirm first: |
1897 | if (m_debugger.GetAutoConfirm()) |
1898 | return default_answer; |
1899 | |
1900 | IOHandlerConfirm *confirm = |
1901 | new IOHandlerConfirm(m_debugger, message, default_answer); |
1902 | IOHandlerSP io_handler_sp(confirm); |
1903 | m_debugger.RunIOHandler(io_handler_sp); |
1904 | return confirm->GetResponse(); |
1905 | } |
1906 | |
1907 | const CommandAlias * |
1908 | CommandInterpreter::GetAlias(llvm::StringRef alias_name) const { |
1909 | OptionArgVectorSP ret_val; |
1910 | |
1911 | auto pos = m_alias_dict.find(alias_name); |
1912 | if (pos != m_alias_dict.end()) |
1913 | return (CommandAlias *)pos->second.get(); |
1914 | |
1915 | return nullptr; |
1916 | } |
1917 | |
1918 | bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); } |
1919 | |
1920 | bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); } |
1921 | |
1922 | bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); } |
1923 | |
1924 | bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); } |
1925 | |
1926 | void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj, |
1927 | const char *alias_name, |
1928 | Args &cmd_args, |
1929 | std::string &raw_input_string, |
1930 | CommandReturnObject &result) { |
1931 | OptionArgVectorSP option_arg_vector_sp = |
1932 | GetAlias(alias_name)->GetOptionArguments(); |
1933 | |
1934 | bool wants_raw_input = alias_cmd_obj->WantsRawCommandString(); |
1935 | |
1936 | // Make sure that the alias name is the 0th element in cmd_args |
1937 | std::string alias_name_str = alias_name; |
1938 | if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0) |
1939 | cmd_args.Unshift(alias_name_str); |
1940 | |
1941 | Args new_args(alias_cmd_obj->GetCommandName()); |
1942 | if (new_args.GetArgumentCount() == 2) |
1943 | new_args.Shift(); |
1944 | |
1945 | if (option_arg_vector_sp.get()) { |
1946 | if (wants_raw_input) { |
1947 | // We have a command that both has command options and takes raw input. |
1948 | // Make *sure* it has a " -- " in the right place in the |
1949 | // raw_input_string. |
1950 | size_t pos = raw_input_string.find(" -- "); |
1951 | if (pos == std::string::npos) { |
1952 | // None found; assume it goes at the beginning of the raw input string |
1953 | raw_input_string.insert(0, " -- "); |
1954 | } |
1955 | } |
1956 | |
1957 | OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); |
1958 | const size_t old_size = cmd_args.GetArgumentCount(); |
1959 | std::vector<bool> used(old_size + 1, false); |
1960 | |
1961 | used[0] = true; |
1962 | |
1963 | int value_type; |
1964 | std::string option; |
1965 | std::string value; |
1966 | for (const auto &option_entry : *option_arg_vector) { |
1967 | std::tie(option, value_type, value) = option_entry; |
1968 | if (option == "<argument>") { |
1969 | if (!wants_raw_input || (value != "--")) { |
1970 | // Since we inserted this above, make sure we don't insert it twice |
1971 | new_args.AppendArgument(value); |
1972 | } |
1973 | continue; |
1974 | } |
1975 | |
1976 | if (value_type != OptionParser::eOptionalArgument) |
1977 | new_args.AppendArgument(option); |
1978 | |
1979 | if (value == "<no-argument>") |
1980 | continue; |
1981 | |
1982 | int index = GetOptionArgumentPosition(value.c_str()); |
1983 | if (index == 0) { |
1984 | // value was NOT a positional argument; must be a real value |
1985 | if (value_type != OptionParser::eOptionalArgument) |
1986 | new_args.AppendArgument(value); |
1987 | else { |
1988 | char buffer[255]; |
1989 | ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(), |
1990 | value.c_str()); |
1991 | new_args.AppendArgument(llvm::StringRef(buffer)); |
1992 | } |
1993 | |
1994 | } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) { |
1995 | result.AppendErrorWithFormat("Not enough arguments provided; you " |
1996 | "need at least %d arguments to use " |
1997 | "this alias.\n", |
1998 | index); |
1999 | result.SetStatus(eReturnStatusFailed); |
2000 | return; |
2001 | } else { |
2002 | // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string |
2003 | size_t strpos = |
2004 | raw_input_string.find(cmd_args.GetArgumentAtIndex(index)); |
2005 | if (strpos != std::string::npos) { |
2006 | raw_input_string = raw_input_string.erase( |
2007 | strpos, strlen(cmd_args.GetArgumentAtIndex(index))); |
2008 | } |
2009 | |
2010 | if (value_type != OptionParser::eOptionalArgument) |
2011 | new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index)); |
2012 | else { |
2013 | char buffer[255]; |
2014 | ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(), |
2015 | cmd_args.GetArgumentAtIndex(index)); |
2016 | new_args.AppendArgument(buffer); |
2017 | } |
2018 | used[index] = true; |
2019 | } |
2020 | } |
2021 | |
2022 | for (auto entry : llvm::enumerate(cmd_args.entries())) { |
2023 | if (!used[entry.index()] && !wants_raw_input) |
2024 | new_args.AppendArgument(entry.value().ref); |
2025 | } |
2026 | |
2027 | cmd_args.Clear(); |
2028 | cmd_args.SetArguments(new_args.GetArgumentCount(), |
2029 | new_args.GetConstArgumentVector()); |
2030 | } else { |
2031 | result.SetStatus(eReturnStatusSuccessFinishNoResult); |
2032 | // This alias was not created with any options; nothing further needs to be |
2033 | // done, unless it is a command that wants raw input, in which case we need |
2034 | // to clear the rest of the data from cmd_args, since its in the raw input |
2035 | // string. |
2036 | if (wants_raw_input) { |
2037 | cmd_args.Clear(); |
2038 | cmd_args.SetArguments(new_args.GetArgumentCount(), |
2039 | new_args.GetConstArgumentVector()); |
2040 | } |
2041 | return; |
2042 | } |
2043 | |
2044 | result.SetStatus(eReturnStatusSuccessFinishNoResult); |
2045 | return; |
2046 | } |
2047 | |
2048 | int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) { |
2049 | int position = 0; // Any string that isn't an argument position, i.e. '%' |
2050 | // followed by an integer, gets a position |
2051 | // of zero. |
2052 | |
2053 | const char *cptr = in_string; |
2054 | |
2055 | // Does it start with '%' |
2056 | if (cptr[0] == '%') { |
2057 | ++cptr; |
2058 | |
2059 | // Is the rest of it entirely digits? |
2060 | if (isdigit(cptr[0])) { |
2061 | const char *start = cptr; |
2062 | while (isdigit(cptr[0])) |
2063 | ++cptr; |
2064 | |
2065 | // We've gotten to the end of the digits; are we at the end of the |
2066 | // string? |
2067 | if (cptr[0] == '\0') |
2068 | position = atoi(start); |
2069 | } |
2070 | } |
2071 | |
2072 | return position; |
2073 | } |
2074 | |
2075 | void CommandInterpreter::SourceInitFile(bool in_cwd, |
2076 | CommandReturnObject &result) { |
2077 | FileSpec init_file; |
2078 | if (in_cwd) { |
2079 | ExecutionContext exe_ctx(GetExecutionContext()); |
2080 | Target *target = exe_ctx.GetTargetPtr(); |
2081 | if (target) { |
2082 | // In the current working directory we don't load any program specific |
2083 | // .lldbinit files, we only look for a ".lldbinit" file. |
2084 | if (m_skip_lldbinit_files) |
2085 | return; |
2086 | |
2087 | LoadCWDlldbinitFile should_load = |
2088 | target->TargetProperties::GetLoadCWDlldbinitFile(); |
2089 | if (should_load == eLoadCWDlldbinitWarn) { |
2090 | FileSpec dot_lldb(".lldbinit", true); |
2091 | llvm::SmallString<64> home_dir_path; |
2092 | llvm::sys::path::home_directory(home_dir_path); |
2093 | FileSpec homedir_dot_lldb(home_dir_path.c_str(), false); |
2094 | homedir_dot_lldb.AppendPathComponent(".lldbinit"); |
2095 | homedir_dot_lldb.ResolvePath(); |
2096 | if (dot_lldb.Exists() && |
2097 | dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) { |
2098 | result.AppendErrorWithFormat( |
2099 | "There is a .lldbinit file in the current directory which is not " |
2100 | "being read.\n" |
2101 | "To silence this warning without sourcing in the local " |
2102 | ".lldbinit,\n" |
2103 | "add the following to the lldbinit file in your home directory:\n" |
2104 | " settings set target.load-cwd-lldbinit false\n" |
2105 | "To allow lldb to source .lldbinit files in the current working " |
2106 | "directory,\n" |
2107 | "set the value of this variable to true. Only do so if you " |
2108 | "understand and\n" |
2109 | "accept the security risk."); |
2110 | result.SetStatus(eReturnStatusFailed); |
2111 | return; |
2112 | } |
2113 | } else if (should_load == eLoadCWDlldbinitTrue) { |
2114 | init_file.SetFile("./.lldbinit", true, FileSpec::Style::native); |
2115 | } |
2116 | } |
2117 | } else { |
2118 | // If we aren't looking in the current working directory we are looking in |
2119 | // the home directory. We will first see if there is an application |
2120 | // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a "-" |
2121 | // and the name of the program. If this file doesn't exist, we fall back to |
2122 | // just the "~/.lldbinit" file. We also obey any requests to not load the |
2123 | // init files. |
2124 | llvm::SmallString<64> home_dir_path; |
2125 | llvm::sys::path::home_directory(home_dir_path); |
2126 | FileSpec profilePath(home_dir_path.c_str(), false); |
2127 | profilePath.AppendPathComponent(".lldbinit"); |
2128 | std::string init_file_path = profilePath.GetPath(); |
2129 | |
2130 | if (m_skip_app_init_files == false) { |
2131 | FileSpec program_file_spec(HostInfo::GetProgramFileSpec()); |
2132 | const char *program_name = program_file_spec.GetFilename().AsCString(); |
2133 | |
2134 | if (program_name) { |
2135 | char program_init_file_name[PATH_MAX4096]; |
2136 | ::snprintf(program_init_file_name, sizeof(program_init_file_name), |
2137 | "%s-%s", init_file_path.c_str(), program_name); |
2138 | init_file.SetFile(program_init_file_name, true, |
2139 | FileSpec::Style::native); |
2140 | if (!init_file.Exists()) |
2141 | init_file.Clear(); |
2142 | } |
2143 | } |
2144 | |
2145 | if (!init_file && !m_skip_lldbinit_files) |
2146 | init_file.SetFile(init_file_path, false, FileSpec::Style::native); |
2147 | } |
2148 | |
2149 | // If the file exists, tell HandleCommand to 'source' it; this will do the |
2150 | // actual broadcasting of the commands back to any appropriate listener (see |
2151 | // CommandObjectSource::Execute for more details). |
2152 | |
2153 | if (init_file.Exists()) { |
2154 | const bool saved_batch = SetBatchCommandMode(true); |
2155 | CommandInterpreterRunOptions options; |
2156 | options.SetSilent(true); |
2157 | options.SetStopOnError(false); |
2158 | options.SetStopOnContinue(true); |
2159 | |
2160 | HandleCommandsFromFile(init_file, |
2161 | nullptr, // Execution context |
2162 | options, result); |
2163 | SetBatchCommandMode(saved_batch); |
2164 | } else { |
2165 | // nothing to be done if the file doesn't exist |
2166 | result.SetStatus(eReturnStatusSuccessFinishNoResult); |
2167 | } |
2168 | } |
2169 | |
2170 | const char *CommandInterpreter::GetCommandPrefix() { |
2171 | const char *prefix = GetDebugger().GetIOHandlerCommandPrefix(); |
2172 | return prefix == NULL__null ? "" : prefix; |
2173 | } |
2174 | |
2175 | PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) { |
2176 | PlatformSP platform_sp; |
2177 | if (prefer_target_platform) { |
2178 | ExecutionContext exe_ctx(GetExecutionContext()); |
2179 | Target *target = exe_ctx.GetTargetPtr(); |
2180 | if (target) |
2181 | platform_sp = target->GetPlatform(); |
2182 | } |
2183 | |
2184 | if (!platform_sp) |
2185 | platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform(); |
2186 | return platform_sp; |
2187 | } |
2188 | |
2189 | void CommandInterpreter::HandleCommands(const StringList &commands, |
2190 | ExecutionContext *override_context, |
2191 | CommandInterpreterRunOptions &options, |
2192 | CommandReturnObject &result) { |
2193 | size_t num_lines = commands.GetSize(); |
2194 | |
2195 | // If we are going to continue past a "continue" then we need to run the |
2196 | // commands synchronously. Make sure you reset this value anywhere you return |
2197 | // from the function. |
2198 | |
2199 | bool old_async_execution = m_debugger.GetAsyncExecution(); |
2200 | |
2201 | // If we've been given an execution context, set it at the start, but don't |
2202 | // keep resetting it or we will cause series of commands that change the |
2203 | // context, then do an operation that relies on that context to fail. |
2204 | |
2205 | if (override_context != nullptr) |
2206 | UpdateExecutionContext(override_context); |
2207 | |
2208 | if (!options.GetStopOnContinue()) { |
2209 | m_debugger.SetAsyncExecution(false); |
2210 | } |
2211 | |
2212 | for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) { |
2213 | const char *cmd = commands.GetStringAtIndex(idx); |
2214 | if (cmd[0] == '\0') |
2215 | continue; |
2216 | |
2217 | if (options.GetEchoCommands()) { |
2218 | // TODO: Add Stream support. |
2219 | result.AppendMessageWithFormat("%s %s\n", |
2220 | m_debugger.GetPrompt().str().c_str(), cmd); |
2221 | } |
2222 | |
2223 | CommandReturnObject tmp_result; |
2224 | // If override_context is not NULL, pass no_context_switching = true for |
2225 | // HandleCommand() since we updated our context already. |
2226 | |
2227 | // We might call into a regex or alias command, in which case the |
2228 | // add_to_history will get lost. This m_command_source_depth dingus is the |
2229 | // way we turn off adding to the history in that case, so set it up here. |
2230 | if (!options.GetAddToHistory()) |
2231 | m_command_source_depth++; |
2232 | bool success = |
2233 | HandleCommand(cmd, options.m_add_to_history, tmp_result, |
2234 | nullptr, /* override_context */ |
2235 | true, /* repeat_on_empty_command */ |
2236 | override_context != nullptr /* no_context_switching */); |
2237 | if (!options.GetAddToHistory()) |
2238 | m_command_source_depth--; |
2239 | |
2240 | if (options.GetPrintResults()) { |
2241 | if (tmp_result.Succeeded()) |
2242 | result.AppendMessage(tmp_result.GetOutputData()); |
2243 | } |
2244 | |
2245 | if (!success || !tmp_result.Succeeded()) { |
2246 | llvm::StringRef error_msg = tmp_result.GetErrorData(); |
2247 | if (error_msg.empty()) |
2248 | error_msg = "<unknown error>.\n"; |
2249 | if (options.GetStopOnError()) { |
2250 | result.AppendErrorWithFormat( |
2251 | "Aborting reading of commands after command #%" PRIu64"l" "u" |
2252 | ": '%s' failed with %s", |
2253 | (uint64_t)idx, cmd, error_msg.str().c_str()); |
2254 | result.SetStatus(eReturnStatusFailed); |
2255 | m_debugger.SetAsyncExecution(old_async_execution); |
2256 | return; |
2257 | } else if (options.GetPrintResults()) { |
2258 | result.AppendMessageWithFormat( |
2259 | "Command #%" PRIu64"l" "u" " '%s' failed with %s", (uint64_t)idx + 1, cmd, |
2260 | error_msg.str().c_str()); |
2261 | } |
2262 | } |
2263 | |
2264 | if (result.GetImmediateOutputStream()) |
2265 | result.GetImmediateOutputStream()->Flush(); |
2266 | |
2267 | if (result.GetImmediateErrorStream()) |
2268 | result.GetImmediateErrorStream()->Flush(); |
2269 | |
2270 | // N.B. Can't depend on DidChangeProcessState, because the state coming |
2271 | // into the command execution could be running (for instance in Breakpoint |
2272 | // Commands. So we check the return value to see if it is has running in |
2273 | // it. |
2274 | if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) || |
2275 | (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) { |
2276 | if (options.GetStopOnContinue()) { |
2277 | // If we caused the target to proceed, and we're going to stop in that |
2278 | // case, set the status in our real result before returning. This is |
2279 | // an error if the continue was not the last command in the set of |
2280 | // commands to be run. |
2281 | if (idx != num_lines - 1) |
2282 | result.AppendErrorWithFormat( |
2283 | "Aborting reading of commands after command #%" PRIu64"l" "u" |
2284 | ": '%s' continued the target.\n", |
2285 | (uint64_t)idx + 1, cmd); |
2286 | else |
2287 | result.AppendMessageWithFormat("Command #%" PRIu64"l" "u" |
2288 | " '%s' continued the target.\n", |
2289 | (uint64_t)idx + 1, cmd); |
2290 | |
2291 | result.SetStatus(tmp_result.GetStatus()); |
2292 | m_debugger.SetAsyncExecution(old_async_execution); |
2293 | |
2294 | return; |
2295 | } |
2296 | } |
2297 | |
2298 | // Also check for "stop on crash here: |
2299 | bool should_stop = false; |
2300 | if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) { |
2301 | TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget()); |
2302 | if (target_sp) { |
2303 | ProcessSP process_sp(target_sp->GetProcessSP()); |
2304 | if (process_sp) { |
2305 | for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) { |
2306 | StopReason reason = thread_sp->GetStopReason(); |
2307 | if (reason == eStopReasonSignal || reason == eStopReasonException || |
2308 | reason == eStopReasonInstrumentation) { |
2309 | should_stop = true; |
2310 | break; |
2311 | } |
2312 | } |
2313 | } |
2314 | } |
2315 | if (should_stop) { |
2316 | if (idx != num_lines - 1) |
2317 | result.AppendErrorWithFormat( |
2318 | "Aborting reading of commands after command #%" PRIu64"l" "u" |
2319 | ": '%s' stopped with a signal or exception.\n", |
2320 | (uint64_t)idx + 1, cmd); |
2321 | else |
2322 | result.AppendMessageWithFormat( |
2323 | "Command #%" PRIu64"l" "u" " '%s' stopped with a signal or exception.\n", |
2324 | (uint64_t)idx + 1, cmd); |
2325 | |
2326 | result.SetStatus(tmp_result.GetStatus()); |
2327 | m_debugger.SetAsyncExecution(old_async_execution); |
2328 | |
2329 | return; |
2330 | } |
2331 | } |
2332 | } |
2333 | |
2334 | result.SetStatus(eReturnStatusSuccessFinishResult); |
2335 | m_debugger.SetAsyncExecution(old_async_execution); |
2336 | |
2337 | return; |
2338 | } |
2339 | |
2340 | // Make flags that we can pass into the IOHandler so our delegates can do the |
2341 | // right thing |
2342 | enum { |
2343 | eHandleCommandFlagStopOnContinue = (1u << 0), |
2344 | eHandleCommandFlagStopOnError = (1u << 1), |
2345 | eHandleCommandFlagEchoCommand = (1u << 2), |
2346 | eHandleCommandFlagEchoCommentCommand = (1u << 3), |
2347 | eHandleCommandFlagPrintResult = (1u << 4), |
2348 | eHandleCommandFlagStopOnCrash = (1u << 5) |
2349 | }; |
2350 | |
2351 | void CommandInterpreter::HandleCommandsFromFile( |
2352 | FileSpec &cmd_file, ExecutionContext *context, |
2353 | CommandInterpreterRunOptions &options, CommandReturnObject &result) { |
2354 | if (cmd_file.Exists()) { |
2355 | StreamFileSP input_file_sp(new StreamFile()); |
2356 | |
2357 | std::string cmd_file_path = cmd_file.GetPath(); |
2358 | Status error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), |
2359 | File::eOpenOptionRead); |
2360 | |
2361 | if (error.Success()) { |
2362 | Debugger &debugger = GetDebugger(); |
2363 | |
2364 | uint32_t flags = 0; |
2365 | |
2366 | if (options.m_stop_on_continue == eLazyBoolCalculate) { |
2367 | if (m_command_source_flags.empty()) { |
2368 | // Stop on continue by default |
2369 | flags |= eHandleCommandFlagStopOnContinue; |
2370 | } else if (m_command_source_flags.back() & |
2371 | eHandleCommandFlagStopOnContinue) { |
2372 | flags |= eHandleCommandFlagStopOnContinue; |
2373 | } |
2374 | } else if (options.m_stop_on_continue == eLazyBoolYes) { |
2375 | flags |= eHandleCommandFlagStopOnContinue; |
2376 | } |
2377 | |
2378 | if (options.m_stop_on_error == eLazyBoolCalculate) { |
2379 | if (m_command_source_flags.empty()) { |
2380 | if (GetStopCmdSourceOnError()) |
2381 | flags |= eHandleCommandFlagStopOnError; |
2382 | } else if (m_command_source_flags.back() & |
2383 | eHandleCommandFlagStopOnError) { |
2384 | flags |= eHandleCommandFlagStopOnError; |
2385 | } |
2386 | } else if (options.m_stop_on_error == eLazyBoolYes) { |
2387 | flags |= eHandleCommandFlagStopOnError; |
2388 | } |
2389 | |
2390 | // stop-on-crash can only be set, if it is present in all levels of |
2391 | // pushed flag sets. |
2392 | if (options.GetStopOnCrash()) { |
2393 | if (m_command_source_flags.empty()) { |
2394 | flags |= eHandleCommandFlagStopOnCrash; |
2395 | } else if (m_command_source_flags.back() & |
2396 | eHandleCommandFlagStopOnCrash) { |
2397 | flags |= eHandleCommandFlagStopOnCrash; |
2398 | } |
2399 | } |
2400 | |
2401 | if (options.m_echo_commands == eLazyBoolCalculate) { |
2402 | if (m_command_source_flags.empty()) { |
2403 | // Echo command by default |
2404 | flags |= eHandleCommandFlagEchoCommand; |
2405 | } else if (m_command_source_flags.back() & |
2406 | eHandleCommandFlagEchoCommand) { |
2407 | flags |= eHandleCommandFlagEchoCommand; |
2408 | } |
2409 | } else if (options.m_echo_commands == eLazyBoolYes) { |
2410 | flags |= eHandleCommandFlagEchoCommand; |
2411 | } |
2412 | |
2413 | // We will only ever ask for this flag, if we echo commands in general. |
2414 | if (options.m_echo_comment_commands == eLazyBoolCalculate) { |
2415 | if (m_command_source_flags.empty()) { |
2416 | // Echo comments by default |
2417 | flags |= eHandleCommandFlagEchoCommentCommand; |
2418 | } else if (m_command_source_flags.back() & |
2419 | eHandleCommandFlagEchoCommentCommand) { |
2420 | flags |= eHandleCommandFlagEchoCommentCommand; |
2421 | } |
2422 | } else if (options.m_echo_comment_commands == eLazyBoolYes) { |
2423 | flags |= eHandleCommandFlagEchoCommentCommand; |
2424 | } |
2425 | |
2426 | if (options.m_print_results == eLazyBoolCalculate) { |
2427 | if (m_command_source_flags.empty()) { |
2428 | // Print output by default |
2429 | flags |= eHandleCommandFlagPrintResult; |
2430 | } else if (m_command_source_flags.back() & |
2431 | eHandleCommandFlagPrintResult) { |
2432 | flags |= eHandleCommandFlagPrintResult; |
2433 | } |
2434 | } else if (options.m_print_results == eLazyBoolYes) { |
2435 | flags |= eHandleCommandFlagPrintResult; |
2436 | } |
2437 | |
2438 | if (flags & eHandleCommandFlagPrintResult) { |
2439 | debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", |
2440 | cmd_file_path.c_str()); |
2441 | } |
2442 | |
2443 | // Used for inheriting the right settings when "command source" might |
2444 | // have nested "command source" commands |
2445 | lldb::StreamFileSP empty_stream_sp; |
2446 | m_command_source_flags.push_back(flags); |
2447 | IOHandlerSP io_handler_sp(new IOHandlerEditline( |
2448 | debugger, IOHandler::Type::CommandInterpreter, input_file_sp, |
2449 | empty_stream_sp, // Pass in an empty stream so we inherit the top |
2450 | // input reader output stream |
2451 | empty_stream_sp, // Pass in an empty stream so we inherit the top |
2452 | // input reader error stream |
2453 | flags, |
2454 | nullptr, // Pass in NULL for "editline_name" so no history is saved, |
2455 | // or written |
2456 | debugger.GetPrompt(), llvm::StringRef(), |
2457 | false, // Not multi-line |
2458 | debugger.GetUseColor(), 0, *this)); |
2459 | const bool old_async_execution = debugger.GetAsyncExecution(); |
2460 | |
2461 | // Set synchronous execution if we are not stopping on continue |
2462 | if ((flags & eHandleCommandFlagStopOnContinue) == 0) |
2463 | debugger.SetAsyncExecution(false); |
2464 | |
2465 | m_command_source_depth++; |
2466 | |
2467 | debugger.RunIOHandler(io_handler_sp); |
2468 | if (!m_command_source_flags.empty()) |
2469 | m_command_source_flags.pop_back(); |
2470 | m_command_source_depth--; |
2471 | result.SetStatus(eReturnStatusSuccessFinishNoResult); |
2472 | debugger.SetAsyncExecution(old_async_execution); |
2473 | } else { |
2474 | result.AppendErrorWithFormat( |
2475 | "error: an error occurred read file '%s': %s\n", |
2476 | cmd_file_path.c_str(), error.AsCString()); |
2477 | result.SetStatus(eReturnStatusFailed); |
2478 | } |
2479 | |
2480 | } else { |
2481 | result.AppendErrorWithFormat( |
2482 | "Error reading commands from file %s - file not found.\n", |
2483 | cmd_file.GetFilename().AsCString("<Unknown>")); |
2484 | result.SetStatus(eReturnStatusFailed); |
2485 | return; |
2486 | } |
2487 | } |
2488 | |
2489 | ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) { |
2490 | std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex); |
2491 | if (!m_script_interpreter_sp) { |
2492 | if (!can_create) |
2493 | return nullptr; |
2494 | lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage(); |
2495 | m_script_interpreter_sp = |
2496 | PluginManager::GetScriptInterpreterForLanguage(script_lang, *this); |
2497 | } |
2498 | return m_script_interpreter_sp.get(); |
2499 | } |
2500 | |
2501 | bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; } |
2502 | |
2503 | void CommandInterpreter::SetSynchronous(bool value) { |
2504 | m_synchronous_execution = value; |
2505 | } |
2506 | |
2507 | void CommandInterpreter::OutputFormattedHelpText(Stream &strm, |
2508 | llvm::StringRef prefix, |
2509 | llvm::StringRef help_text) { |
2510 | const uint32_t max_columns = m_debugger.GetTerminalWidth(); |
2511 | |
2512 | size_t line_width_max = max_columns - prefix.size(); |
2513 | if (line_width_max < 16) |
2514 | line_width_max = help_text.size() + prefix.size(); |
2515 | |
2516 | strm.IndentMore(prefix.size()); |
2517 | bool prefixed_yet = false; |
2518 | while (!help_text.empty()) { |
2519 | // Prefix the first line, indent subsequent lines to line up |
2520 | if (!prefixed_yet) { |
2521 | strm << prefix; |
2522 | prefixed_yet = true; |
2523 | } else |
2524 | strm.Indent(); |
2525 | |
2526 | // Never print more than the maximum on one line. |
2527 | llvm::StringRef this_line = help_text.substr(0, line_width_max); |
2528 | |
2529 | // Always break on an explicit newline. |
2530 | std::size_t first_newline = this_line.find_first_of("\n"); |
2531 | |
2532 | // Don't break on space/tab unless the text is too long to fit on one line. |
2533 | std::size_t last_space = llvm::StringRef::npos; |
2534 | if (this_line.size() != help_text.size()) |
2535 | last_space = this_line.find_last_of(" \t"); |
2536 | |
2537 | // Break at whichever condition triggered first. |
2538 | this_line = this_line.substr(0, std::min(first_newline, last_space)); |
2539 | strm.PutCString(this_line); |
2540 | strm.EOL(); |
2541 | |
2542 | // Remove whitespace / newlines after breaking. |
2543 | help_text = help_text.drop_front(this_line.size()).ltrim(); |
2544 | } |
2545 | strm.IndentLess(prefix.size()); |
2546 | } |
2547 | |
2548 | void CommandInterpreter::OutputFormattedHelpText(Stream &strm, |
2549 | llvm::StringRef word_text, |
2550 | llvm::StringRef separator, |
2551 | llvm::StringRef help_text, |
2552 | size_t max_word_len) { |
2553 | StreamString prefix_stream; |
2554 | prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(), |
2555 | (int)separator.size(), separator.data()); |
2556 | OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text); |
2557 | } |
2558 | |
2559 | void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text, |
2560 | llvm::StringRef separator, |
2561 | llvm::StringRef help_text, |
2562 | uint32_t max_word_len) { |
2563 | int indent_size = max_word_len + separator.size() + 2; |
2564 | |
2565 | strm.IndentMore(indent_size); |
2566 | |
2567 | StreamString text_strm; |
2568 | text_strm.Printf("%-*s ", (int)max_word_len, word_text.data()); |
2569 | text_strm << separator << " " << help_text; |
2570 | |
2571 | const uint32_t max_columns = m_debugger.GetTerminalWidth(); |
2572 | |
2573 | llvm::StringRef text = text_strm.GetString(); |
2574 | |
2575 | uint32_t chars_left = max_columns; |
2576 | |
2577 | auto nextWordLength = [](llvm::StringRef S) { |
2578 | size_t pos = S.find_first_of(' '); |
2579 | return pos == llvm::StringRef::npos ? S.size() : pos; |
2580 | }; |
2581 | |
2582 | while (!text.empty()) { |
2583 | if (text.front() == '\n' || |
2584 | (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) { |
2585 | strm.EOL(); |
2586 | strm.Indent(); |
2587 | chars_left = max_columns - indent_size; |
2588 | if (text.front() == '\n') |
2589 | text = text.drop_front(); |
2590 | else |
2591 | text = text.ltrim(' '); |
2592 | } else { |
2593 | strm.PutChar(text.front()); |
2594 | --chars_left; |
2595 | text = text.drop_front(); |
2596 | } |
2597 | } |
2598 | |
2599 | strm.EOL(); |
2600 | strm.IndentLess(indent_size); |
2601 | } |
2602 | |
2603 | void CommandInterpreter::FindCommandsForApropos( |
2604 | llvm::StringRef search_word, StringList &commands_found, |
2605 | StringList &commands_help, CommandObject::CommandMap &command_map) { |
2606 | CommandObject::CommandMap::const_iterator pos; |
2607 | |
2608 | for (pos = command_map.begin(); pos != command_map.end(); ++pos) { |
2609 | llvm::StringRef command_name = pos->first; |
2610 | CommandObject *cmd_obj = pos->second.get(); |
2611 | |
2612 | const bool search_short_help = true; |
2613 | const bool search_long_help = false; |
2614 | const bool search_syntax = false; |
2615 | const bool search_options = false; |
2616 | if (command_name.contains_lower(search_word) || |
2617 | cmd_obj->HelpTextContainsWord(search_word, search_short_help, |
2618 | search_long_help, search_syntax, |
2619 | search_options)) { |
2620 | commands_found.AppendString(cmd_obj->GetCommandName()); |
2621 | commands_help.AppendString(cmd_obj->GetHelp()); |
2622 | } |
2623 | |
2624 | if (cmd_obj->IsMultiwordObject()) { |
2625 | CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand(); |
2626 | FindCommandsForApropos(search_word, commands_found, commands_help, |
2627 | cmd_multiword->GetSubcommandDictionary()); |
2628 | } |
2629 | } |
2630 | } |
2631 | |
2632 | void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word, |
2633 | StringList &commands_found, |
2634 | StringList &commands_help, |
2635 | bool search_builtin_commands, |
2636 | bool search_user_commands, |
2637 | bool search_alias_commands) { |
2638 | CommandObject::CommandMap::const_iterator pos; |
2639 | |
2640 | if (search_builtin_commands) |
2641 | FindCommandsForApropos(search_word, commands_found, commands_help, |
2642 | m_command_dict); |
2643 | |
2644 | if (search_user_commands) |
2645 | FindCommandsForApropos(search_word, commands_found, commands_help, |
2646 | m_user_dict); |
2647 | |
2648 | if (search_alias_commands) |
2649 | FindCommandsForApropos(search_word, commands_found, commands_help, |
2650 | m_alias_dict); |
2651 | } |
2652 | |
2653 | void CommandInterpreter::UpdateExecutionContext( |
2654 | ExecutionContext *override_context) { |
2655 | if (override_context != nullptr) { |
2656 | m_exe_ctx_ref = *override_context; |
2657 | } else { |
2658 | const bool adopt_selected = true; |
2659 | m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(), |
2660 | adopt_selected); |
2661 | } |
2662 | } |
2663 | |
2664 | size_t CommandInterpreter::GetProcessOutput() { |
2665 | // The process has stuff waiting for stderr; get it and write it out to the |
2666 | // appropriate place. |
2667 | char stdio_buffer[1024]; |
2668 | size_t len; |
2669 | size_t total_bytes = 0; |
2670 | Status error; |
2671 | TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget()); |
2672 | if (target_sp) { |
2673 | ProcessSP process_sp(target_sp->GetProcessSP()); |
2674 | if (process_sp) { |
2675 | while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer), |
2676 | error)) > 0) { |
2677 | size_t bytes_written = len; |
2678 | m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written); |
2679 | total_bytes += len; |
2680 | } |
2681 | while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer), |
2682 | error)) > 0) { |
2683 | size_t bytes_written = len; |
2684 | m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written); |
2685 | total_bytes += len; |
2686 | } |
2687 | } |
2688 | } |
2689 | return total_bytes; |
2690 | } |
2691 | |
2692 | void CommandInterpreter::StartHandlingCommand() { |
2693 | auto idle_state = CommandHandlingState::eIdle; |
2694 | if (m_command_state.compare_exchange_strong( |
2695 | idle_state, CommandHandlingState::eInProgress)) |
2696 | lldbassert(m_iohandler_nesting_level == 0)lldb_private::lldb_assert(static_cast<bool>(m_iohandler_nesting_level == 0), "m_iohandler_nesting_level == 0", __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 2696); |
2697 | else |
2698 | lldbassert(m_iohandler_nesting_level > 0)lldb_private::lldb_assert(static_cast<bool>(m_iohandler_nesting_level > 0), "m_iohandler_nesting_level > 0", __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 2698); |
2699 | ++m_iohandler_nesting_level; |
2700 | } |
2701 | |
2702 | void CommandInterpreter::FinishHandlingCommand() { |
2703 | lldbassert(m_iohandler_nesting_level > 0)lldb_private::lldb_assert(static_cast<bool>(m_iohandler_nesting_level > 0), "m_iohandler_nesting_level > 0", __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 2703); |
2704 | if (--m_iohandler_nesting_level == 0) { |
2705 | auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle); |
2706 | lldbassert(prev_state != CommandHandlingState::eIdle)lldb_private::lldb_assert(static_cast<bool>(prev_state != CommandHandlingState::eIdle), "prev_state != CommandHandlingState::eIdle" , __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 2706); |
2707 | } |
2708 | } |
2709 | |
2710 | bool CommandInterpreter::InterruptCommand() { |
2711 | auto in_progress = CommandHandlingState::eInProgress; |
2712 | return m_command_state.compare_exchange_strong( |
2713 | in_progress, CommandHandlingState::eInterrupted); |
2714 | } |
2715 | |
2716 | bool CommandInterpreter::WasInterrupted() const { |
2717 | bool was_interrupted = |
2718 | (m_command_state == CommandHandlingState::eInterrupted); |
2719 | lldbassert(!was_interrupted || m_iohandler_nesting_level > 0)lldb_private::lldb_assert(static_cast<bool>(!was_interrupted || m_iohandler_nesting_level > 0), "!was_interrupted || m_iohandler_nesting_level > 0" , __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 2719); |
2720 | return was_interrupted; |
2721 | } |
2722 | |
2723 | void CommandInterpreter::PrintCommandOutput(Stream &stream, |
2724 | llvm::StringRef str) { |
2725 | // Split the output into lines and poll for interrupt requests |
2726 | const char *data = str.data(); |
2727 | size_t size = str.size(); |
2728 | while (size > 0 && !WasInterrupted()) { |
2729 | size_t chunk_size = 0; |
2730 | for (; chunk_size < size; ++chunk_size) { |
2731 | lldbassert(data[chunk_size] != '\0')lldb_private::lldb_assert(static_cast<bool>(data[chunk_size ] != '\0'), "data[chunk_size] != '\\0'", __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 2731); |
2732 | if (data[chunk_size] == '\n') { |
2733 | ++chunk_size; |
2734 | break; |
2735 | } |
2736 | } |
2737 | chunk_size = stream.Write(data, chunk_size); |
2738 | lldbassert(size >= chunk_size)lldb_private::lldb_assert(static_cast<bool>(size >= chunk_size ), "size >= chunk_size", __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 2738); |
2739 | data += chunk_size; |
2740 | size -= chunk_size; |
2741 | } |
2742 | if (size > 0) { |
2743 | stream.Printf("\n... Interrupted.\n"); |
2744 | } |
2745 | } |
2746 | |
2747 | bool CommandInterpreter::EchoCommandNonInteractive( |
2748 | llvm::StringRef line, const Flags &io_handler_flags) const { |
2749 | if (!io_handler_flags.Test(eHandleCommandFlagEchoCommand)) |
2750 | return false; |
2751 | |
2752 | llvm::StringRef command = line.trim(); |
2753 | if (command.empty()) |
2754 | return true; |
2755 | |
2756 | if (command.front() == m_comment_char) |
2757 | return io_handler_flags.Test(eHandleCommandFlagEchoCommentCommand); |
2758 | |
2759 | return true; |
2760 | } |
2761 | |
2762 | void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler, |
2763 | std::string &line) { |
2764 | // If we were interrupted, bail out... |
2765 | if (WasInterrupted()) |
2766 | return; |
2767 | |
2768 | const bool is_interactive = io_handler.GetIsInteractive(); |
2769 | if (is_interactive == false) { |
2770 | // When we are not interactive, don't execute blank lines. This will happen |
2771 | // sourcing a commands file. We don't want blank lines to repeat the |
2772 | // previous command and cause any errors to occur (like redefining an |
2773 | // alias, get an error and stop parsing the commands file). |
2774 | if (line.empty()) |
2775 | return; |
2776 | |
2777 | // When using a non-interactive file handle (like when sourcing commands |
2778 | // from a file) we need to echo the command out so we don't just see the |
2779 | // command output and no command... |
2780 | if (EchoCommandNonInteractive(line, io_handler.GetFlags())) |
2781 | io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(), |
2782 | line.c_str()); |
2783 | } |
2784 | |
2785 | StartHandlingCommand(); |
2786 | |
2787 | lldb_private::CommandReturnObject result; |
2788 | HandleCommand(line.c_str(), eLazyBoolCalculate, result); |
2789 | |
2790 | // Now emit the command output text from the command we just executed |
2791 | if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) { |
2792 | // Display any STDOUT/STDERR _prior_ to emitting the command result text |
2793 | GetProcessOutput(); |
2794 | |
2795 | if (!result.GetImmediateOutputStream()) { |
2796 | llvm::StringRef output = result.GetOutputData(); |
2797 | PrintCommandOutput(*io_handler.GetOutputStreamFile(), output); |
2798 | } |
2799 | |
2800 | // Now emit the command error text from the command we just executed |
2801 | if (!result.GetImmediateErrorStream()) { |
2802 | llvm::StringRef error = result.GetErrorData(); |
2803 | PrintCommandOutput(*io_handler.GetErrorStreamFile(), error); |
2804 | } |
2805 | } |
2806 | |
2807 | FinishHandlingCommand(); |
2808 | |
2809 | switch (result.GetStatus()) { |
2810 | case eReturnStatusInvalid: |
2811 | case eReturnStatusSuccessFinishNoResult: |
2812 | case eReturnStatusSuccessFinishResult: |
2813 | case eReturnStatusStarted: |
2814 | break; |
2815 | |
2816 | case eReturnStatusSuccessContinuingNoResult: |
2817 | case eReturnStatusSuccessContinuingResult: |
2818 | if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue)) |
2819 | io_handler.SetIsDone(true); |
2820 | break; |
2821 | |
2822 | case eReturnStatusFailed: |
2823 | m_num_errors++; |
2824 | if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError)) |
2825 | io_handler.SetIsDone(true); |
2826 | break; |
2827 | |
2828 | case eReturnStatusQuit: |
2829 | m_quit_requested = true; |
2830 | io_handler.SetIsDone(true); |
2831 | break; |
2832 | } |
2833 | |
2834 | // Finally, if we're going to stop on crash, check that here: |
2835 | if (!m_quit_requested && result.GetDidChangeProcessState() && |
2836 | io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) { |
2837 | bool should_stop = false; |
2838 | TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget()); |
2839 | if (target_sp) { |
2840 | ProcessSP process_sp(target_sp->GetProcessSP()); |
2841 | if (process_sp) { |
2842 | for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) { |
2843 | StopReason reason = thread_sp->GetStopReason(); |
2844 | if ((reason == eStopReasonSignal || reason == eStopReasonException || |
2845 | reason == eStopReasonInstrumentation) && |
2846 | !result.GetAbnormalStopWasExpected()) { |
2847 | should_stop = true; |
2848 | break; |
2849 | } |
2850 | } |
2851 | } |
2852 | } |
2853 | if (should_stop) { |
2854 | io_handler.SetIsDone(true); |
2855 | m_stopped_for_crash = true; |
2856 | } |
2857 | } |
2858 | } |
2859 | |
2860 | bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) { |
2861 | ExecutionContext exe_ctx(GetExecutionContext()); |
2862 | Process *process = exe_ctx.GetProcessPtr(); |
2863 | |
2864 | if (InterruptCommand()) |
2865 | return true; |
2866 | |
2867 | if (process) { |
2868 | StateType state = process->GetState(); |
2869 | if (StateIsRunningState(state)) { |
2870 | process->Halt(); |
2871 | return true; // Don't do any updating when we are running |
2872 | } |
2873 | } |
2874 | |
2875 | ScriptInterpreter *script_interpreter = GetScriptInterpreter(false); |
2876 | if (script_interpreter) { |
2877 | if (script_interpreter->Interrupt()) |
2878 | return true; |
2879 | } |
2880 | return false; |
2881 | } |
2882 | |
2883 | void CommandInterpreter::GetLLDBCommandsFromIOHandler( |
2884 | const char *prompt, IOHandlerDelegate &delegate, bool asynchronously, |
2885 | void *baton) { |
2886 | Debugger &debugger = GetDebugger(); |
2887 | IOHandlerSP io_handler_sp( |
2888 | new IOHandlerEditline(debugger, IOHandler::Type::CommandList, |
2889 | "lldb", // Name of input reader for history |
2890 | llvm::StringRef::withNullAsEmpty(prompt), // Prompt |
2891 | llvm::StringRef(), // Continuation prompt |
2892 | true, // Get multiple lines |
2893 | debugger.GetUseColor(), |
2894 | 0, // Don't show line numbers |
2895 | delegate)); // IOHandlerDelegate |
2896 | |
2897 | if (io_handler_sp) { |
2898 | io_handler_sp->SetUserData(baton); |
2899 | if (asynchronously) |
2900 | debugger.PushIOHandler(io_handler_sp); |
2901 | else |
2902 | debugger.RunIOHandler(io_handler_sp); |
2903 | } |
2904 | } |
2905 | |
2906 | void CommandInterpreter::GetPythonCommandsFromIOHandler( |
2907 | const char *prompt, IOHandlerDelegate &delegate, bool asynchronously, |
2908 | void *baton) { |
2909 | Debugger &debugger = GetDebugger(); |
2910 | IOHandlerSP io_handler_sp( |
2911 | new IOHandlerEditline(debugger, IOHandler::Type::PythonCode, |
2912 | "lldb-python", // Name of input reader for history |
2913 | llvm::StringRef::withNullAsEmpty(prompt), // Prompt |
2914 | llvm::StringRef(), // Continuation prompt |
2915 | true, // Get multiple lines |
2916 | debugger.GetUseColor(), |
2917 | 0, // Don't show line numbers |
2918 | delegate)); // IOHandlerDelegate |
2919 | |
2920 | if (io_handler_sp) { |
2921 | io_handler_sp->SetUserData(baton); |
2922 | if (asynchronously) |
2923 | debugger.PushIOHandler(io_handler_sp); |
2924 | else |
2925 | debugger.RunIOHandler(io_handler_sp); |
2926 | } |
2927 | } |
2928 | |
2929 | bool CommandInterpreter::IsActive() { |
2930 | return m_debugger.IsTopIOHandler(m_command_io_handler_sp); |
2931 | } |
2932 | |
2933 | lldb::IOHandlerSP |
2934 | CommandInterpreter::GetIOHandler(bool force_create, |
2935 | CommandInterpreterRunOptions *options) { |
2936 | // Always re-create the IOHandlerEditline in case the input changed. The old |
2937 | // instance might have had a non-interactive input and now it does or vice |
2938 | // versa. |
2939 | if (force_create || !m_command_io_handler_sp) { |
2940 | // Always re-create the IOHandlerEditline in case the input changed. The |
2941 | // old instance might have had a non-interactive input and now it does or |
2942 | // vice versa. |
2943 | uint32_t flags = 0; |
2944 | |
2945 | if (options) { |
2946 | if (options->m_stop_on_continue == eLazyBoolYes) |
2947 | flags |= eHandleCommandFlagStopOnContinue; |
2948 | if (options->m_stop_on_error == eLazyBoolYes) |
2949 | flags |= eHandleCommandFlagStopOnError; |
2950 | if (options->m_stop_on_crash == eLazyBoolYes) |
2951 | flags |= eHandleCommandFlagStopOnCrash; |
2952 | if (options->m_echo_commands != eLazyBoolNo) |
2953 | flags |= eHandleCommandFlagEchoCommand; |
2954 | if (options->m_echo_comment_commands != eLazyBoolNo) |
2955 | flags |= eHandleCommandFlagEchoCommentCommand; |
2956 | if (options->m_print_results != eLazyBoolNo) |
2957 | flags |= eHandleCommandFlagPrintResult; |
2958 | } else { |
2959 | flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult; |
2960 | } |
2961 | |
2962 | m_command_io_handler_sp.reset(new IOHandlerEditline( |
2963 | m_debugger, IOHandler::Type::CommandInterpreter, |
2964 | m_debugger.GetInputFile(), m_debugger.GetOutputFile(), |
2965 | m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(), |
2966 | llvm::StringRef(), // Continuation prompt |
2967 | false, // Don't enable multiple line input, just single line commands |
2968 | m_debugger.GetUseColor(), |
2969 | 0, // Don't show line numbers |
2970 | *this)); |
2971 | } |
2972 | return m_command_io_handler_sp; |
2973 | } |
2974 | |
2975 | void CommandInterpreter::RunCommandInterpreter( |
2976 | bool auto_handle_events, bool spawn_thread, |
2977 | CommandInterpreterRunOptions &options) { |
2978 | // Always re-create the command interpreter when we run it in case any file |
2979 | // handles have changed. |
2980 | bool force_create = true; |
2981 | m_debugger.PushIOHandler(GetIOHandler(force_create, &options)); |
2982 | m_stopped_for_crash = false; |
2983 | |
2984 | if (auto_handle_events) |
2985 | m_debugger.StartEventHandlerThread(); |
2986 | |
2987 | if (spawn_thread) { |
2988 | m_debugger.StartIOHandlerThread(); |
2989 | } else { |
2990 | m_debugger.ExecuteIOHandlers(); |
2991 | |
2992 | if (auto_handle_events) |
2993 | m_debugger.StopEventHandlerThread(); |
2994 | } |
2995 | } |
2996 | |
2997 | CommandObject * |
2998 | CommandInterpreter::ResolveCommandImpl(std::string &command_line, |
2999 | CommandReturnObject &result) { |
3000 | std::string scratch_command(command_line); // working copy so we don't modify |
3001 | // command_line unless we succeed |
3002 | CommandObject *cmd_obj = nullptr; |
3003 | StreamString revised_command_line; |
3004 | bool wants_raw_input = false; |
3005 | size_t actual_cmd_name_len = 0; |
3006 | std::string next_word; |
3007 | StringList matches; |
3008 | bool done = false; |
3009 | while (!done) { |
3010 | char quote_char = '\0'; |
3011 | std::string suffix; |
3012 | ExtractCommand(scratch_command, next_word, suffix, quote_char); |
3013 | if (cmd_obj == nullptr) { |
3014 | std::string full_name; |
3015 | bool is_alias = GetAliasFullName(next_word, full_name); |
3016 | cmd_obj = GetCommandObject(next_word, &matches); |
3017 | bool is_real_command = |
3018 | (is_alias == false) || |
3019 | (cmd_obj != nullptr && cmd_obj->IsAlias() == false); |
3020 | if (!is_real_command) { |
3021 | matches.Clear(); |
3022 | std::string alias_result; |
3023 | cmd_obj = |
3024 | BuildAliasResult(full_name, scratch_command, alias_result, result); |
3025 | revised_command_line.Printf("%s", alias_result.c_str()); |
3026 | if (cmd_obj) { |
3027 | wants_raw_input = cmd_obj->WantsRawCommandString(); |
3028 | actual_cmd_name_len = cmd_obj->GetCommandName().size(); |
3029 | } |
3030 | } else { |
3031 | if (cmd_obj) { |
3032 | llvm::StringRef cmd_name = cmd_obj->GetCommandName(); |
3033 | actual_cmd_name_len += cmd_name.size(); |
3034 | revised_command_line.Printf("%s", cmd_name.str().c_str()); |
3035 | wants_raw_input = cmd_obj->WantsRawCommandString(); |
3036 | } else { |
3037 | revised_command_line.Printf("%s", next_word.c_str()); |
3038 | } |
3039 | } |
3040 | } else { |
3041 | if (cmd_obj->IsMultiwordObject()) { |
3042 | CommandObject *sub_cmd_obj = |
3043 | cmd_obj->GetSubcommandObject(next_word.c_str()); |
3044 | if (sub_cmd_obj) { |
3045 | // The subcommand's name includes the parent command's name, so |
3046 | // restart rather than append to the revised_command_line. |
3047 | llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName(); |
3048 | actual_cmd_name_len = sub_cmd_name.size() + 1; |
3049 | revised_command_line.Clear(); |
3050 | revised_command_line.Printf("%s", sub_cmd_name.str().c_str()); |
3051 | cmd_obj = sub_cmd_obj; |
3052 | wants_raw_input = cmd_obj->WantsRawCommandString(); |
3053 | } else { |
3054 | if (quote_char) |
3055 | revised_command_line.Printf(" %c%s%s%c", quote_char, |
3056 | next_word.c_str(), suffix.c_str(), |
3057 | quote_char); |
3058 | else |
3059 | revised_command_line.Printf(" %s%s", next_word.c_str(), |
3060 | suffix.c_str()); |
3061 | done = true; |
3062 | } |
3063 | } else { |
3064 | if (quote_char) |
3065 | revised_command_line.Printf(" %c%s%s%c", quote_char, |
3066 | next_word.c_str(), suffix.c_str(), |
3067 | quote_char); |
3068 | else |
3069 | revised_command_line.Printf(" %s%s", next_word.c_str(), |
3070 | suffix.c_str()); |
3071 | done = true; |
3072 | } |
3073 | } |
3074 | |
3075 | if (cmd_obj == nullptr) { |
3076 | const size_t num_matches = matches.GetSize(); |
3077 | if (matches.GetSize() > 1) { |
3078 | StreamString error_msg; |
3079 | error_msg.Printf("Ambiguous command '%s'. Possible matches:\n", |
3080 | next_word.c_str()); |
3081 | |
3082 | for (uint32_t i = 0; i < num_matches; ++i) { |
3083 | error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i)); |
3084 | } |
3085 | result.AppendRawError(error_msg.GetString()); |
3086 | } else { |
3087 | // We didn't have only one match, otherwise we wouldn't get here. |
3088 | lldbassert(num_matches == 0)lldb_private::lldb_assert(static_cast<bool>(num_matches == 0), "num_matches == 0", __FUNCTION__, "/build/llvm-toolchain-snapshot-8~svn345461/tools/lldb/source/Interpreter/CommandInterpreter.cpp" , 3088); |
3089 | result.AppendErrorWithFormat("'%s' is not a valid command.\n", |
3090 | next_word.c_str()); |
3091 | } |
3092 | result.SetStatus(eReturnStatusFailed); |
3093 | return nullptr; |
3094 | } |
3095 | |
3096 | if (cmd_obj->IsMultiwordObject()) { |
3097 | if (!suffix.empty()) { |
3098 | result.AppendErrorWithFormat( |
3099 | "command '%s' did not recognize '%s%s%s' as valid (subcommand " |
3100 | "might be invalid).\n", |
3101 | cmd_obj->GetCommandName().str().c_str(), |
3102 | next_word.empty() ? "" : next_word.c_str(), |
3103 | next_word.empty() ? " -- " : " ", suffix.c_str()); |
3104 | result.SetStatus(eReturnStatusFailed); |
3105 | return nullptr; |
3106 | } |
3107 | } else { |
3108 | // If we found a normal command, we are done |
3109 | done = true; |
3110 | if (!suffix.empty()) { |
3111 | switch (suffix[0]) { |
3112 | case '/': |
3113 | // GDB format suffixes |
3114 | { |
3115 | Options *command_options = cmd_obj->GetOptions(); |
3116 | if (command_options && |
3117 | command_options->SupportsLongOption("gdb-format")) { |
3118 | std::string gdb_format_option("--gdb-format="); |
3119 | gdb_format_option += (suffix.c_str() + 1); |
3120 | |
3121 | std::string cmd = revised_command_line.GetString(); |
3122 | size_t arg_terminator_idx = FindArgumentTerminator(cmd); |
3123 | if (arg_terminator_idx != std::string::npos) { |
3124 | // Insert the gdb format option before the "--" that terminates |
3125 | // options |
3126 | gdb_format_option.append(1, ' '); |
3127 | cmd.insert(arg_terminator_idx, gdb_format_option); |
3128 | revised_command_line.Clear(); |
3129 | revised_command_line.PutCString(cmd); |
3130 | } else |
3131 | revised_command_line.Printf(" %s", gdb_format_option.c_str()); |
3132 | |
3133 | if (wants_raw_input && |
3134 | FindArgumentTerminator(cmd) == std::string::npos) |
3135 | revised_command_line.PutCString(" --"); |
3136 | } else { |
3137 | result.AppendErrorWithFormat( |
3138 | "the '%s' command doesn't support the --gdb-format option\n", |
3139 | cmd_obj->GetCommandName().str().c_str()); |
3140 | result.SetStatus(eReturnStatusFailed); |
3141 | return nullptr; |
3142 | } |
3143 | } |
3144 | break; |
3145 | |
3146 | default: |
3147 | result.AppendErrorWithFormat( |
3148 | "unknown command shorthand suffix: '%s'\n", suffix.c_str()); |
3149 | result.SetStatus(eReturnStatusFailed); |
3150 | return nullptr; |
3151 | } |
3152 | } |
3153 | } |
3154 | if (scratch_command.empty()) |
3155 | done = true; |
3156 | } |
3157 | |
3158 | if (!scratch_command.empty()) |
3159 | revised_command_line.Printf(" %s", scratch_command.c_str()); |
3160 | |
3161 | if (cmd_obj != NULL__null) |
3162 | command_line = revised_command_line.GetString(); |
3163 | |
3164 | return cmd_obj; |
3165 | } |