1//===-- CommandInterpreter.cpp --------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include <chrono>
10#include <cstdlib>
11#include <limits>
12#include <memory>
13#include <optional>
14#include <string>
15#include <vector>
16
17#include "Commands/CommandObjectApropos.h"
18#include "Commands/CommandObjectBreakpoint.h"
19#include "Commands/CommandObjectCommands.h"
20#include "Commands/CommandObjectDWIMPrint.h"
21#include "Commands/CommandObjectDiagnostics.h"
22#include "Commands/CommandObjectDisassemble.h"
23#include "Commands/CommandObjectExpression.h"
24#include "Commands/CommandObjectFrame.h"
25#include "Commands/CommandObjectGUI.h"
26#include "Commands/CommandObjectHelp.h"
27#include "Commands/CommandObjectLanguage.h"
28#include "Commands/CommandObjectLog.h"
29#include "Commands/CommandObjectMemory.h"
30#include "Commands/CommandObjectPlatform.h"
31#include "Commands/CommandObjectPlugin.h"
32#include "Commands/CommandObjectProcess.h"
33#include "Commands/CommandObjectProtocolServer.h"
34#include "Commands/CommandObjectQuit.h"
35#include "Commands/CommandObjectRegexCommand.h"
36#include "Commands/CommandObjectRegister.h"
37#include "Commands/CommandObjectScripting.h"
38#include "Commands/CommandObjectSession.h"
39#include "Commands/CommandObjectSettings.h"
40#include "Commands/CommandObjectSource.h"
41#include "Commands/CommandObjectStats.h"
42#include "Commands/CommandObjectTarget.h"
43#include "Commands/CommandObjectThread.h"
44#include "Commands/CommandObjectTrace.h"
45#include "Commands/CommandObjectType.h"
46#include "Commands/CommandObjectVersion.h"
47#include "Commands/CommandObjectWatchpoint.h"
48
49#include "lldb/Core/Debugger.h"
50#include "lldb/Core/Module.h"
51#include "lldb/Core/PluginManager.h"
52#include "lldb/Core/Telemetry.h"
53#include "lldb/Host/StreamFile.h"
54#include "lldb/Utility/ErrorMessages.h"
55#include "lldb/Utility/LLDBLog.h"
56#include "lldb/Utility/Log.h"
57#include "lldb/Utility/State.h"
58#include "lldb/Utility/Stream.h"
59#include "lldb/Utility/StructuredData.h"
60#include "lldb/Utility/Timer.h"
61
62#include "lldb/Host/Config.h"
63#include "lldb/lldb-forward.h"
64#if LLDB_ENABLE_LIBEDIT
65#include "lldb/Host/Editline.h"
66#endif
67#include "lldb/Host/File.h"
68#include "lldb/Host/FileCache.h"
69#include "lldb/Host/Host.h"
70#include "lldb/Host/HostInfo.h"
71
72#include "lldb/Interpreter/CommandCompletions.h"
73#include "lldb/Interpreter/CommandInterpreter.h"
74#include "lldb/Interpreter/CommandReturnObject.h"
75#include "lldb/Interpreter/OptionValueProperties.h"
76#include "lldb/Interpreter/Options.h"
77#include "lldb/Interpreter/Property.h"
78#include "lldb/Utility/Args.h"
79
80#include "lldb/Target/Language.h"
81#include "lldb/Target/Process.h"
82#include "lldb/Target/StopInfo.h"
83#include "lldb/Target/TargetList.h"
84#include "lldb/Target/Thread.h"
85#include "lldb/Target/UnixSignals.h"
86
87#include "llvm/ADT/STLExtras.h"
88#include "llvm/ADT/ScopeExit.h"
89#include "llvm/ADT/SmallString.h"
90#include "llvm/Support/FormatAdapters.h"
91#include "llvm/Support/Path.h"
92#include "llvm/Support/PrettyStackTrace.h"
93#include "llvm/Support/ScopedPrinter.h"
94#include "llvm/Telemetry/Telemetry.h"
95
96#if defined(__APPLE__)
97#include <TargetConditionals.h>
98#endif
99
100using namespace lldb;
101using namespace lldb_private;
102
103static const char *k_white_space = " \t\v";
104
105static constexpr const char *InitFileWarning =
106 "There is a .lldbinit file in the current directory which is not being "
107 "read.\n"
108 "To silence this warning without sourcing in the local .lldbinit,\n"
109 "add the following to the lldbinit file in your home directory:\n"
110 " settings set target.load-cwd-lldbinit false\n"
111 "To allow lldb to source .lldbinit files in the current working "
112 "directory,\n"
113 "set the value of this variable to true. Only do so if you understand "
114 "and\n"
115 "accept the security risk.";
116
117const char *CommandInterpreter::g_no_argument = "<no-argument>";
118const char *CommandInterpreter::g_need_argument = "<need-argument>";
119const char *CommandInterpreter::g_argument = "<argument>";
120
121#define LLDB_PROPERTIES_interpreter
122#include "InterpreterProperties.inc"
123
124enum {
125#define LLDB_PROPERTIES_interpreter
126#include "InterpreterPropertiesEnum.inc"
127};
128
129llvm::StringRef CommandInterpreter::GetStaticBroadcasterClass() {
130 static constexpr llvm::StringLiteral class_name("lldb.commandInterpreter");
131 return class_name;
132}
133
134CommandInterpreter::CommandInterpreter(Debugger &debugger,
135 bool synchronous_execution)
136 : Broadcaster(debugger.GetBroadcasterManager(),
137 CommandInterpreter::GetStaticBroadcasterClass().str()),
138 Properties(
139 OptionValuePropertiesSP(new OptionValueProperties("interpreter"))),
140 IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand),
141 m_debugger(debugger), m_synchronous_execution(true),
142 m_skip_lldbinit_files(false), m_skip_app_init_files(false),
143 m_comment_char('#'), m_batch_command_mode(false),
144 m_truncation_warning(eNoOmission), m_max_depth_warning(eNoOmission),
145 m_command_source_depth(0) {
146 SetEventName(event_mask: eBroadcastBitThreadShouldExit, name: "thread-should-exit");
147 SetEventName(event_mask: eBroadcastBitResetPrompt, name: "reset-prompt");
148 SetEventName(event_mask: eBroadcastBitQuitCommandReceived, name: "quit");
149 SetSynchronous(synchronous_execution);
150 CheckInWithManager();
151 m_collection_sp->Initialize(setting_definitions: g_interpreter_properties);
152}
153
154bool CommandInterpreter::GetExpandRegexAliases() const {
155 const uint32_t idx = ePropertyExpandRegexAliases;
156 return GetPropertyAtIndexAs<bool>(
157 idx, default_value: g_interpreter_properties[idx].default_uint_value != 0);
158}
159
160bool CommandInterpreter::GetPromptOnQuit() const {
161 const uint32_t idx = ePropertyPromptOnQuit;
162 return GetPropertyAtIndexAs<bool>(
163 idx, default_value: g_interpreter_properties[idx].default_uint_value != 0);
164}
165
166void CommandInterpreter::SetPromptOnQuit(bool enable) {
167 const uint32_t idx = ePropertyPromptOnQuit;
168 SetPropertyAtIndex(idx, t: enable);
169}
170
171bool CommandInterpreter::GetSaveTranscript() const {
172 const uint32_t idx = ePropertySaveTranscript;
173 return GetPropertyAtIndexAs<bool>(
174 idx, default_value: g_interpreter_properties[idx].default_uint_value != 0);
175}
176
177void CommandInterpreter::SetSaveTranscript(bool enable) {
178 const uint32_t idx = ePropertySaveTranscript;
179 SetPropertyAtIndex(idx, t: enable);
180}
181
182bool CommandInterpreter::GetSaveSessionOnQuit() const {
183 const uint32_t idx = ePropertySaveSessionOnQuit;
184 return GetPropertyAtIndexAs<bool>(
185 idx, default_value: g_interpreter_properties[idx].default_uint_value != 0);
186}
187
188void CommandInterpreter::SetSaveSessionOnQuit(bool enable) {
189 const uint32_t idx = ePropertySaveSessionOnQuit;
190 SetPropertyAtIndex(idx, t: enable);
191}
192
193bool CommandInterpreter::GetOpenTranscriptInEditor() const {
194 const uint32_t idx = ePropertyOpenTranscriptInEditor;
195 return GetPropertyAtIndexAs<bool>(
196 idx, default_value: g_interpreter_properties[idx].default_uint_value != 0);
197}
198
199void CommandInterpreter::SetOpenTranscriptInEditor(bool enable) {
200 const uint32_t idx = ePropertyOpenTranscriptInEditor;
201 SetPropertyAtIndex(idx, t: enable);
202}
203
204FileSpec CommandInterpreter::GetSaveSessionDirectory() const {
205 const uint32_t idx = ePropertySaveSessionDirectory;
206 return GetPropertyAtIndexAs<FileSpec>(idx, default_value: {});
207}
208
209void CommandInterpreter::SetSaveSessionDirectory(llvm::StringRef path) {
210 const uint32_t idx = ePropertySaveSessionDirectory;
211 SetPropertyAtIndex(idx, t: path);
212}
213
214bool CommandInterpreter::GetEchoCommands() const {
215 const uint32_t idx = ePropertyEchoCommands;
216 return GetPropertyAtIndexAs<bool>(
217 idx, default_value: g_interpreter_properties[idx].default_uint_value != 0);
218}
219
220void CommandInterpreter::SetEchoCommands(bool enable) {
221 const uint32_t idx = ePropertyEchoCommands;
222 SetPropertyAtIndex(idx, t: enable);
223}
224
225bool CommandInterpreter::GetEchoCommentCommands() const {
226 const uint32_t idx = ePropertyEchoCommentCommands;
227 return GetPropertyAtIndexAs<bool>(
228 idx, default_value: g_interpreter_properties[idx].default_uint_value != 0);
229}
230
231void CommandInterpreter::SetEchoCommentCommands(bool enable) {
232 const uint32_t idx = ePropertyEchoCommentCommands;
233 SetPropertyAtIndex(idx, t: enable);
234}
235
236void CommandInterpreter::AllowExitCodeOnQuit(bool allow) {
237 m_allow_exit_code = allow;
238 if (!allow)
239 m_quit_exit_code.reset();
240}
241
242bool CommandInterpreter::SetQuitExitCode(int exit_code) {
243 if (!m_allow_exit_code)
244 return false;
245 m_quit_exit_code = exit_code;
246 return true;
247}
248
249int CommandInterpreter::GetQuitExitCode(bool &exited) const {
250 exited = m_quit_exit_code.has_value();
251 if (exited)
252 return *m_quit_exit_code;
253 return 0;
254}
255
256void CommandInterpreter::ResolveCommand(const char *command_line,
257 CommandReturnObject &result) {
258 std::string command = command_line;
259 if (ResolveCommandImpl(command_line&: command, result) != nullptr) {
260 result.AppendMessageWithFormat(format: "%s", command.c_str());
261 result.SetStatus(eReturnStatusSuccessFinishResult);
262 }
263}
264
265bool CommandInterpreter::GetStopCmdSourceOnError() const {
266 const uint32_t idx = ePropertyStopCmdSourceOnError;
267 return GetPropertyAtIndexAs<bool>(
268 idx, default_value: g_interpreter_properties[idx].default_uint_value != 0);
269}
270
271bool CommandInterpreter::GetSpaceReplPrompts() const {
272 const uint32_t idx = ePropertySpaceReplPrompts;
273 return GetPropertyAtIndexAs<bool>(
274 idx, default_value: g_interpreter_properties[idx].default_uint_value != 0);
275}
276
277bool CommandInterpreter::GetRepeatPreviousCommand() const {
278 const uint32_t idx = ePropertyRepeatPreviousCommand;
279 return GetPropertyAtIndexAs<bool>(
280 idx, default_value: g_interpreter_properties[idx].default_uint_value != 0);
281}
282
283bool CommandInterpreter::GetRequireCommandOverwrite() const {
284 const uint32_t idx = ePropertyRequireCommandOverwrite;
285 return GetPropertyAtIndexAs<bool>(
286 idx, default_value: g_interpreter_properties[idx].default_uint_value != 0);
287}
288
289void CommandInterpreter::Initialize() {
290 LLDB_SCOPED_TIMER();
291
292 LoadCommandDictionary();
293
294 // An alias arguments vector to reuse - reset it before use...
295 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
296
297 // Set up some initial aliases.
298 CommandObjectSP cmd_obj_sp = GetCommandSPExact(cmd: "quit");
299 if (cmd_obj_sp) {
300 AddAlias(alias_name: "q", command_obj_sp&: cmd_obj_sp);
301 AddAlias(alias_name: "exit", command_obj_sp&: cmd_obj_sp);
302 }
303
304 cmd_obj_sp = GetCommandSPExact(cmd: "_regexp-attach");
305 if (cmd_obj_sp)
306 AddAlias(alias_name: "attach", command_obj_sp&: cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
307
308 cmd_obj_sp = GetCommandSPExact(cmd: "process detach");
309 if (cmd_obj_sp) {
310 AddAlias(alias_name: "detach", command_obj_sp&: cmd_obj_sp);
311 }
312
313 cmd_obj_sp = GetCommandSPExact(cmd: "process continue");
314 if (cmd_obj_sp) {
315 AddAlias(alias_name: "c", command_obj_sp&: cmd_obj_sp);
316 AddAlias(alias_name: "continue", command_obj_sp&: cmd_obj_sp);
317 }
318
319 cmd_obj_sp = GetCommandSPExact(cmd: "_regexp-break");
320 if (cmd_obj_sp)
321 AddAlias(alias_name: "b", command_obj_sp&: cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
322
323 cmd_obj_sp = GetCommandSPExact(cmd: "_regexp-tbreak");
324 if (cmd_obj_sp)
325 AddAlias(alias_name: "tbreak", command_obj_sp&: cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
326
327 cmd_obj_sp = GetCommandSPExact(cmd: "thread step-inst");
328 if (cmd_obj_sp) {
329 AddAlias(alias_name: "stepi", command_obj_sp&: cmd_obj_sp);
330 AddAlias(alias_name: "si", command_obj_sp&: cmd_obj_sp);
331 }
332
333 cmd_obj_sp = GetCommandSPExact(cmd: "thread step-inst-over");
334 if (cmd_obj_sp) {
335 AddAlias(alias_name: "nexti", command_obj_sp&: cmd_obj_sp);
336 AddAlias(alias_name: "ni", command_obj_sp&: cmd_obj_sp);
337 }
338
339 cmd_obj_sp = GetCommandSPExact(cmd: "thread step-in");
340 if (cmd_obj_sp) {
341 AddAlias(alias_name: "s", command_obj_sp&: cmd_obj_sp);
342 AddAlias(alias_name: "step", command_obj_sp&: cmd_obj_sp);
343 CommandAlias *sif_alias = AddAlias(
344 alias_name: "sif", command_obj_sp&: cmd_obj_sp, args_string: "--end-linenumber block --step-in-target %1");
345 if (sif_alias) {
346 sif_alias->SetHelp("Step through the current block, stopping if you step "
347 "directly into a function whose name matches the "
348 "TargetFunctionName.");
349 sif_alias->SetSyntax("sif <TargetFunctionName>");
350 }
351 }
352
353 cmd_obj_sp = GetCommandSPExact(cmd: "thread step-over");
354 if (cmd_obj_sp) {
355 AddAlias(alias_name: "n", command_obj_sp&: cmd_obj_sp);
356 AddAlias(alias_name: "next", command_obj_sp&: cmd_obj_sp);
357 }
358
359 cmd_obj_sp = GetCommandSPExact(cmd: "thread step-out");
360 if (cmd_obj_sp) {
361 AddAlias(alias_name: "finish", command_obj_sp&: cmd_obj_sp);
362 }
363
364 cmd_obj_sp = GetCommandSPExact(cmd: "frame select");
365 if (cmd_obj_sp) {
366 AddAlias(alias_name: "f", command_obj_sp&: cmd_obj_sp);
367 }
368
369 cmd_obj_sp = GetCommandSPExact(cmd: "thread select");
370 if (cmd_obj_sp) {
371 AddAlias(alias_name: "t", command_obj_sp&: cmd_obj_sp);
372 }
373
374 cmd_obj_sp = GetCommandSPExact(cmd: "_regexp-jump");
375 if (cmd_obj_sp) {
376 AddAlias(alias_name: "j", command_obj_sp&: cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
377 AddAlias(alias_name: "jump", command_obj_sp&: cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
378 }
379
380 cmd_obj_sp = GetCommandSPExact(cmd: "_regexp-list");
381 if (cmd_obj_sp) {
382 AddAlias(alias_name: "l", command_obj_sp&: cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
383 AddAlias(alias_name: "list", command_obj_sp&: cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
384 }
385
386 cmd_obj_sp = GetCommandSPExact(cmd: "_regexp-env");
387 if (cmd_obj_sp)
388 AddAlias(alias_name: "env", command_obj_sp&: cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
389
390 cmd_obj_sp = GetCommandSPExact(cmd: "memory read");
391 if (cmd_obj_sp)
392 AddAlias(alias_name: "x", command_obj_sp&: cmd_obj_sp);
393
394 cmd_obj_sp = GetCommandSPExact(cmd: "_regexp-up");
395 if (cmd_obj_sp)
396 AddAlias(alias_name: "up", command_obj_sp&: cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
397
398 cmd_obj_sp = GetCommandSPExact(cmd: "_regexp-down");
399 if (cmd_obj_sp)
400 AddAlias(alias_name: "down", command_obj_sp&: cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
401
402 cmd_obj_sp = GetCommandSPExact(cmd: "_regexp-display");
403 if (cmd_obj_sp)
404 AddAlias(alias_name: "display", command_obj_sp&: cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
405
406 cmd_obj_sp = GetCommandSPExact(cmd: "disassemble");
407 if (cmd_obj_sp)
408 AddAlias(alias_name: "dis", command_obj_sp&: cmd_obj_sp);
409
410 cmd_obj_sp = GetCommandSPExact(cmd: "disassemble");
411 if (cmd_obj_sp)
412 AddAlias(alias_name: "di", command_obj_sp&: cmd_obj_sp);
413
414 cmd_obj_sp = GetCommandSPExact(cmd: "_regexp-undisplay");
415 if (cmd_obj_sp)
416 AddAlias(alias_name: "undisplay", command_obj_sp&: cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
417
418 cmd_obj_sp = GetCommandSPExact(cmd: "_regexp-bt");
419 if (cmd_obj_sp)
420 AddAlias(alias_name: "bt", command_obj_sp&: cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
421
422 cmd_obj_sp = GetCommandSPExact(cmd: "target create");
423 if (cmd_obj_sp)
424 AddAlias(alias_name: "file", command_obj_sp&: cmd_obj_sp);
425
426 cmd_obj_sp = GetCommandSPExact(cmd: "target modules");
427 if (cmd_obj_sp)
428 AddAlias(alias_name: "image", command_obj_sp&: cmd_obj_sp);
429
430 alias_arguments_vector_sp = std::make_shared<OptionArgVector>();
431
432 cmd_obj_sp = GetCommandSPExact(cmd: "dwim-print");
433 if (cmd_obj_sp) {
434 AddAlias(alias_name: "p", command_obj_sp&: cmd_obj_sp, args_string: "--")->SetHelpLong("");
435 AddAlias(alias_name: "print", command_obj_sp&: cmd_obj_sp, args_string: "--")->SetHelpLong("");
436 if (auto *po = AddAlias(alias_name: "po", command_obj_sp&: cmd_obj_sp, args_string: "-O --")) {
437 po->SetHelp("Evaluate an expression on the current thread. Displays any "
438 "returned value with formatting "
439 "controlled by the type's author.");
440 po->SetHelpLong("");
441 }
442 }
443
444 cmd_obj_sp = GetCommandSPExact(cmd: "expression");
445 if (cmd_obj_sp) {
446 // Ensure `e` runs `expression`.
447 AddAlias(alias_name: "e", command_obj_sp&: cmd_obj_sp);
448 AddAlias(alias_name: "call", command_obj_sp&: cmd_obj_sp, args_string: "--")->SetHelpLong("");
449 CommandAlias *parray_alias =
450 AddAlias(alias_name: "parray", command_obj_sp&: cmd_obj_sp, args_string: "--element-count %1 --");
451 if (parray_alias) {
452 parray_alias->SetHelp(
453 "parray <COUNT> <EXPRESSION> -- lldb will evaluate EXPRESSION "
454 "to get a typed-pointer-to-an-array in memory, and will display "
455 "COUNT elements of that type from the array.");
456 parray_alias->SetHelpLong("");
457 }
458 CommandAlias *poarray_alias = AddAlias(
459 alias_name: "poarray", command_obj_sp&: cmd_obj_sp, args_string: "--object-description --element-count %1 --");
460 if (poarray_alias) {
461 poarray_alias->SetHelp(
462 "poarray <COUNT> <EXPRESSION> -- lldb will "
463 "evaluate EXPRESSION to get the address of an array of COUNT "
464 "objects in memory, and will call po on them.");
465 poarray_alias->SetHelpLong("");
466 }
467 }
468
469 cmd_obj_sp = GetCommandSPExact(cmd: "platform shell");
470 if (cmd_obj_sp) {
471 CommandAlias *shell_alias = AddAlias(alias_name: "shell", command_obj_sp&: cmd_obj_sp, args_string: " --host --");
472 if (shell_alias) {
473 shell_alias->SetHelp("Run a shell command on the host.");
474 shell_alias->SetHelpLong("");
475 shell_alias->SetSyntax("shell <shell-command>");
476 }
477 }
478
479 cmd_obj_sp = GetCommandSPExact(cmd: "process kill");
480 if (cmd_obj_sp) {
481 AddAlias(alias_name: "kill", command_obj_sp&: cmd_obj_sp);
482 }
483
484 cmd_obj_sp = GetCommandSPExact(cmd: "process launch");
485 if (cmd_obj_sp) {
486 alias_arguments_vector_sp = std::make_shared<OptionArgVector>();
487#if defined(__APPLE__)
488#if TARGET_OS_IPHONE
489 AddAlias("r", cmd_obj_sp, "--");
490 AddAlias("run", cmd_obj_sp, "--");
491#else
492 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
493 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
494#endif
495#else
496 StreamString defaultshell;
497 defaultshell.Printf(format: "--shell=%s --",
498 HostInfo::GetDefaultShell().GetPath().c_str());
499 AddAlias(alias_name: "r", command_obj_sp&: cmd_obj_sp, args_string: defaultshell.GetString());
500 AddAlias(alias_name: "run", command_obj_sp&: cmd_obj_sp, args_string: defaultshell.GetString());
501#endif
502 }
503
504 cmd_obj_sp = GetCommandSPExact(cmd: "target symbols add");
505 if (cmd_obj_sp) {
506 AddAlias(alias_name: "add-dsym", command_obj_sp&: cmd_obj_sp);
507 }
508
509 cmd_obj_sp = GetCommandSPExact(cmd: "breakpoint set");
510 if (cmd_obj_sp) {
511 AddAlias(alias_name: "rbreak", command_obj_sp&: cmd_obj_sp, args_string: "--func-regex %1");
512 }
513
514 cmd_obj_sp = GetCommandSPExact(cmd: "frame variable");
515 if (cmd_obj_sp) {
516 AddAlias(alias_name: "v", command_obj_sp&: cmd_obj_sp);
517 AddAlias(alias_name: "var", command_obj_sp&: cmd_obj_sp);
518 AddAlias(alias_name: "vo", command_obj_sp&: cmd_obj_sp, args_string: "--object-description");
519 }
520
521 cmd_obj_sp = GetCommandSPExact(cmd: "register");
522 if (cmd_obj_sp) {
523 AddAlias(alias_name: "re", command_obj_sp&: cmd_obj_sp);
524 }
525
526 cmd_obj_sp = GetCommandSPExact(cmd: "scripting run");
527 if (cmd_obj_sp) {
528 AddAlias(alias_name: "script", command_obj_sp&: cmd_obj_sp);
529 }
530
531 cmd_obj_sp = GetCommandSPExact(cmd: "session history");
532 if (cmd_obj_sp) {
533 AddAlias(alias_name: "history", command_obj_sp&: cmd_obj_sp);
534 }
535
536 cmd_obj_sp = GetCommandSPExact(cmd: "help");
537 if (cmd_obj_sp) {
538 AddAlias(alias_name: "h", command_obj_sp&: cmd_obj_sp);
539 }
540}
541
542void CommandInterpreter::Clear() { m_command_io_handler_sp.reset(); }
543
544const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
545 // This function has not yet been implemented.
546
547 // Look for any embedded script command
548 // If found,
549 // get interpreter object from the command dictionary,
550 // call execute_one_command on it,
551 // get the results as a string,
552 // substitute that string for current stuff.
553
554 return arg;
555}
556
557#define REGISTER_COMMAND_OBJECT(NAME, CLASS) \
558 m_command_dict[NAME] = std::make_shared<CLASS>(*this);
559
560void CommandInterpreter::LoadCommandDictionary() {
561 LLDB_SCOPED_TIMER();
562
563 REGISTER_COMMAND_OBJECT("apropos", CommandObjectApropos);
564 REGISTER_COMMAND_OBJECT("breakpoint", CommandObjectMultiwordBreakpoint);
565 REGISTER_COMMAND_OBJECT("command", CommandObjectMultiwordCommands);
566 REGISTER_COMMAND_OBJECT("diagnostics", CommandObjectDiagnostics);
567 REGISTER_COMMAND_OBJECT("disassemble", CommandObjectDisassemble);
568 REGISTER_COMMAND_OBJECT("dwim-print", CommandObjectDWIMPrint);
569 REGISTER_COMMAND_OBJECT("expression", CommandObjectExpression);
570 REGISTER_COMMAND_OBJECT("frame", CommandObjectMultiwordFrame);
571 REGISTER_COMMAND_OBJECT("gui", CommandObjectGUI);
572 REGISTER_COMMAND_OBJECT("help", CommandObjectHelp);
573 REGISTER_COMMAND_OBJECT("log", CommandObjectLog);
574 REGISTER_COMMAND_OBJECT("memory", CommandObjectMemory);
575 REGISTER_COMMAND_OBJECT("platform", CommandObjectPlatform);
576 REGISTER_COMMAND_OBJECT("plugin", CommandObjectPlugin);
577 REGISTER_COMMAND_OBJECT("process", CommandObjectMultiwordProcess);
578 REGISTER_COMMAND_OBJECT("protocol-server", CommandObjectProtocolServer);
579 REGISTER_COMMAND_OBJECT("quit", CommandObjectQuit);
580 REGISTER_COMMAND_OBJECT("register", CommandObjectRegister);
581 REGISTER_COMMAND_OBJECT("scripting", CommandObjectMultiwordScripting);
582 REGISTER_COMMAND_OBJECT("settings", CommandObjectMultiwordSettings);
583 REGISTER_COMMAND_OBJECT("session", CommandObjectSession);
584 REGISTER_COMMAND_OBJECT("source", CommandObjectMultiwordSource);
585 REGISTER_COMMAND_OBJECT("statistics", CommandObjectStats);
586 REGISTER_COMMAND_OBJECT("target", CommandObjectMultiwordTarget);
587 REGISTER_COMMAND_OBJECT("thread", CommandObjectMultiwordThread);
588 REGISTER_COMMAND_OBJECT("trace", CommandObjectTrace);
589 REGISTER_COMMAND_OBJECT("type", CommandObjectType);
590 REGISTER_COMMAND_OBJECT("version", CommandObjectVersion);
591 REGISTER_COMMAND_OBJECT("watchpoint", CommandObjectMultiwordWatchpoint);
592 REGISTER_COMMAND_OBJECT("language", CommandObjectLanguage);
593
594 // clang-format off
595 const char *break_regexes[][2] = {
596 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
597 "breakpoint set --file '%1' --line %2 --column %3"},
598 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
599 "breakpoint set --file '%1' --line %2"},
600 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
601 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
602 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
603 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
604 "breakpoint set --name '%1'"},
605 {"^(-.*)$", "breakpoint set %1"},
606 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
607 "breakpoint set --name '%2' --shlib '%1'"},
608 {"^\\&(.*[^[:space:]])[[:space:]]*$",
609 "breakpoint set --name '%1' --skip-prologue=0"},
610 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
611 "breakpoint set --name '%1'"}};
612 // clang-format on
613
614 size_t num_regexes = std::size(break_regexes);
615
616 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_up(
617 new CommandObjectRegexCommand(
618 *this, "_regexp-break",
619 "Set a breakpoint using one of several shorthand formats.",
620 "\n"
621 "_regexp-break <filename>:<linenum>:<colnum>\n"
622 " main.c:12:21 // Break at line 12 and column "
623 "21 of main.c\n\n"
624 "_regexp-break <filename>:<linenum>\n"
625 " main.c:12 // Break at line 12 of "
626 "main.c\n\n"
627 "_regexp-break <linenum>\n"
628 " 12 // Break at line 12 of current "
629 "file\n\n"
630 "_regexp-break 0x<address>\n"
631 " 0x1234000 // Break at address "
632 "0x1234000\n\n"
633 "_regexp-break <name>\n"
634 " main // Break in 'main' after the "
635 "prologue\n\n"
636 "_regexp-break &<name>\n"
637 " &main // Break at first instruction "
638 "in 'main'\n\n"
639 "_regexp-break <module>`<name>\n"
640 " libc.so`malloc // Break in 'malloc' from "
641 "'libc.so'\n\n"
642 "_regexp-break /<source-regex>/\n"
643 " /break here/ // Break on source lines in "
644 "current file\n"
645 " // containing text 'break "
646 "here'.\n",
647 lldb::eSymbolCompletion | lldb::eSourceFileCompletion, false));
648
649 if (break_regex_cmd_up) {
650 bool success = true;
651 for (size_t i = 0; i < num_regexes; i++) {
652 success = break_regex_cmd_up->AddRegexCommand(re_cstr: break_regexes[i][0],
653 command_cstr: break_regexes[i][1]);
654 if (!success)
655 break;
656 }
657 success =
658 break_regex_cmd_up->AddRegexCommand(re_cstr: "^$", command_cstr: "breakpoint list --full");
659
660 if (success) {
661 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_up.release());
662 m_command_dict[std::string(break_regex_cmd_sp->GetCommandName())] =
663 break_regex_cmd_sp;
664 }
665 }
666
667 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_up(
668 new CommandObjectRegexCommand(
669 *this, "_regexp-tbreak",
670 "Set a one-shot breakpoint using one of several shorthand formats.",
671 "\n"
672 "_regexp-break <filename>:<linenum>:<colnum>\n"
673 " main.c:12:21 // Break at line 12 and column "
674 "21 of main.c\n\n"
675 "_regexp-break <filename>:<linenum>\n"
676 " main.c:12 // Break at line 12 of "
677 "main.c\n\n"
678 "_regexp-break <linenum>\n"
679 " 12 // Break at line 12 of current "
680 "file\n\n"
681 "_regexp-break 0x<address>\n"
682 " 0x1234000 // Break at address "
683 "0x1234000\n\n"
684 "_regexp-break <name>\n"
685 " main // Break in 'main' after the "
686 "prologue\n\n"
687 "_regexp-break &<name>\n"
688 " &main // Break at first instruction "
689 "in 'main'\n\n"
690 "_regexp-break <module>`<name>\n"
691 " libc.so`malloc // Break in 'malloc' from "
692 "'libc.so'\n\n"
693 "_regexp-break /<source-regex>/\n"
694 " /break here/ // Break on source lines in "
695 "current file\n"
696 " // containing text 'break "
697 "here'.\n",
698 lldb::eSymbolCompletion | lldb::eSourceFileCompletion, false));
699
700 if (tbreak_regex_cmd_up) {
701 bool success = true;
702 for (size_t i = 0; i < num_regexes; i++) {
703 std::string command = break_regexes[i][1];
704 command += " -o 1";
705 success =
706 tbreak_regex_cmd_up->AddRegexCommand(re_cstr: break_regexes[i][0], command_cstr: command);
707 if (!success)
708 break;
709 }
710 success =
711 tbreak_regex_cmd_up->AddRegexCommand(re_cstr: "^$", command_cstr: "breakpoint list --full");
712
713 if (success) {
714 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_up.release());
715 m_command_dict[std::string(tbreak_regex_cmd_sp->GetCommandName())] =
716 tbreak_regex_cmd_sp;
717 }
718 }
719
720 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_up(
721 new CommandObjectRegexCommand(
722 *this, "_regexp-attach", "Attach to process by ID or name.",
723 "_regexp-attach <pid> | <process-name>", 0, false));
724 if (attach_regex_cmd_up) {
725 if (attach_regex_cmd_up->AddRegexCommand(re_cstr: "^([0-9]+)[[:space:]]*$",
726 command_cstr: "process attach --pid %1") &&
727 attach_regex_cmd_up->AddRegexCommand(
728 re_cstr: "^(-.*|.* -.*)$", command_cstr: "process attach %1") && // Any options that are
729 // specified get passed to
730 // 'process attach'
731 attach_regex_cmd_up->AddRegexCommand(re_cstr: "^(.+)$",
732 command_cstr: "process attach --name '%1'") &&
733 attach_regex_cmd_up->AddRegexCommand(re_cstr: "^$", command_cstr: "process attach")) {
734 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_up.release());
735 m_command_dict[std::string(attach_regex_cmd_sp->GetCommandName())] =
736 attach_regex_cmd_sp;
737 }
738 }
739
740 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_up(
741 new CommandObjectRegexCommand(*this, "_regexp-down",
742 "Select a newer stack frame. Defaults to "
743 "moving one frame, a numeric argument can "
744 "specify an arbitrary number.",
745 "_regexp-down [<count>]", 0, false));
746 if (down_regex_cmd_up) {
747 if (down_regex_cmd_up->AddRegexCommand(re_cstr: "^$", command_cstr: "frame select -r -1") &&
748 down_regex_cmd_up->AddRegexCommand(re_cstr: "^([0-9]+)$",
749 command_cstr: "frame select -r -%1")) {
750 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_up.release());
751 m_command_dict[std::string(down_regex_cmd_sp->GetCommandName())] =
752 down_regex_cmd_sp;
753 }
754 }
755
756 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_up(
757 new CommandObjectRegexCommand(
758 *this, "_regexp-up",
759 "Select an older stack frame. Defaults to moving one "
760 "frame, a numeric argument can specify an arbitrary number.",
761 "_regexp-up [<count>]", 0, false));
762 if (up_regex_cmd_up) {
763 if (up_regex_cmd_up->AddRegexCommand(re_cstr: "^$", command_cstr: "frame select -r 1") &&
764 up_regex_cmd_up->AddRegexCommand(re_cstr: "^([0-9]+)$", command_cstr: "frame select -r %1")) {
765 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_up.release());
766 m_command_dict[std::string(up_regex_cmd_sp->GetCommandName())] =
767 up_regex_cmd_sp;
768 }
769 }
770
771 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_up(
772 new CommandObjectRegexCommand(
773 *this, "_regexp-display",
774 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
775 "_regexp-display expression", 0, false));
776 if (display_regex_cmd_up) {
777 if (display_regex_cmd_up->AddRegexCommand(
778 re_cstr: "^(.+)$", command_cstr: "target stop-hook add -o \"expr -- %1\"")) {
779 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_up.release());
780 m_command_dict[std::string(display_regex_cmd_sp->GetCommandName())] =
781 display_regex_cmd_sp;
782 }
783 }
784
785 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_up(
786 new CommandObjectRegexCommand(*this, "_regexp-undisplay",
787 "Stop displaying expression at every "
788 "stop (specified by stop-hook index.)",
789 "_regexp-undisplay stop-hook-number", 0,
790 false));
791 if (undisplay_regex_cmd_up) {
792 if (undisplay_regex_cmd_up->AddRegexCommand(re_cstr: "^([0-9]+)$",
793 command_cstr: "target stop-hook delete %1")) {
794 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_up.release());
795 m_command_dict[std::string(undisplay_regex_cmd_sp->GetCommandName())] =
796 undisplay_regex_cmd_sp;
797 }
798 }
799
800 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_up(
801 new CommandObjectRegexCommand(
802 *this, "gdb-remote",
803 "Connect to a process via remote GDB server.\n"
804 "If no host is specified, localhost is assumed.\n"
805 "gdb-remote is an abbreviation for 'process connect --plugin "
806 "gdb-remote connect://<hostname>:<port>'\n",
807 "gdb-remote [<hostname>:]<portnum>", 0, false));
808 if (connect_gdb_remote_cmd_up) {
809 if (connect_gdb_remote_cmd_up->AddRegexCommand(
810 re_cstr: "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
811 command_cstr: "process connect --plugin gdb-remote connect://%1:%2") &&
812 connect_gdb_remote_cmd_up->AddRegexCommand(
813 re_cstr: "^([[:digit:]]+)$",
814 command_cstr: "process connect --plugin gdb-remote connect://localhost:%1")) {
815 CommandObjectSP command_sp(connect_gdb_remote_cmd_up.release());
816 m_command_dict[std::string(command_sp->GetCommandName())] = command_sp;
817 }
818 }
819
820 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_up(
821 new CommandObjectRegexCommand(
822 *this, "kdp-remote",
823 "Connect to a process via remote KDP server.\n"
824 "If no UDP port is specified, port 41139 is assumed.\n"
825 "kdp-remote is an abbreviation for 'process connect --plugin "
826 "kdp-remote udp://<hostname>:<port>'\n",
827 "kdp-remote <hostname>[:<portnum>]", 0, false));
828 if (connect_kdp_remote_cmd_up) {
829 if (connect_kdp_remote_cmd_up->AddRegexCommand(
830 re_cstr: "^([^:]+:[[:digit:]]+)$",
831 command_cstr: "process connect --plugin kdp-remote udp://%1") &&
832 connect_kdp_remote_cmd_up->AddRegexCommand(
833 re_cstr: "^(.+)$", command_cstr: "process connect --plugin kdp-remote udp://%1:41139")) {
834 CommandObjectSP command_sp(connect_kdp_remote_cmd_up.release());
835 m_command_dict[std::string(command_sp->GetCommandName())] = command_sp;
836 }
837 }
838
839 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_up(
840 new CommandObjectRegexCommand(
841 *this, "_regexp-bt",
842 "Show backtrace of the current thread's call stack. Any numeric "
843 "argument displays at most that many frames. The argument 'all' "
844 "displays all threads. Use 'settings set frame-format' to customize "
845 "the printing of individual frames and 'settings set thread-format' "
846 "to customize the thread header. Frame recognizers may filter the "
847 "list. Use 'thread backtrace -u (--unfiltered)' to see them all.",
848 "bt [<digit> | all]", 0, false));
849 if (bt_regex_cmd_up) {
850 // accept but don't document "bt -c <number>" -- before bt was a regex
851 // command if you wanted to backtrace three frames you would do "bt -c 3"
852 // but the intention is to have this emulate the gdb "bt" command and so
853 // now "bt 3" is the preferred form, in line with gdb.
854 if (bt_regex_cmd_up->AddRegexCommand(re_cstr: "^([[:digit:]]+)[[:space:]]*$",
855 command_cstr: "thread backtrace -c %1") &&
856 bt_regex_cmd_up->AddRegexCommand(re_cstr: "^(-[^[:space:]].*)$",
857 command_cstr: "thread backtrace %1") &&
858 bt_regex_cmd_up->AddRegexCommand(re_cstr: "^all[[:space:]]*$",
859 command_cstr: "thread backtrace all") &&
860 bt_regex_cmd_up->AddRegexCommand(re_cstr: "^[[:space:]]*$",
861 command_cstr: "thread backtrace")) {
862 CommandObjectSP command_sp(bt_regex_cmd_up.release());
863 m_command_dict[std::string(command_sp->GetCommandName())] = command_sp;
864 }
865 }
866
867 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_up(
868 new CommandObjectRegexCommand(
869 *this, "_regexp-list",
870 "List relevant source code using one of several shorthand formats.",
871 "\n"
872 "_regexp-list <file>:<line> // List around specific file/line\n"
873 "_regexp-list <line> // List current file around specified "
874 "line\n"
875 "_regexp-list <function-name> // List specified function\n"
876 "_regexp-list 0x<address> // List around specified address\n"
877 "_regexp-list -[<count>] // List previous <count> lines\n"
878 "_regexp-list // List subsequent lines",
879 lldb::eSourceFileCompletion, false));
880 if (list_regex_cmd_up) {
881 if (list_regex_cmd_up->AddRegexCommand(re_cstr: "^([0-9]+)[[:space:]]*$",
882 command_cstr: "source list --line %1") &&
883 list_regex_cmd_up->AddRegexCommand(
884 re_cstr: "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
885 "]*$",
886 command_cstr: "source list --file '%1' --line %2") &&
887 list_regex_cmd_up->AddRegexCommand(
888 re_cstr: "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
889 command_cstr: "source list --address %1") &&
890 list_regex_cmd_up->AddRegexCommand(re_cstr: "^-[[:space:]]*$",
891 command_cstr: "source list --reverse") &&
892 list_regex_cmd_up->AddRegexCommand(
893 re_cstr: "^-([[:digit:]]+)[[:space:]]*$",
894 command_cstr: "source list --reverse --count %1") &&
895 list_regex_cmd_up->AddRegexCommand(re_cstr: "^(.+)$",
896 command_cstr: "source list --name \"%1\"") &&
897 list_regex_cmd_up->AddRegexCommand(re_cstr: "^$", command_cstr: "source list")) {
898 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_up.release());
899 m_command_dict[std::string(list_regex_cmd_sp->GetCommandName())] =
900 list_regex_cmd_sp;
901 }
902 }
903
904 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_up(
905 new CommandObjectRegexCommand(
906 *this, "_regexp-env",
907 "Shorthand for viewing and setting environment variables.",
908 "\n"
909 "_regexp-env // Show environment\n"
910 "_regexp-env <name>=<value> // Set an environment variable",
911 0, false));
912 if (env_regex_cmd_up) {
913 if (env_regex_cmd_up->AddRegexCommand(re_cstr: "^$",
914 command_cstr: "settings show target.env-vars") &&
915 env_regex_cmd_up->AddRegexCommand(re_cstr: "^([A-Za-z_][A-Za-z_0-9]*=.*)$",
916 command_cstr: "settings set target.env-vars %1")) {
917 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_up.release());
918 m_command_dict[std::string(env_regex_cmd_sp->GetCommandName())] =
919 env_regex_cmd_sp;
920 }
921 }
922
923 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_up(
924 new CommandObjectRegexCommand(
925 *this, "_regexp-jump", "Set the program counter to a new address.",
926 "\n"
927 "_regexp-jump <line>\n"
928 "_regexp-jump +<line-offset> | -<line-offset>\n"
929 "_regexp-jump <file>:<line>\n"
930 "_regexp-jump *<addr>\n",
931 0, false));
932 if (jump_regex_cmd_up) {
933 if (jump_regex_cmd_up->AddRegexCommand(re_cstr: "^\\*(.*)$",
934 command_cstr: "thread jump --addr %1") &&
935 jump_regex_cmd_up->AddRegexCommand(re_cstr: "^([0-9]+)$",
936 command_cstr: "thread jump --line %1") &&
937 jump_regex_cmd_up->AddRegexCommand(re_cstr: "^([^:]+):([0-9]+)$",
938 command_cstr: "thread jump --file %1 --line %2") &&
939 jump_regex_cmd_up->AddRegexCommand(re_cstr: "^([+\\-][0-9]+)$",
940 command_cstr: "thread jump --by %1")) {
941 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_up.release());
942 m_command_dict[std::string(jump_regex_cmd_sp->GetCommandName())] =
943 jump_regex_cmd_sp;
944 }
945 }
946}
947
948int CommandInterpreter::GetCommandNamesMatchingPartialString(
949 const char *cmd_str, bool include_aliases, StringList &matches,
950 StringList &descriptions) {
951 AddNamesMatchingPartialString(in_map: m_command_dict, cmd_str, matches,
952 descriptions: &descriptions);
953
954 if (include_aliases) {
955 AddNamesMatchingPartialString(in_map: m_alias_dict, cmd_str, matches,
956 descriptions: &descriptions);
957 }
958
959 return matches.GetSize();
960}
961
962CommandObjectMultiword *
963CommandInterpreter::VerifyUserMultiwordCmdPath(Args &path, bool leaf_is_command,
964 Status &result) {
965 result.Clear();
966
967 auto get_multi_or_report_error =
968 [&result](CommandObjectSP cmd_sp,
969 const char *name) -> CommandObjectMultiword * {
970 if (!cmd_sp) {
971 result = Status::FromErrorStringWithFormat(
972 format: "Path component: '%s' not found", name);
973 return nullptr;
974 }
975 if (!cmd_sp->IsUserCommand()) {
976 result = Status::FromErrorStringWithFormat(
977 format: "Path component: '%s' is not a user "
978 "command",
979 name);
980 return nullptr;
981 }
982 CommandObjectMultiword *cmd_as_multi = cmd_sp->GetAsMultiwordCommand();
983 if (!cmd_as_multi) {
984 result = Status::FromErrorStringWithFormat(
985 format: "Path component: '%s' is not a container "
986 "command",
987 name);
988 return nullptr;
989 }
990 return cmd_as_multi;
991 };
992
993 size_t num_args = path.GetArgumentCount();
994 if (num_args == 0) {
995 result = Status::FromErrorString(str: "empty command path");
996 return nullptr;
997 }
998
999 if (num_args == 1 && leaf_is_command) {
1000 // We just got a leaf command to be added to the root. That's not an error,
1001 // just return null for the container.
1002 return nullptr;
1003 }
1004
1005 // Start by getting the root command from the interpreter.
1006 const char *cur_name = path.GetArgumentAtIndex(idx: 0);
1007 CommandObjectSP cur_cmd_sp = GetCommandSPExact(cmd: cur_name);
1008 CommandObjectMultiword *cur_as_multi =
1009 get_multi_or_report_error(cur_cmd_sp, cur_name);
1010 if (cur_as_multi == nullptr)
1011 return nullptr;
1012
1013 size_t num_path_elements = num_args - (leaf_is_command ? 1 : 0);
1014 for (size_t cursor = 1; cursor < num_path_elements && cur_as_multi != nullptr;
1015 cursor++) {
1016 cur_name = path.GetArgumentAtIndex(idx: cursor);
1017 cur_cmd_sp = cur_as_multi->GetSubcommandSPExact(sub_cmd: cur_name);
1018 cur_as_multi = get_multi_or_report_error(cur_cmd_sp, cur_name);
1019 }
1020 return cur_as_multi;
1021}
1022
1023CommandObjectSP CommandInterpreter::GetFrameLanguageCommand() const {
1024 auto frame_sp = GetExecutionContext().GetFrameSP();
1025 if (!frame_sp)
1026 return {};
1027 auto frame_language =
1028 Language::GetPrimaryLanguage(language: frame_sp->GuessLanguage().AsLanguageType());
1029
1030 auto it = m_command_dict.find(x: "language");
1031 if (it == m_command_dict.end())
1032 return {};
1033 // The root "language" command.
1034 CommandObjectSP language_cmd_sp = it->second;
1035
1036 auto *plugin = Language::FindPlugin(language: frame_language);
1037 if (!plugin)
1038 return {};
1039 // "cplusplus", "objc", etc.
1040 auto lang_name = plugin->GetPluginName();
1041
1042 return language_cmd_sp->GetSubcommandSPExact(sub_cmd: lang_name);
1043}
1044
1045CommandObjectSP
1046CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases,
1047 bool exact, StringList *matches,
1048 StringList *descriptions) const {
1049 CommandObjectSP command_sp;
1050
1051 std::string cmd = std::string(cmd_str);
1052
1053 if (HasCommands()) {
1054 auto pos = m_command_dict.find(x: cmd);
1055 if (pos != m_command_dict.end())
1056 command_sp = pos->second;
1057 }
1058
1059 if (include_aliases && HasAliases()) {
1060 auto alias_pos = m_alias_dict.find(x: cmd);
1061 if (alias_pos != m_alias_dict.end())
1062 command_sp = alias_pos->second;
1063 }
1064
1065 if (HasUserCommands()) {
1066 auto pos = m_user_dict.find(x: cmd);
1067 if (pos != m_user_dict.end())
1068 command_sp = pos->second;
1069 }
1070
1071 if (HasUserMultiwordCommands()) {
1072 auto pos = m_user_mw_dict.find(x: cmd);
1073 if (pos != m_user_mw_dict.end())
1074 command_sp = pos->second;
1075 }
1076
1077 if (!exact && !command_sp) {
1078 // We will only get into here if we didn't find any exact matches.
1079
1080 CommandObjectSP user_match_sp, user_mw_match_sp, alias_match_sp,
1081 real_match_sp;
1082
1083 StringList local_matches;
1084 if (matches == nullptr)
1085 matches = &local_matches;
1086
1087 unsigned int num_cmd_matches = 0;
1088 unsigned int num_alias_matches = 0;
1089 unsigned int num_user_matches = 0;
1090 unsigned int num_user_mw_matches = 0;
1091
1092 // Look through the command dictionaries one by one, and if we get only one
1093 // match from any of them in toto, then return that, otherwise return an
1094 // empty CommandObjectSP and the list of matches.
1095
1096 if (HasCommands()) {
1097 num_cmd_matches = AddNamesMatchingPartialString(in_map: m_command_dict, cmd_str,
1098 matches&: *matches, descriptions);
1099 }
1100
1101 if (num_cmd_matches == 1) {
1102 cmd.assign(s: matches->GetStringAtIndex(idx: 0));
1103 auto pos = m_command_dict.find(x: cmd);
1104 if (pos != m_command_dict.end())
1105 real_match_sp = pos->second;
1106 }
1107
1108 if (include_aliases && HasAliases()) {
1109 num_alias_matches = AddNamesMatchingPartialString(in_map: m_alias_dict, cmd_str,
1110 matches&: *matches, descriptions);
1111 }
1112
1113 if (num_alias_matches == 1) {
1114 cmd.assign(s: matches->GetStringAtIndex(idx: num_cmd_matches));
1115 auto alias_pos = m_alias_dict.find(x: cmd);
1116 if (alias_pos != m_alias_dict.end())
1117 alias_match_sp = alias_pos->second;
1118 }
1119
1120 if (HasUserCommands()) {
1121 num_user_matches = AddNamesMatchingPartialString(in_map: m_user_dict, cmd_str,
1122 matches&: *matches, descriptions);
1123 }
1124
1125 if (num_user_matches == 1) {
1126 cmd.assign(
1127 s: matches->GetStringAtIndex(idx: num_cmd_matches + num_alias_matches));
1128
1129 auto pos = m_user_dict.find(x: cmd);
1130 if (pos != m_user_dict.end())
1131 user_match_sp = pos->second;
1132 }
1133
1134 if (HasUserMultiwordCommands()) {
1135 num_user_mw_matches = AddNamesMatchingPartialString(
1136 in_map: m_user_mw_dict, cmd_str, matches&: *matches, descriptions);
1137 }
1138
1139 if (num_user_mw_matches == 1) {
1140 cmd.assign(s: matches->GetStringAtIndex(idx: num_cmd_matches + num_alias_matches +
1141 num_user_matches));
1142
1143 auto pos = m_user_mw_dict.find(x: cmd);
1144 if (pos != m_user_mw_dict.end())
1145 user_mw_match_sp = pos->second;
1146 }
1147
1148 // If we got exactly one match, return that, otherwise return the match
1149 // list.
1150
1151 if (num_user_matches + num_user_mw_matches + num_cmd_matches +
1152 num_alias_matches ==
1153 1) {
1154 if (num_cmd_matches)
1155 return real_match_sp;
1156 else if (num_alias_matches)
1157 return alias_match_sp;
1158 else if (num_user_mw_matches)
1159 return user_mw_match_sp;
1160 else
1161 return user_match_sp;
1162 }
1163 }
1164
1165 // When no single match is found, attempt to resolve the command as a language
1166 // plugin subcommand.
1167 if (!command_sp) {
1168 // The `language` subcommand ("language objc", "language cplusplus", etc).
1169 CommandObjectMultiword *lang_subcmd = nullptr;
1170 if (auto lang_subcmd_sp = GetFrameLanguageCommand()) {
1171 lang_subcmd = lang_subcmd_sp->GetAsMultiwordCommand();
1172 command_sp = lang_subcmd_sp->GetSubcommandSPExact(sub_cmd: cmd_str);
1173 }
1174
1175 if (!command_sp && !exact && lang_subcmd) {
1176 StringList lang_matches;
1177 AddNamesMatchingPartialString(in_map: lang_subcmd->GetSubcommandDictionary(),
1178 cmd_str, matches&: lang_matches, descriptions);
1179 if (matches)
1180 matches->AppendList(strings: lang_matches);
1181 if (lang_matches.GetSize() == 1) {
1182 const auto &lang_dict = lang_subcmd->GetSubcommandDictionary();
1183 auto pos = lang_dict.find(x: lang_matches[0]);
1184 if (pos != lang_dict.end())
1185 return pos->second;
1186 }
1187 }
1188 }
1189
1190 if (matches && command_sp) {
1191 matches->AppendString(str: cmd_str);
1192 if (descriptions)
1193 descriptions->AppendString(str: command_sp->GetHelp());
1194 }
1195
1196 return command_sp;
1197}
1198
1199bool CommandInterpreter::AddCommand(llvm::StringRef name,
1200 const lldb::CommandObjectSP &cmd_sp,
1201 bool can_replace) {
1202 if (cmd_sp.get())
1203 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
1204 "tried to add a CommandObject from a different interpreter");
1205
1206 if (name.empty())
1207 return false;
1208
1209 cmd_sp->SetIsUserCommand(false);
1210
1211 std::string name_sstr(name);
1212 auto name_iter = m_command_dict.find(x: name_sstr);
1213 if (name_iter != m_command_dict.end()) {
1214 if (!can_replace || !name_iter->second->IsRemovable())
1215 return false;
1216 name_iter->second = cmd_sp;
1217 } else {
1218 m_command_dict[name_sstr] = cmd_sp;
1219 }
1220 return true;
1221}
1222
1223Status CommandInterpreter::AddUserCommand(llvm::StringRef name,
1224 const lldb::CommandObjectSP &cmd_sp,
1225 bool can_replace) {
1226 Status result;
1227 if (cmd_sp.get())
1228 lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
1229 "tried to add a CommandObject from a different interpreter");
1230 if (name.empty()) {
1231 result = Status::FromErrorString(
1232 str: "can't use the empty string for a command name");
1233 return result;
1234 }
1235 // do not allow replacement of internal commands
1236 if (CommandExists(cmd: name)) {
1237 result = Status::FromErrorString(str: "can't replace builtin command");
1238 return result;
1239 }
1240
1241 if (UserCommandExists(cmd: name)) {
1242 if (!can_replace) {
1243 result = Status::FromErrorStringWithFormatv(
1244 format: "user command \"{0}\" already exists and force replace was not set "
1245 "by --overwrite or 'settings set interpreter.require-overwrite "
1246 "false'",
1247 args&: name);
1248 return result;
1249 }
1250 if (cmd_sp->IsMultiwordObject()) {
1251 if (!m_user_mw_dict[std::string(name)]->IsRemovable()) {
1252 result = Status::FromErrorString(
1253 str: "can't replace explicitly non-removable multi-word command");
1254 return result;
1255 }
1256 } else {
1257 if (!m_user_dict[std::string(name)]->IsRemovable()) {
1258 result = Status::FromErrorString(
1259 str: "can't replace explicitly non-removable command");
1260 return result;
1261 }
1262 }
1263 }
1264
1265 cmd_sp->SetIsUserCommand(true);
1266
1267 if (cmd_sp->IsMultiwordObject())
1268 m_user_mw_dict[std::string(name)] = cmd_sp;
1269 else
1270 m_user_dict[std::string(name)] = cmd_sp;
1271 return result;
1272}
1273
1274CommandObjectSP
1275CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
1276 bool include_aliases) const {
1277 // Break up the command string into words, in case it's a multi-word command.
1278 Args cmd_words(cmd_str);
1279
1280 if (cmd_str.empty())
1281 return {};
1282
1283 if (cmd_words.GetArgumentCount() == 1)
1284 return GetCommandSP(cmd_str, include_aliases, exact: true);
1285
1286 // We have a multi-word command (seemingly), so we need to do more work.
1287 // First, get the cmd_obj_sp for the first word in the command.
1288 CommandObjectSP cmd_obj_sp =
1289 GetCommandSP(cmd_str: cmd_words.GetArgumentAtIndex(idx: 0), include_aliases, exact: true);
1290 if (!cmd_obj_sp)
1291 return {};
1292
1293 // Loop through the rest of the words in the command (everything passed in
1294 // was supposed to be part of a command name), and find the appropriate
1295 // sub-command SP for each command word....
1296 size_t end = cmd_words.GetArgumentCount();
1297 for (size_t i = 1; i < end; ++i) {
1298 if (!cmd_obj_sp->IsMultiwordObject()) {
1299 // We have more words in the command name, but we don't have a
1300 // multiword object. Fail and return.
1301 return {};
1302 }
1303
1304 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP(sub_cmd: cmd_words.GetArgumentAtIndex(idx: i));
1305 if (!cmd_obj_sp) {
1306 // The sub-command name was invalid. Fail and return.
1307 return {};
1308 }
1309 }
1310
1311 // We successfully looped through all the command words and got valid
1312 // command objects for them.
1313 return cmd_obj_sp;
1314}
1315
1316CommandObject *
1317CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
1318 StringList *matches,
1319 StringList *descriptions) const {
1320 // Try to find a match among commands and aliases. Allowing inexact matches,
1321 // but perferring exact matches.
1322 return GetCommandSP(cmd_str, /*include_aliases=*/true, /*exact=*/false,
1323 matches, descriptions)
1324 .get();
1325}
1326
1327CommandObject *CommandInterpreter::GetUserCommandObject(
1328 llvm::StringRef cmd, StringList *matches, StringList *descriptions) const {
1329 std::string cmd_str(cmd);
1330 auto find_exact = [&](const CommandObject::CommandMap &map) {
1331 auto found_elem = map.find(x: cmd);
1332 if (found_elem == map.end())
1333 return (CommandObject *)nullptr;
1334 CommandObject *exact_cmd = found_elem->second.get();
1335 if (exact_cmd) {
1336 if (matches)
1337 matches->AppendString(str: exact_cmd->GetCommandName());
1338 if (descriptions)
1339 descriptions->AppendString(str: exact_cmd->GetHelp());
1340 return exact_cmd;
1341 }
1342 return (CommandObject *)nullptr;
1343 };
1344
1345 CommandObject *exact_cmd = find_exact(GetUserCommands());
1346 if (exact_cmd)
1347 return exact_cmd;
1348
1349 exact_cmd = find_exact(GetUserMultiwordCommands());
1350 if (exact_cmd)
1351 return exact_cmd;
1352
1353 // We didn't have an exact command, so now look for partial matches.
1354 StringList tmp_list;
1355 StringList *matches_ptr = matches ? matches : &tmp_list;
1356 AddNamesMatchingPartialString(in_map: GetUserCommands(), cmd_str, matches&: *matches_ptr);
1357 AddNamesMatchingPartialString(in_map: GetUserMultiwordCommands(), cmd_str,
1358 matches&: *matches_ptr);
1359
1360 return {};
1361}
1362
1363CommandObject *CommandInterpreter::GetAliasCommandObject(
1364 llvm::StringRef cmd, StringList *matches, StringList *descriptions) const {
1365 auto find_exact =
1366 [&](const CommandObject::CommandMap &map) -> CommandObject * {
1367 auto found_elem = map.find(x: cmd);
1368 if (found_elem == map.end())
1369 return (CommandObject *)nullptr;
1370 CommandObject *exact_cmd = found_elem->second.get();
1371 if (!exact_cmd)
1372 return nullptr;
1373
1374 if (matches)
1375 matches->AppendString(str: exact_cmd->GetCommandName());
1376
1377 if (descriptions)
1378 descriptions->AppendString(str: exact_cmd->GetHelp());
1379
1380 return exact_cmd;
1381 return nullptr;
1382 };
1383
1384 CommandObject *exact_cmd = find_exact(GetAliases());
1385 if (exact_cmd)
1386 return exact_cmd;
1387
1388 // We didn't have an exact command, so now look for partial matches.
1389 StringList tmp_list;
1390 StringList *matches_ptr = matches ? matches : &tmp_list;
1391 AddNamesMatchingPartialString(in_map: GetAliases(), cmd_str: cmd, matches&: *matches_ptr);
1392
1393 return {};
1394}
1395
1396bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
1397 return m_command_dict.find(x: cmd) != m_command_dict.end();
1398}
1399
1400bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1401 std::string &full_name) const {
1402 bool exact_match = (m_alias_dict.find(x: cmd) != m_alias_dict.end());
1403 if (exact_match) {
1404 full_name.assign(str: std::string(cmd));
1405 return exact_match;
1406 } else {
1407 StringList matches;
1408 size_t num_alias_matches;
1409 num_alias_matches =
1410 AddNamesMatchingPartialString(in_map: m_alias_dict, cmd_str: cmd, matches);
1411 if (num_alias_matches == 1) {
1412 // Make sure this isn't shadowing a command in the regular command space:
1413 StringList regular_matches;
1414 const bool include_aliases = false;
1415 const bool exact = false;
1416 CommandObjectSP cmd_obj_sp(
1417 GetCommandSP(cmd_str: cmd, include_aliases, exact, matches: &regular_matches));
1418 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1419 return false;
1420 else {
1421 full_name.assign(s: matches.GetStringAtIndex(idx: 0));
1422 return true;
1423 }
1424 } else
1425 return false;
1426 }
1427}
1428
1429bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
1430 return m_alias_dict.find(x: cmd) != m_alias_dict.end();
1431}
1432
1433bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
1434 return m_user_dict.find(x: cmd) != m_user_dict.end();
1435}
1436
1437bool CommandInterpreter::UserMultiwordCommandExists(llvm::StringRef cmd) const {
1438 return m_user_mw_dict.find(x: cmd) != m_user_mw_dict.end();
1439}
1440
1441CommandAlias *
1442CommandInterpreter::AddAlias(llvm::StringRef alias_name,
1443 lldb::CommandObjectSP &command_obj_sp,
1444 llvm::StringRef args_string) {
1445 if (command_obj_sp.get())
1446 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1447 "tried to add a CommandObject from a different interpreter");
1448
1449 std::unique_ptr<CommandAlias> command_alias_up(
1450 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1451
1452 if (command_alias_up && command_alias_up->IsValid()) {
1453 m_alias_dict[std::string(alias_name)] =
1454 CommandObjectSP(command_alias_up.get());
1455 return command_alias_up.release();
1456 }
1457
1458 return nullptr;
1459}
1460
1461bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
1462 auto pos = m_alias_dict.find(x: alias_name);
1463 if (pos != m_alias_dict.end()) {
1464 m_alias_dict.erase(position: pos);
1465 return true;
1466 }
1467 return false;
1468}
1469
1470bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd, bool force) {
1471 auto pos = m_command_dict.find(x: cmd);
1472 if (pos != m_command_dict.end()) {
1473 if (force || pos->second->IsRemovable()) {
1474 // Only regular expression objects or python commands are removable under
1475 // normal circumstances.
1476 m_command_dict.erase(position: pos);
1477 return true;
1478 }
1479 }
1480 return false;
1481}
1482
1483bool CommandInterpreter::RemoveUser(llvm::StringRef user_name) {
1484 CommandObject::CommandMap::iterator pos = m_user_dict.find(x: user_name);
1485 if (pos != m_user_dict.end()) {
1486 m_user_dict.erase(position: pos);
1487 return true;
1488 }
1489 return false;
1490}
1491
1492bool CommandInterpreter::RemoveUserMultiword(llvm::StringRef multi_name) {
1493 CommandObject::CommandMap::iterator pos = m_user_mw_dict.find(x: multi_name);
1494 if (pos != m_user_mw_dict.end()) {
1495 m_user_mw_dict.erase(position: pos);
1496 return true;
1497 }
1498 return false;
1499}
1500
1501void CommandInterpreter::GetHelp(CommandReturnObject &result,
1502 uint32_t cmd_types) {
1503 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1504 if (!help_prologue.empty()) {
1505 OutputFormattedHelpText(strm&: result.GetOutputStream(), prefix: llvm::StringRef(),
1506 help_text: help_prologue);
1507 }
1508
1509 CommandObject::CommandMap::const_iterator pos;
1510 size_t max_len = FindLongestCommandWord(dict&: m_command_dict);
1511
1512 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1513 result.AppendMessage(in_string: "Debugger commands:");
1514 result.AppendMessage(in_string: "");
1515
1516 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1517 if (!(cmd_types & eCommandTypesHidden) &&
1518 (pos->first.compare(pos: 0, n1: 1, s: "_") == 0))
1519 continue;
1520
1521 OutputFormattedHelpText(stream&: result.GetOutputStream(), command_word: pos->first, separator: "--",
1522 help_text: pos->second->GetHelp(), max_word_len: max_len);
1523 }
1524 result.AppendMessage(in_string: "");
1525 }
1526
1527 if (!m_alias_dict.empty() &&
1528 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1529 result.AppendMessageWithFormat(
1530 format: "Current command abbreviations "
1531 "(type '%shelp command alias' for more info):\n",
1532 GetCommandPrefix());
1533 result.AppendMessage(in_string: "");
1534 max_len = FindLongestCommandWord(dict&: m_alias_dict);
1535
1536 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1537 ++alias_pos) {
1538 OutputFormattedHelpText(stream&: result.GetOutputStream(), command_word: alias_pos->first, separator: "--",
1539 help_text: alias_pos->second->GetHelp(), max_word_len: max_len);
1540 }
1541 result.AppendMessage(in_string: "");
1542 }
1543
1544 if (!m_user_dict.empty() &&
1545 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1546 result.AppendMessage(in_string: "Current user-defined commands:");
1547 result.AppendMessage(in_string: "");
1548 max_len = FindLongestCommandWord(dict&: m_user_dict);
1549 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
1550 OutputFormattedHelpText(stream&: result.GetOutputStream(), command_word: pos->first, separator: "--",
1551 help_text: pos->second->GetHelp(), max_word_len: max_len);
1552 }
1553 result.AppendMessage(in_string: "");
1554 }
1555
1556 if (!m_user_mw_dict.empty() &&
1557 ((cmd_types & eCommandTypesUserMW) == eCommandTypesUserMW)) {
1558 result.AppendMessage(in_string: "Current user-defined container commands:");
1559 result.AppendMessage(in_string: "");
1560 max_len = FindLongestCommandWord(dict&: m_user_mw_dict);
1561 for (pos = m_user_mw_dict.begin(); pos != m_user_mw_dict.end(); ++pos) {
1562 OutputFormattedHelpText(stream&: result.GetOutputStream(), command_word: pos->first, separator: "--",
1563 help_text: pos->second->GetHelp(), max_word_len: max_len);
1564 }
1565 result.AppendMessage(in_string: "");
1566 }
1567
1568 result.AppendMessageWithFormat(
1569 format: "For more information on any command, type '%shelp <command-name>'.\n",
1570 GetCommandPrefix());
1571}
1572
1573CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1574 llvm::StringRef &command_string) {
1575 // This function finds the final, lowest-level, alias-resolved command object
1576 // whose 'Execute' function will eventually be invoked by the given command
1577 // line.
1578
1579 CommandObject *cmd_obj = nullptr;
1580 size_t start = command_string.find_first_not_of(Chars: k_white_space);
1581 size_t end = 0;
1582 bool done = false;
1583 while (!done) {
1584 if (start != std::string::npos) {
1585 // Get the next word from command_string.
1586 end = command_string.find_first_of(Chars: k_white_space, From: start);
1587 if (end == std::string::npos)
1588 end = command_string.size();
1589 std::string cmd_word =
1590 std::string(command_string.substr(Start: start, N: end - start));
1591
1592 if (cmd_obj == nullptr)
1593 // Since cmd_obj is NULL we are on our first time through this loop.
1594 // Check to see if cmd_word is a valid command or alias.
1595 cmd_obj = GetCommandObject(cmd_str: cmd_word);
1596 else if (cmd_obj->IsMultiwordObject()) {
1597 // Our current object is a multi-word object; see if the cmd_word is a
1598 // valid sub-command for our object.
1599 CommandObject *sub_cmd_obj =
1600 cmd_obj->GetSubcommandObject(sub_cmd: cmd_word.c_str());
1601 if (sub_cmd_obj)
1602 cmd_obj = sub_cmd_obj;
1603 else // cmd_word was not a valid sub-command word, so we are done
1604 done = true;
1605 } else
1606 // We have a cmd_obj and it is not a multi-word object, so we are done.
1607 done = true;
1608
1609 // If we didn't find a valid command object, or our command object is not
1610 // a multi-word object, or we are at the end of the command_string, then
1611 // we are done. Otherwise, find the start of the next word.
1612
1613 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1614 end >= command_string.size())
1615 done = true;
1616 else
1617 start = command_string.find_first_not_of(Chars: k_white_space, From: end);
1618 } else
1619 // Unable to find any more words.
1620 done = true;
1621 }
1622
1623 command_string = command_string.substr(Start: end);
1624 return cmd_obj;
1625}
1626
1627static const char *k_valid_command_chars =
1628 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1629static void StripLeadingSpaces(std::string &s) {
1630 if (!s.empty()) {
1631 size_t pos = s.find_first_not_of(s: k_white_space);
1632 if (pos == std::string::npos)
1633 s.clear();
1634 else if (pos == 0)
1635 return;
1636 s.erase(pos: 0, n: pos);
1637 }
1638}
1639
1640static size_t FindArgumentTerminator(const std::string &s) {
1641 const size_t s_len = s.size();
1642 size_t offset = 0;
1643 while (offset < s_len) {
1644 size_t pos = s.find(s: "--", pos: offset);
1645 if (pos == std::string::npos)
1646 break;
1647 if (pos > 0) {
1648 if (llvm::isSpace(C: s[pos - 1])) {
1649 // Check if the string ends "\s--" (where \s is a space character) or
1650 // if we have "\s--\s".
1651 if ((pos + 2 >= s_len) || llvm::isSpace(C: s[pos + 2])) {
1652 return pos;
1653 }
1654 }
1655 }
1656 offset = pos + 2;
1657 }
1658 return std::string::npos;
1659}
1660
1661static bool ExtractCommand(std::string &command_string, std::string &command,
1662 std::string &suffix, char &quote_char) {
1663 command.clear();
1664 suffix.clear();
1665 StripLeadingSpaces(s&: command_string);
1666
1667 bool result = false;
1668 quote_char = '\0';
1669
1670 if (!command_string.empty()) {
1671 const char first_char = command_string[0];
1672 if (first_char == '\'' || first_char == '"') {
1673 quote_char = first_char;
1674 const size_t end_quote_pos = command_string.find(c: quote_char, pos: 1);
1675 if (end_quote_pos == std::string::npos) {
1676 command.swap(s&: command_string);
1677 command_string.erase();
1678 } else {
1679 command.assign(str: command_string, pos: 1, n: end_quote_pos - 1);
1680 if (end_quote_pos + 1 < command_string.size())
1681 command_string.erase(pos: 0, n: command_string.find_first_not_of(
1682 s: k_white_space, pos: end_quote_pos + 1));
1683 else
1684 command_string.erase();
1685 }
1686 } else {
1687 const size_t first_space_pos =
1688 command_string.find_first_of(s: k_white_space);
1689 if (first_space_pos == std::string::npos) {
1690 command.swap(s&: command_string);
1691 command_string.erase();
1692 } else {
1693 command.assign(str: command_string, pos: 0, n: first_space_pos);
1694 command_string.erase(pos: 0, n: command_string.find_first_not_of(
1695 s: k_white_space, pos: first_space_pos));
1696 }
1697 }
1698 result = true;
1699 }
1700
1701 if (!command.empty()) {
1702 // actual commands can't start with '-' or '_'
1703 if (command[0] != '-' && command[0] != '_') {
1704 size_t pos = command.find_first_not_of(s: k_valid_command_chars);
1705 if (pos > 0 && pos != std::string::npos) {
1706 suffix.assign(first: command.begin() + pos, last: command.end());
1707 command.erase(pos: pos);
1708 }
1709 }
1710 }
1711
1712 return result;
1713}
1714
1715CommandObject *CommandInterpreter::BuildAliasResult(
1716 llvm::StringRef alias_name, std::string &raw_input_string,
1717 std::string &alias_result, CommandReturnObject &result) {
1718 CommandObject *alias_cmd_obj = nullptr;
1719 Args cmd_args(raw_input_string);
1720 alias_cmd_obj = GetCommandObject(cmd_str: alias_name);
1721 StreamString result_str;
1722
1723 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1724 alias_result.clear();
1725 return alias_cmd_obj;
1726 }
1727 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1728 ((CommandAlias *)alias_cmd_obj)->Desugar();
1729 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1730 alias_cmd_obj = desugared.first.get();
1731 std::string alias_name_str = std::string(alias_name);
1732 if ((cmd_args.GetArgumentCount() == 0) ||
1733 (alias_name_str != cmd_args.GetArgumentAtIndex(idx: 0)))
1734 cmd_args.Unshift(arg_str: alias_name_str);
1735
1736 result_str.Printf(format: "%s", alias_cmd_obj->GetCommandName().str().c_str());
1737
1738 if (!option_arg_vector_sp.get()) {
1739 alias_result = std::string(result_str.GetString());
1740 return alias_cmd_obj;
1741 }
1742 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1743
1744 int value_type;
1745 std::string option;
1746 std::string value;
1747 for (const auto &entry : *option_arg_vector) {
1748 std::tie(args&: option, args&: value_type, args&: value) = entry;
1749 if (option == g_argument) {
1750 result_str.Printf(format: " %s", value.c_str());
1751 continue;
1752 }
1753
1754 result_str.Printf(format: " %s", option.c_str());
1755 if (value_type == OptionParser::eNoArgument)
1756 continue;
1757
1758 if (value_type != OptionParser::eOptionalArgument)
1759 result_str.Printf(format: " ");
1760 int index = GetOptionArgumentPosition(in_string: value.c_str());
1761 if (index == 0)
1762 result_str.Printf(format: "%s", value.c_str());
1763 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1764
1765 result.AppendErrorWithFormat(format: "Not enough arguments provided; you "
1766 "need at least %d arguments to use "
1767 "this alias.\n",
1768 index);
1769 return nullptr;
1770 } else {
1771 const Args::ArgEntry &entry = cmd_args[index];
1772 size_t strpos = raw_input_string.find(s: entry.c_str());
1773 const char quote_char = entry.GetQuoteChar();
1774 if (strpos != std::string::npos) {
1775 const size_t start_fudge = quote_char == '\0' ? 0 : 1;
1776 const size_t len_fudge = quote_char == '\0' ? 0 : 2;
1777
1778 // Make sure we aren't going outside the bounds of the cmd string:
1779 if (strpos < start_fudge) {
1780 result.AppendError(in_string: "Unmatched quote at command beginning.");
1781 return nullptr;
1782 }
1783 llvm::StringRef arg_text = entry.ref();
1784 if (strpos - start_fudge + arg_text.size() + len_fudge >
1785 raw_input_string.size()) {
1786 result.AppendError(in_string: "Unmatched quote at command end.");
1787 return nullptr;
1788 }
1789 raw_input_string = raw_input_string.erase(
1790 pos: strpos - start_fudge,
1791 n: strlen(s: cmd_args.GetArgumentAtIndex(idx: index)) + len_fudge);
1792 }
1793 if (quote_char == '\0')
1794 result_str.Printf(format: "%s", cmd_args.GetArgumentAtIndex(idx: index));
1795 else
1796 result_str.Printf(format: "%c%s%c", quote_char, entry.c_str(), quote_char);
1797 }
1798 }
1799
1800 alias_result = std::string(result_str.GetString());
1801 return alias_cmd_obj;
1802}
1803
1804Status CommandInterpreter::PreprocessCommand(std::string &command) {
1805 // The command preprocessor needs to do things to the command line before any
1806 // parsing of arguments or anything else is done. The only current stuff that
1807 // gets preprocessed is anything enclosed in backtick ('`') characters is
1808 // evaluated as an expression and the result of the expression must be a
1809 // scalar that can be substituted into the command. An example would be:
1810 // (lldb) memory read `$rsp + 20`
1811 Status error; // Status for any expressions that might not evaluate
1812 size_t start_backtick;
1813 size_t pos = 0;
1814 while ((start_backtick = command.find(c: '`', pos: pos)) != std::string::npos) {
1815 // Stop if an error was encountered during the previous iteration.
1816 if (error.Fail())
1817 break;
1818
1819 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
1820 // The backtick was preceded by a '\' character, remove the slash and
1821 // don't treat the backtick as the start of an expression.
1822 command.erase(pos: start_backtick - 1, n: 1);
1823 // No need to add one to start_backtick since we just deleted a char.
1824 pos = start_backtick;
1825 continue;
1826 }
1827
1828 const size_t expr_content_start = start_backtick + 1;
1829 const size_t end_backtick = command.find(c: '`', pos: expr_content_start);
1830
1831 if (end_backtick == std::string::npos) {
1832 // Stop if there's no end backtick.
1833 break;
1834 }
1835
1836 if (end_backtick == expr_content_start) {
1837 // Skip over empty expression. (two backticks in a row)
1838 command.erase(pos: start_backtick, n: 2);
1839 continue;
1840 }
1841
1842 std::string expr_str(command, expr_content_start,
1843 end_backtick - expr_content_start);
1844 error = PreprocessToken(token&: expr_str);
1845 // We always stop at the first error:
1846 if (error.Fail())
1847 break;
1848
1849 command.erase(pos: start_backtick, n: end_backtick - start_backtick + 1);
1850 command.insert(pos1: start_backtick, str: std::string(expr_str));
1851 pos = start_backtick + expr_str.size();
1852 }
1853 return error;
1854}
1855
1856Status CommandInterpreter::PreprocessToken(std::string &expr_str) {
1857 Status error;
1858 ExecutionContext exe_ctx(GetExecutionContext());
1859
1860 // Get a dummy target to allow for calculator mode while processing
1861 // backticks. This also helps break the infinite loop caused when target is
1862 // null.
1863 Target *exe_target = exe_ctx.GetTargetPtr();
1864 Target &target = exe_target ? *exe_target : m_debugger.GetDummyTarget();
1865
1866 ValueObjectSP expr_result_valobj_sp;
1867
1868 EvaluateExpressionOptions options;
1869 options.SetCoerceToId(false);
1870 options.SetUnwindOnError(true);
1871 options.SetIgnoreBreakpoints(true);
1872 options.SetKeepInMemory(false);
1873 options.SetTryAllThreads(true);
1874 options.SetTimeout(std::nullopt);
1875
1876 ExpressionResults expr_result = target.EvaluateExpression(
1877 expression: expr_str.c_str(), exe_scope: exe_ctx.GetFramePtr(), result_valobj_sp&: expr_result_valobj_sp, options);
1878
1879 if (expr_result == eExpressionCompleted) {
1880 Scalar scalar;
1881 if (expr_result_valobj_sp)
1882 expr_result_valobj_sp =
1883 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1884 dynValue: expr_result_valobj_sp->GetDynamicValueType(), synthValue: true);
1885 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1886
1887 StreamString value_strm;
1888 const bool show_type = false;
1889 scalar.GetValue(s&: value_strm, show_type);
1890 size_t value_string_size = value_strm.GetSize();
1891 if (value_string_size) {
1892 expr_str = value_strm.GetData();
1893 } else {
1894 error =
1895 Status::FromErrorStringWithFormat(format: "expression value didn't result "
1896 "in a scalar value for the "
1897 "expression '%s'",
1898 expr_str.c_str());
1899 }
1900 } else {
1901 error =
1902 Status::FromErrorStringWithFormat(format: "expression value didn't result "
1903 "in a scalar value for the "
1904 "expression '%s'",
1905 expr_str.c_str());
1906 }
1907 return error;
1908 }
1909
1910 // If we have an error from the expression evaluation it will be in the
1911 // ValueObject error, which won't be success and we will just report it.
1912 // But if for some reason we didn't get a value object at all, then we will
1913 // make up some helpful errors from the expression result.
1914 if (expr_result_valobj_sp)
1915 error = expr_result_valobj_sp->GetError().Clone();
1916
1917 if (error.Success()) {
1918 std::string result = lldb_private::toString(e: expr_result) +
1919 "for the expression '" + expr_str + "'";
1920 error = Status(result);
1921 }
1922 return error;
1923}
1924
1925bool CommandInterpreter::HandleCommand(const char *command_line,
1926 LazyBool lazy_add_to_history,
1927 const ExecutionContext &override_context,
1928 CommandReturnObject &result) {
1929
1930 OverrideExecutionContext(override_context);
1931 bool status = HandleCommand(command_line, add_to_history: lazy_add_to_history, result);
1932 RestoreExecutionContext();
1933 return status;
1934}
1935
1936bool CommandInterpreter::HandleCommand(const char *command_line,
1937 LazyBool lazy_add_to_history,
1938 CommandReturnObject &result,
1939 bool force_repeat_command) {
1940 // These are assigned later in the function but they must be declared before
1941 // the ScopedDispatcher object because we need their destructions to occur
1942 // after the dispatcher's dtor call, which may reference them.
1943 // TODO: This function could be refactored?
1944 std::string parsed_command_args;
1945 CommandObject *cmd_obj = nullptr;
1946
1947 telemetry::ScopedDispatcher<telemetry::CommandInfo> helper(&m_debugger);
1948 const bool detailed_command_telemetry =
1949 telemetry::TelemetryManager::GetInstance()
1950 ->GetConfig()
1951 ->detailed_command_telemetry;
1952 const int command_id = telemetry::CommandInfo::GetNextID();
1953
1954 std::string command_string(command_line);
1955 std::string original_command_string(command_string);
1956 std::string real_original_command_string(command_string);
1957
1958 helper.DispatchNow(populate_fields_cb: [&](lldb_private::telemetry::CommandInfo *info) {
1959 info->command_id = command_id;
1960 if (Target *target = GetExecutionContext().GetTargetPtr()) {
1961 // If we have a target attached to this command, then get the UUID.
1962 info->target_uuid = target->GetExecutableModule() != nullptr
1963 ? target->GetExecutableModule()->GetUUID()
1964 : UUID();
1965 }
1966 if (detailed_command_telemetry)
1967 info->original_command = original_command_string;
1968 // The rest (eg., command_name, args, etc) hasn't been parsed yet;
1969 // Those will be collected by the on-exit-callback.
1970 });
1971
1972 helper.DispatchOnExit(final_callback: [&cmd_obj, &parsed_command_args, &result,
1973 detailed_command_telemetry, command_id](
1974 lldb_private::telemetry::CommandInfo *info) {
1975 // TODO: this is logging the time the command-handler finishes.
1976 // But we may want a finer-grain durations too?
1977 // (ie., the execute_time recorded below?)
1978 info->command_id = command_id;
1979 llvm::StringRef command_name =
1980 cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1981 info->command_name = command_name.str();
1982 info->ret_status = result.GetStatus();
1983 if (std::string error_str = result.GetErrorString(); !error_str.empty())
1984 info->error_data = std::move(error_str);
1985
1986 if (detailed_command_telemetry)
1987 info->args = parsed_command_args;
1988 });
1989
1990 Log *log = GetLog(mask: LLDBLog::Commands);
1991 LLDB_LOGF(log, "Processing command: %s", command_line);
1992 LLDB_SCOPED_TIMERF("Processing command: %s.", command_line);
1993
1994 // Set the command in the CommandReturnObject here so that it's there even if
1995 // the command is interrupted.
1996 result.SetCommand(command_line);
1997
1998 if (INTERRUPT_REQUESTED(GetDebugger(), "Interrupted initiating command")) {
1999 result.AppendError(in_string: "... Interrupted");
2000 return false;
2001 }
2002
2003 bool add_to_history;
2004 if (lazy_add_to_history == eLazyBoolCalculate)
2005 add_to_history = (m_command_source_depth == 0);
2006 else
2007 add_to_history = (lazy_add_to_history == eLazyBoolYes);
2008
2009 // The same `transcript_item` will be used below to add output and error of
2010 // the command.
2011 StructuredData::DictionarySP transcript_item;
2012 if (GetSaveTranscript()) {
2013 m_transcript_stream << "(lldb) " << command_line << '\n';
2014
2015 transcript_item = std::make_shared<StructuredData::Dictionary>();
2016 transcript_item->AddStringItem(key: "command", value: command_line);
2017 transcript_item->AddIntegerItem(
2018 key: "timestampInEpochSeconds",
2019 value: std::chrono::duration_cast<std::chrono::seconds>(
2020 d: std::chrono::system_clock::now().time_since_epoch())
2021 .count());
2022 m_transcript.AddItem(item: transcript_item);
2023 }
2024
2025 bool empty_command = false;
2026 bool comment_command = false;
2027 if (command_string.empty())
2028 empty_command = true;
2029 else {
2030 const char *k_space_characters = "\t\n\v\f\r ";
2031
2032 size_t non_space = command_string.find_first_not_of(s: k_space_characters);
2033 // Check for empty line or comment line (lines whose first non-space
2034 // character is the comment character for this interpreter)
2035 if (non_space == std::string::npos)
2036 empty_command = true;
2037 else if (command_string[non_space] == m_comment_char)
2038 comment_command = true;
2039 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
2040 llvm::StringRef search_str(command_string);
2041 search_str = search_str.drop_front(N: non_space);
2042 if (auto hist_str = m_command_history.FindString(input_str: search_str)) {
2043 add_to_history = false;
2044 command_string = std::string(*hist_str);
2045 original_command_string = std::string(*hist_str);
2046 } else {
2047 result.AppendErrorWithFormat(format: "Could not find entry: %s in history",
2048 command_string.c_str());
2049 return false;
2050 }
2051 }
2052 }
2053
2054 if (empty_command) {
2055 if (!GetRepeatPreviousCommand()) {
2056 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2057 return true;
2058 }
2059
2060 if (m_command_history.IsEmpty()) {
2061 result.AppendError(in_string: "empty command");
2062 return false;
2063 }
2064
2065 command_line = m_repeat_command.c_str();
2066 command_string = command_line;
2067 original_command_string = command_line;
2068 if (m_repeat_command.empty()) {
2069 result.AppendError(in_string: "No auto repeat.");
2070 return false;
2071 }
2072
2073 add_to_history = false;
2074 } else if (comment_command) {
2075 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2076 return true;
2077 }
2078
2079 // Phase 1.
2080
2081 // Before we do ANY kind of argument processing, we need to figure out what
2082 // the real/final command object is for the specified command. This gets
2083 // complicated by the fact that the user could have specified an alias, and,
2084 // in translating the alias, there may also be command options and/or even
2085 // data (including raw text strings) that need to be found and inserted into
2086 // the command line as part of the translation. So this first step is plain
2087 // look-up and replacement, resulting in:
2088 // 1. the command object whose Execute method will actually be called
2089 // 2. a revised command string, with all substitutions and replacements
2090 // taken care of
2091 // From 1 above, we can determine whether the Execute function wants raw
2092 // input or not.
2093
2094 cmd_obj = ResolveCommandImpl(command_line&: command_string, result);
2095
2096 // We have to preprocess the whole command string for Raw commands, since we
2097 // don't know the structure of the command. For parsed commands, we only
2098 // treat backticks as quote characters specially.
2099 // FIXME: We probably want to have raw commands do their own preprocessing.
2100 // For instance, I don't think people expect substitution in expr expressions.
2101 if (cmd_obj && cmd_obj->WantsRawCommandString()) {
2102 Status error(PreprocessCommand(command&: command_string));
2103
2104 if (error.Fail()) {
2105 result.AppendError(in_string: error.AsCString());
2106 return false;
2107 }
2108 }
2109
2110 // Although the user may have abbreviated the command, the command_string now
2111 // has the command expanded to the full name. For example, if the input was
2112 // "br s -n main", command_string is now "breakpoint set -n main".
2113 if (log) {
2114 llvm::StringRef command_name =
2115 cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
2116 LLDB_LOGF(log, "HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
2117 LLDB_LOGF(log, "HandleCommand, (revised) command_string: '%s'",
2118 command_string.c_str());
2119 const bool wants_raw_input =
2120 (cmd_obj != nullptr) ? cmd_obj->WantsRawCommandString() : false;
2121 LLDB_LOGF(log, "HandleCommand, wants_raw_input:'%s'",
2122 wants_raw_input ? "True" : "False");
2123 }
2124
2125 // Phase 2.
2126 // Take care of things like setting up the history command & calling the
2127 // appropriate Execute method on the CommandObject, with the appropriate
2128 // arguments.
2129 StatsDuration execute_time;
2130 if (cmd_obj != nullptr) {
2131 bool generate_repeat_command = add_to_history;
2132 // If we got here when empty_command was true, then this command is a
2133 // stored "repeat command" which we should give a chance to produce it's
2134 // repeat command, even though we don't add repeat commands to the history.
2135 generate_repeat_command |= empty_command;
2136 // For `command regex`, the regex command (ex `bt`) is added to history, but
2137 // the resolved command (ex `thread backtrace`) is _not_ added to history.
2138 // However, the resolved command must be given the opportunity to provide a
2139 // repeat command. `force_repeat_command` supports this case.
2140 generate_repeat_command |= force_repeat_command;
2141 if (generate_repeat_command) {
2142 Args command_args(command_string);
2143 std::optional<std::string> repeat_command =
2144 cmd_obj->GetRepeatCommand(current_command_args&: command_args, index: 0);
2145 if (repeat_command) {
2146 LLDB_LOGF(log, "Repeat command: %s", repeat_command->data());
2147 m_repeat_command.assign(str: *repeat_command);
2148 } else {
2149 m_repeat_command.assign(str: original_command_string);
2150 }
2151 }
2152
2153 if (add_to_history)
2154 m_command_history.AppendString(str: original_command_string);
2155
2156 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
2157 if (actual_cmd_name_len < command_string.length())
2158 parsed_command_args = command_string.substr(pos: actual_cmd_name_len);
2159
2160 // Remove any initial spaces
2161 size_t pos = parsed_command_args.find_first_not_of(s: k_white_space);
2162 if (pos != 0 && pos != std::string::npos)
2163 parsed_command_args.erase(pos: 0, n: pos);
2164
2165 LLDB_LOGF(
2166 log, "HandleCommand, command line after removing command name(s): '%s'",
2167 parsed_command_args.c_str());
2168
2169 // To test whether or not transcript should be saved, `transcript_item` is
2170 // used instead of `GetSaveTranscript()`. This is because the latter will
2171 // fail when the command is "settings set interpreter.save-transcript true".
2172 if (transcript_item) {
2173 transcript_item->AddStringItem(key: "commandName", value: cmd_obj->GetCommandName());
2174 transcript_item->AddStringItem(key: "commandArguments", value: parsed_command_args);
2175 }
2176
2177 ElapsedTime elapsed(execute_time);
2178 cmd_obj->SetOriginalCommandString(real_original_command_string);
2179 // Set the indent to the position of the command in the command line.
2180 pos = real_original_command_string.rfind(str: parsed_command_args);
2181 std::optional<uint16_t> indent;
2182 if (pos != std::string::npos)
2183 indent = pos;
2184 result.SetDiagnosticIndent(indent);
2185 cmd_obj->Execute(args_string: parsed_command_args.c_str(), result);
2186 }
2187
2188 LLDB_LOGF(log, "HandleCommand, command %s",
2189 (result.Succeeded() ? "succeeded" : "did not succeed"));
2190
2191 // To test whether or not transcript should be saved, `transcript_item` is
2192 // used instead of `GetSaveTrasncript()`. This is because the latter will
2193 // fail when the command is "settings set interpreter.save-transcript true".
2194 if (transcript_item) {
2195 m_transcript_stream << result.GetOutputString();
2196 m_transcript_stream << result.GetErrorString();
2197
2198 transcript_item->AddStringItem(key: "output", value: result.GetOutputString());
2199 transcript_item->AddStringItem(key: "error", value: result.GetErrorString());
2200 transcript_item->AddFloatItem(key: "durationInSeconds",
2201 value: execute_time.get().count());
2202 }
2203
2204 return result.Succeeded();
2205}
2206
2207void CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
2208 bool look_for_subcommand = false;
2209
2210 // For any of the command completions a unique match will be a complete word.
2211
2212 if (request.GetParsedLine().GetArgumentCount() == 0) {
2213 // We got nothing on the command line, so return the list of commands
2214 bool include_aliases = true;
2215 StringList new_matches, descriptions;
2216 GetCommandNamesMatchingPartialString(cmd_str: "", include_aliases, matches&: new_matches,
2217 descriptions);
2218 request.AddCompletions(completions: new_matches, descriptions);
2219 } else if (request.GetCursorIndex() == 0) {
2220 // The cursor is in the first argument, so just do a lookup in the
2221 // dictionary.
2222 StringList new_matches, new_descriptions;
2223 CommandObject *cmd_obj =
2224 GetCommandObject(cmd_str: request.GetParsedLine().GetArgumentAtIndex(idx: 0),
2225 matches: &new_matches, descriptions: &new_descriptions);
2226
2227 if (new_matches.GetSize() && cmd_obj && cmd_obj->IsMultiwordObject() &&
2228 new_matches.GetStringAtIndex(idx: 0) != nullptr &&
2229 strcmp(s1: request.GetParsedLine().GetArgumentAtIndex(idx: 0),
2230 s2: new_matches.GetStringAtIndex(idx: 0)) == 0) {
2231 if (request.GetParsedLine().GetArgumentCount() != 1) {
2232 look_for_subcommand = true;
2233 new_matches.DeleteStringAtIndex(id: 0);
2234 new_descriptions.DeleteStringAtIndex(id: 0);
2235 request.AppendEmptyArgument();
2236 }
2237 }
2238 request.AddCompletions(completions: new_matches, descriptions: new_descriptions);
2239 }
2240
2241 if (request.GetCursorIndex() > 0 || look_for_subcommand) {
2242 // We are completing further on into a commands arguments, so find the
2243 // command and tell it to complete the command. First see if there is a
2244 // matching initial command:
2245 CommandObject *command_object =
2246 GetCommandObject(cmd_str: request.GetParsedLine().GetArgumentAtIndex(idx: 0));
2247 if (command_object) {
2248 request.ShiftArguments();
2249 command_object->HandleCompletion(request);
2250 }
2251 }
2252}
2253
2254void CommandInterpreter::HandleCompletion(CompletionRequest &request) {
2255
2256 // Don't complete comments, and if the line we are completing is just the
2257 // history repeat character, substitute the appropriate history line.
2258 llvm::StringRef first_arg = request.GetParsedLine().GetArgumentAtIndex(idx: 0);
2259
2260 if (!first_arg.empty()) {
2261 if (first_arg.front() == m_comment_char)
2262 return;
2263 if (first_arg.front() == CommandHistory::g_repeat_char) {
2264 if (auto hist_str = m_command_history.FindString(input_str: first_arg))
2265 request.AddCompletion(completion: *hist_str, description: "Previous command history event",
2266 mode: CompletionMode::RewriteLine);
2267 return;
2268 }
2269 }
2270
2271 HandleCompletionMatches(request);
2272}
2273
2274std::optional<std::string>
2275CommandInterpreter::GetAutoSuggestionForCommand(llvm::StringRef line) {
2276 if (line.empty())
2277 return std::nullopt;
2278 const size_t s = m_command_history.GetSize();
2279 for (int i = s - 1; i >= 0; --i) {
2280 llvm::StringRef entry = m_command_history.GetStringAtIndex(idx: i);
2281 if (entry.consume_front(Prefix: line))
2282 return entry.str();
2283 }
2284 return std::nullopt;
2285}
2286
2287void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
2288 EventSP prompt_change_event_sp(
2289 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
2290
2291 BroadcastEvent(event_sp&: prompt_change_event_sp);
2292 if (m_command_io_handler_sp)
2293 m_command_io_handler_sp->SetPrompt(new_prompt);
2294}
2295
2296void CommandInterpreter::UpdateUseColor(bool use_color) {
2297 if (m_command_io_handler_sp)
2298 m_command_io_handler_sp->SetUseColor(use_color);
2299}
2300
2301bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
2302 // Check AutoConfirm first:
2303 if (m_debugger.GetAutoConfirm())
2304 return default_answer;
2305
2306 IOHandlerConfirm *confirm =
2307 new IOHandlerConfirm(m_debugger, message, default_answer);
2308 IOHandlerSP io_handler_sp(confirm);
2309 m_debugger.RunIOHandlerSync(reader_sp: io_handler_sp);
2310 return confirm->GetResponse();
2311}
2312
2313const CommandAlias *
2314CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
2315 OptionArgVectorSP ret_val;
2316
2317 auto pos = m_alias_dict.find(x: alias_name);
2318 if (pos != m_alias_dict.end())
2319 return (CommandAlias *)pos->second.get();
2320
2321 return nullptr;
2322}
2323
2324bool CommandInterpreter::HasCommands() const {
2325 return (!m_command_dict.empty());
2326}
2327
2328bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
2329
2330bool CommandInterpreter::HasUserCommands() const {
2331 return (!m_user_dict.empty());
2332}
2333
2334bool CommandInterpreter::HasUserMultiwordCommands() const {
2335 return (!m_user_mw_dict.empty());
2336}
2337
2338bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
2339
2340void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
2341 const char *alias_name,
2342 Args &cmd_args,
2343 std::string &raw_input_string,
2344 CommandReturnObject &result) {
2345 OptionArgVectorSP option_arg_vector_sp =
2346 GetAlias(alias_name)->GetOptionArguments();
2347
2348 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
2349
2350 // Make sure that the alias name is the 0th element in cmd_args
2351 std::string alias_name_str = alias_name;
2352 if (alias_name_str != cmd_args.GetArgumentAtIndex(idx: 0))
2353 cmd_args.Unshift(arg_str: alias_name_str);
2354
2355 Args new_args(alias_cmd_obj->GetCommandName());
2356 if (new_args.GetArgumentCount() == 2)
2357 new_args.Shift();
2358
2359 if (option_arg_vector_sp.get()) {
2360 if (wants_raw_input) {
2361 // We have a command that both has command options and takes raw input.
2362 // Make *sure* it has a " -- " in the right place in the
2363 // raw_input_string.
2364 size_t pos = raw_input_string.find(s: " -- ");
2365 if (pos == std::string::npos) {
2366 // None found; assume it goes at the beginning of the raw input string
2367 raw_input_string.insert(pos: 0, s: " -- ");
2368 }
2369 }
2370
2371 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2372 const size_t old_size = cmd_args.GetArgumentCount();
2373 std::vector<bool> used(old_size + 1, false);
2374
2375 used[0] = true;
2376
2377 int value_type;
2378 std::string option;
2379 std::string value;
2380 for (const auto &option_entry : *option_arg_vector) {
2381 std::tie(args&: option, args&: value_type, args&: value) = option_entry;
2382 if (option == g_argument) {
2383 if (!wants_raw_input || (value != "--")) {
2384 // Since we inserted this above, make sure we don't insert it twice
2385 new_args.AppendArgument(arg_str: value);
2386 }
2387 continue;
2388 }
2389
2390 if (value_type != OptionParser::eOptionalArgument)
2391 new_args.AppendArgument(arg_str: option);
2392
2393 if (value == g_no_argument)
2394 continue;
2395
2396 int index = GetOptionArgumentPosition(in_string: value.c_str());
2397 if (index == 0) {
2398 // value was NOT a positional argument; must be a real value
2399 if (value_type != OptionParser::eOptionalArgument)
2400 new_args.AppendArgument(arg_str: value);
2401 else {
2402 new_args.AppendArgument(arg_str: option + value);
2403 }
2404
2405 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
2406 result.AppendErrorWithFormat(format: "Not enough arguments provided; you "
2407 "need at least %d arguments to use "
2408 "this alias.\n",
2409 index);
2410 return;
2411 } else {
2412 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2413 size_t strpos =
2414 raw_input_string.find(s: cmd_args.GetArgumentAtIndex(idx: index));
2415 if (strpos != std::string::npos) {
2416 raw_input_string = raw_input_string.erase(
2417 pos: strpos, n: strlen(s: cmd_args.GetArgumentAtIndex(idx: index)));
2418 }
2419
2420 if (value_type != OptionParser::eOptionalArgument)
2421 new_args.AppendArgument(arg_str: cmd_args.GetArgumentAtIndex(idx: index));
2422 else {
2423 new_args.AppendArgument(arg_str: option + cmd_args.GetArgumentAtIndex(idx: index));
2424 }
2425 used[index] = true;
2426 }
2427 }
2428
2429 for (auto entry : llvm::enumerate(First: cmd_args.entries())) {
2430 if (!used[entry.index()] && !wants_raw_input)
2431 new_args.AppendArgument(arg_str: entry.value().ref());
2432 }
2433
2434 cmd_args.Clear();
2435 cmd_args.SetArguments(argc: new_args.GetArgumentCount(),
2436 argv: new_args.GetConstArgumentVector());
2437 } else {
2438 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2439 // This alias was not created with any options; nothing further needs to be
2440 // done, unless it is a command that wants raw input, in which case we need
2441 // to clear the rest of the data from cmd_args, since its in the raw input
2442 // string.
2443 if (wants_raw_input) {
2444 cmd_args.Clear();
2445 cmd_args.SetArguments(argc: new_args.GetArgumentCount(),
2446 argv: new_args.GetConstArgumentVector());
2447 }
2448 return;
2449 }
2450
2451 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2452}
2453
2454int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2455 int position = 0; // Any string that isn't an argument position, i.e. '%'
2456 // followed by an integer, gets a position
2457 // of zero.
2458
2459 const char *cptr = in_string;
2460
2461 // Does it start with '%'
2462 if (cptr[0] == '%') {
2463 ++cptr;
2464
2465 // Is the rest of it entirely digits?
2466 if (isdigit(cptr[0])) {
2467 const char *start = cptr;
2468 while (isdigit(cptr[0]))
2469 ++cptr;
2470
2471 // We've gotten to the end of the digits; are we at the end of the
2472 // string?
2473 if (cptr[0] == '\0')
2474 position = atoi(nptr: start);
2475 }
2476 }
2477
2478 return position;
2479}
2480
2481static void GetHomeInitFile(llvm::SmallVectorImpl<char> &init_file,
2482 llvm::StringRef suffix = {}) {
2483 std::string init_file_name = ".lldbinit";
2484 if (!suffix.empty()) {
2485 init_file_name.append(s: "-");
2486 init_file_name.append(str: suffix.str());
2487 }
2488
2489 FileSystem::Instance().GetHomeDirectory(path&: init_file);
2490 llvm::sys::path::append(path&: init_file, a: init_file_name);
2491
2492 FileSystem::Instance().Resolve(path&: init_file);
2493}
2494
2495static void GetHomeREPLInitFile(llvm::SmallVectorImpl<char> &init_file,
2496 LanguageType language) {
2497 if (language == eLanguageTypeUnknown) {
2498 LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs();
2499 if (auto main_repl_language = repl_languages.GetSingularLanguage())
2500 language = *main_repl_language;
2501 else
2502 return;
2503 }
2504
2505 std::string init_file_name =
2506 (llvm::Twine(".lldbinit-") +
2507 llvm::Twine(Language::GetNameForLanguageType(language)) +
2508 llvm::Twine("-repl"))
2509 .str();
2510 FileSystem::Instance().GetHomeDirectory(path&: init_file);
2511 llvm::sys::path::append(path&: init_file, a: init_file_name);
2512 FileSystem::Instance().Resolve(path&: init_file);
2513}
2514
2515static void GetCwdInitFile(llvm::SmallVectorImpl<char> &init_file) {
2516 llvm::StringRef s = ".lldbinit";
2517 init_file.assign(in_start: s.begin(), in_end: s.end());
2518 FileSystem::Instance().Resolve(path&: init_file);
2519}
2520
2521void CommandInterpreter::SourceInitFile(FileSpec file,
2522 CommandReturnObject &result) {
2523 assert(!m_skip_lldbinit_files);
2524
2525 if (!FileSystem::Instance().Exists(file_spec: file)) {
2526 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2527 return;
2528 }
2529
2530 // Use HandleCommand to 'source' the given file; this will do the actual
2531 // broadcasting of the commands back to any appropriate listener (see
2532 // CommandObjectSource::Execute for more details).
2533 const bool saved_batch = SetBatchCommandMode(true);
2534 CommandInterpreterRunOptions options;
2535 options.SetSilent(true);
2536 options.SetPrintErrors(true);
2537 options.SetStopOnError(false);
2538 options.SetStopOnContinue(true);
2539 HandleCommandsFromFile(file, options, result);
2540 SetBatchCommandMode(saved_batch);
2541}
2542
2543void CommandInterpreter::SourceInitFileCwd(CommandReturnObject &result) {
2544 if (m_skip_lldbinit_files) {
2545 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2546 return;
2547 }
2548
2549 llvm::SmallString<128> init_file;
2550 GetCwdInitFile(init_file);
2551 if (!FileSystem::Instance().Exists(path: init_file)) {
2552 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2553 return;
2554 }
2555
2556 LoadCWDlldbinitFile should_load =
2557 Target::GetGlobalProperties().GetLoadCWDlldbinitFile();
2558
2559 switch (should_load) {
2560 case eLoadCWDlldbinitFalse:
2561 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2562 break;
2563 case eLoadCWDlldbinitTrue:
2564 SourceInitFile(file: FileSpec(init_file.str()), result);
2565 break;
2566 case eLoadCWDlldbinitWarn: {
2567 llvm::SmallString<128> home_init_file;
2568 GetHomeInitFile(init_file&: home_init_file);
2569 if (llvm::sys::path::parent_path(path: init_file) ==
2570 llvm::sys::path::parent_path(path: home_init_file)) {
2571 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2572 } else {
2573 result.AppendError(in_string: InitFileWarning);
2574 }
2575 }
2576 }
2577}
2578
2579/// We will first see if there is an application specific ".lldbinit" file
2580/// whose name is "~/.lldbinit" followed by a "-" and the name of the program.
2581/// If this file doesn't exist, we fall back to the REPL init file or the
2582/// default home init file in "~/.lldbinit".
2583void CommandInterpreter::SourceInitFileHome(CommandReturnObject &result,
2584 bool is_repl) {
2585 if (m_skip_lldbinit_files) {
2586 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2587 return;
2588 }
2589
2590 llvm::SmallString<128> init_file;
2591
2592 if (is_repl)
2593 GetHomeREPLInitFile(init_file, language: GetDebugger().GetREPLLanguage());
2594
2595 if (init_file.empty())
2596 GetHomeInitFile(init_file);
2597
2598 if (!m_skip_app_init_files) {
2599 llvm::StringRef program_name =
2600 HostInfo::GetProgramFileSpec().GetFilename().GetStringRef();
2601 llvm::SmallString<128> program_init_file;
2602 GetHomeInitFile(init_file&: program_init_file, suffix: program_name);
2603 if (FileSystem::Instance().Exists(path: program_init_file))
2604 init_file = program_init_file;
2605 }
2606
2607 SourceInitFile(file: FileSpec(init_file.str()), result);
2608}
2609
2610void CommandInterpreter::SourceInitFileGlobal(CommandReturnObject &result) {
2611#ifdef LLDB_GLOBAL_INIT_DIRECTORY
2612 if (!m_skip_lldbinit_files) {
2613 FileSpec init_file(LLDB_GLOBAL_INIT_DIRECTORY);
2614 if (init_file)
2615 init_file.MakeAbsolute(HostInfo::GetShlibDir());
2616
2617 init_file.AppendPathComponent("lldbinit");
2618 SourceInitFile(init_file, result);
2619 return;
2620 }
2621#endif
2622 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2623}
2624
2625const char *CommandInterpreter::GetCommandPrefix() {
2626 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2627 return prefix == nullptr ? "" : prefix;
2628}
2629
2630PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2631 PlatformSP platform_sp;
2632 if (prefer_target_platform) {
2633 ExecutionContext exe_ctx(GetExecutionContext());
2634 Target *target = exe_ctx.GetTargetPtr();
2635 if (target)
2636 platform_sp = target->GetPlatform();
2637 }
2638
2639 if (!platform_sp)
2640 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2641 return platform_sp;
2642}
2643
2644bool CommandInterpreter::DidProcessStopAbnormally() const {
2645 auto exe_ctx = GetExecutionContext();
2646 TargetSP target_sp = exe_ctx.GetTargetSP();
2647 if (!target_sp)
2648 return false;
2649
2650 ProcessSP process_sp(target_sp->GetProcessSP());
2651 if (!process_sp)
2652 return false;
2653
2654 if (eStateStopped != process_sp->GetState())
2655 return false;
2656
2657 for (const auto &thread_sp : process_sp->GetThreadList().Threads()) {
2658 StopInfoSP stop_info = thread_sp->GetStopInfo();
2659 if (!stop_info) {
2660 // If there's no stop_info, keep iterating through the other threads;
2661 // it's enough that any thread has got a stop_info that indicates
2662 // an abnormal stop, to consider the process to be stopped abnormally.
2663 continue;
2664 }
2665
2666 const StopReason reason = stop_info->GetStopReason();
2667 if (reason == eStopReasonException ||
2668 reason == eStopReasonInstrumentation ||
2669 reason == eStopReasonProcessorTrace || reason == eStopReasonInterrupt ||
2670 reason == eStopReasonHistoryBoundary)
2671 return true;
2672
2673 if (reason == eStopReasonSignal) {
2674 const auto stop_signal = static_cast<int32_t>(stop_info->GetValue());
2675 UnixSignalsSP signals_sp = process_sp->GetUnixSignals();
2676 if (!signals_sp || !signals_sp->SignalIsValid(signo: stop_signal))
2677 // The signal is unknown, treat it as abnormal.
2678 return true;
2679
2680 const auto sigint_num = signals_sp->GetSignalNumberFromName(name: "SIGINT");
2681 const auto sigstop_num = signals_sp->GetSignalNumberFromName(name: "SIGSTOP");
2682 if ((stop_signal != sigint_num) && (stop_signal != sigstop_num))
2683 // The signal very likely implies a crash.
2684 return true;
2685 }
2686 }
2687
2688 return false;
2689}
2690
2691void CommandInterpreter::HandleCommands(
2692 const StringList &commands, const ExecutionContext &override_context,
2693 const CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2694
2695 OverrideExecutionContext(override_context);
2696 HandleCommands(commands, options, result);
2697 RestoreExecutionContext();
2698}
2699
2700void CommandInterpreter::HandleCommands(
2701 const StringList &commands, const CommandInterpreterRunOptions &options,
2702 CommandReturnObject &result) {
2703 size_t num_lines = commands.GetSize();
2704
2705 // If we are going to continue past a "continue" then we need to run the
2706 // commands synchronously. Make sure you reset this value anywhere you return
2707 // from the function.
2708
2709 bool old_async_execution = m_debugger.GetAsyncExecution();
2710
2711 if (!options.GetStopOnContinue()) {
2712 m_debugger.SetAsyncExecution(false);
2713 }
2714
2715 for (size_t idx = 0; idx < num_lines; idx++) {
2716 const char *cmd = commands.GetStringAtIndex(idx);
2717 if (cmd[0] == '\0')
2718 continue;
2719
2720 if (options.GetEchoCommands()) {
2721 // TODO: Add Stream support.
2722 result.AppendMessageWithFormat(format: "%s %s\n",
2723 m_debugger.GetPrompt().str().c_str(), cmd);
2724 }
2725
2726 CommandReturnObject tmp_result(m_debugger.GetUseColor());
2727 tmp_result.SetInteractive(result.GetInteractive());
2728 tmp_result.SetSuppressImmediateOutput(true);
2729
2730 // We might call into a regex or alias command, in which case the
2731 // add_to_history will get lost. This m_command_source_depth dingus is the
2732 // way we turn off adding to the history in that case, so set it up here.
2733 if (!options.GetAddToHistory())
2734 m_command_source_depth++;
2735 bool success = HandleCommand(command_line: cmd, lazy_add_to_history: options.m_add_to_history, result&: tmp_result);
2736 if (!options.GetAddToHistory())
2737 m_command_source_depth--;
2738
2739 if (options.GetPrintResults()) {
2740 if (tmp_result.Succeeded())
2741 result.AppendMessage(in_string: tmp_result.GetOutputString());
2742 }
2743
2744 if (!success || !tmp_result.Succeeded()) {
2745 std::string error_msg = tmp_result.GetErrorString();
2746 if (error_msg.empty())
2747 error_msg = "<unknown error>.\n";
2748 if (options.GetStopOnError()) {
2749 result.AppendErrorWithFormatv(format: "Aborting reading of commands after "
2750 "command #{0}: '{1}' failed with {2}",
2751 args: (uint64_t)idx, args&: cmd, args&: error_msg);
2752 m_debugger.SetAsyncExecution(old_async_execution);
2753 return;
2754 }
2755 if (options.GetPrintResults()) {
2756 result.AppendMessageWithFormatv(format: "Command #{0} '{1}' failed with {2}",
2757 args: (uint64_t)idx + 1, args&: cmd, args&: error_msg);
2758 }
2759 }
2760
2761 if (result.GetImmediateOutputStream())
2762 result.GetImmediateOutputStream()->Flush();
2763
2764 if (result.GetImmediateErrorStream())
2765 result.GetImmediateErrorStream()->Flush();
2766
2767 // N.B. Can't depend on DidChangeProcessState, because the state coming
2768 // into the command execution could be running (for instance in Breakpoint
2769 // Commands. So we check the return value to see if it is has running in
2770 // it.
2771 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2772 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2773 if (options.GetStopOnContinue()) {
2774 // If we caused the target to proceed, and we're going to stop in that
2775 // case, set the status in our real result before returning. This is
2776 // an error if the continue was not the last command in the set of
2777 // commands to be run.
2778 if (idx != num_lines - 1)
2779 result.AppendErrorWithFormat(
2780 format: "Aborting reading of commands after command #%" PRIu64
2781 ": '%s' continued the target.\n",
2782 (uint64_t)idx + 1, cmd);
2783 else
2784 result.AppendMessageWithFormat(format: "Command #%" PRIu64
2785 " '%s' continued the target.\n",
2786 (uint64_t)idx + 1, cmd);
2787
2788 result.SetStatus(tmp_result.GetStatus());
2789 m_debugger.SetAsyncExecution(old_async_execution);
2790
2791 return;
2792 }
2793 }
2794
2795 // Also check for "stop on crash here:
2796 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash() &&
2797 DidProcessStopAbnormally()) {
2798 if (idx != num_lines - 1)
2799 result.AppendErrorWithFormat(
2800 format: "Aborting reading of commands after command #%" PRIu64
2801 ": '%s' stopped with a signal or exception.\n",
2802 (uint64_t)idx + 1, cmd);
2803 else
2804 result.AppendMessageWithFormat(
2805 format: "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2806 (uint64_t)idx + 1, cmd);
2807
2808 result.SetStatus(tmp_result.GetStatus());
2809 m_debugger.SetAsyncExecution(old_async_execution);
2810
2811 return;
2812 }
2813 }
2814
2815 result.SetStatus(eReturnStatusSuccessFinishResult);
2816 m_debugger.SetAsyncExecution(old_async_execution);
2817}
2818
2819// Make flags that we can pass into the IOHandler so our delegates can do the
2820// right thing
2821enum {
2822 eHandleCommandFlagStopOnContinue = (1u << 0),
2823 eHandleCommandFlagStopOnError = (1u << 1),
2824 eHandleCommandFlagEchoCommand = (1u << 2),
2825 eHandleCommandFlagEchoCommentCommand = (1u << 3),
2826 eHandleCommandFlagPrintResult = (1u << 4),
2827 eHandleCommandFlagPrintErrors = (1u << 5),
2828 eHandleCommandFlagStopOnCrash = (1u << 6),
2829 eHandleCommandFlagAllowRepeats = (1u << 7)
2830};
2831
2832void CommandInterpreter::HandleCommandsFromFile(
2833 FileSpec &cmd_file, const ExecutionContext &context,
2834 const CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2835 OverrideExecutionContext(override_context: context);
2836 HandleCommandsFromFile(file&: cmd_file, options, result);
2837 RestoreExecutionContext();
2838}
2839
2840void CommandInterpreter::HandleCommandsFromFile(
2841 FileSpec &cmd_file, const CommandInterpreterRunOptions &options,
2842 CommandReturnObject &result) {
2843 if (!FileSystem::Instance().Exists(file_spec: cmd_file)) {
2844 result.AppendErrorWithFormat(
2845 format: "Error reading commands from file %s - file not found.\n",
2846 cmd_file.GetFilename().AsCString(value_if_empty: "<Unknown>"));
2847 return;
2848 }
2849
2850 std::string cmd_file_path = cmd_file.GetPath();
2851 auto input_file_up =
2852 FileSystem::Instance().Open(file_spec: cmd_file, options: File::eOpenOptionReadOnly);
2853 if (!input_file_up) {
2854 std::string error = llvm::toString(E: input_file_up.takeError());
2855 result.AppendErrorWithFormatv(
2856 format: "error: an error occurred read file '{0}': {1}\n", args&: cmd_file_path,
2857 args: llvm::fmt_consume(Item: input_file_up.takeError()));
2858 return;
2859 }
2860 FileSP input_file_sp = FileSP(std::move(input_file_up.get()));
2861
2862 Debugger &debugger = GetDebugger();
2863
2864 uint32_t flags = 0;
2865
2866 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2867 if (m_command_source_flags.empty()) {
2868 // Stop on continue by default
2869 flags |= eHandleCommandFlagStopOnContinue;
2870 } else if (m_command_source_flags.back() &
2871 eHandleCommandFlagStopOnContinue) {
2872 flags |= eHandleCommandFlagStopOnContinue;
2873 }
2874 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2875 flags |= eHandleCommandFlagStopOnContinue;
2876 }
2877
2878 if (options.m_stop_on_error == eLazyBoolCalculate) {
2879 if (m_command_source_flags.empty()) {
2880 if (GetStopCmdSourceOnError())
2881 flags |= eHandleCommandFlagStopOnError;
2882 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) {
2883 flags |= eHandleCommandFlagStopOnError;
2884 }
2885 } else if (options.m_stop_on_error == eLazyBoolYes) {
2886 flags |= eHandleCommandFlagStopOnError;
2887 }
2888
2889 // stop-on-crash can only be set, if it is present in all levels of
2890 // pushed flag sets.
2891 if (options.GetStopOnCrash()) {
2892 if (m_command_source_flags.empty()) {
2893 flags |= eHandleCommandFlagStopOnCrash;
2894 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) {
2895 flags |= eHandleCommandFlagStopOnCrash;
2896 }
2897 }
2898
2899 if (options.m_echo_commands == eLazyBoolCalculate) {
2900 if (m_command_source_flags.empty()) {
2901 // Echo command by default
2902 flags |= eHandleCommandFlagEchoCommand;
2903 } else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) {
2904 flags |= eHandleCommandFlagEchoCommand;
2905 }
2906 } else if (options.m_echo_commands == eLazyBoolYes) {
2907 flags |= eHandleCommandFlagEchoCommand;
2908 }
2909
2910 // We will only ever ask for this flag, if we echo commands in general.
2911 if (options.m_echo_comment_commands == eLazyBoolCalculate) {
2912 if (m_command_source_flags.empty()) {
2913 // Echo comments by default
2914 flags |= eHandleCommandFlagEchoCommentCommand;
2915 } else if (m_command_source_flags.back() &
2916 eHandleCommandFlagEchoCommentCommand) {
2917 flags |= eHandleCommandFlagEchoCommentCommand;
2918 }
2919 } else if (options.m_echo_comment_commands == eLazyBoolYes) {
2920 flags |= eHandleCommandFlagEchoCommentCommand;
2921 }
2922
2923 if (options.m_print_results == eLazyBoolCalculate) {
2924 if (m_command_source_flags.empty()) {
2925 // Print output by default
2926 flags |= eHandleCommandFlagPrintResult;
2927 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) {
2928 flags |= eHandleCommandFlagPrintResult;
2929 }
2930 } else if (options.m_print_results == eLazyBoolYes) {
2931 flags |= eHandleCommandFlagPrintResult;
2932 }
2933
2934 if (options.m_print_errors == eLazyBoolCalculate) {
2935 if (m_command_source_flags.empty()) {
2936 // Print output by default
2937 flags |= eHandleCommandFlagPrintErrors;
2938 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintErrors) {
2939 flags |= eHandleCommandFlagPrintErrors;
2940 }
2941 } else if (options.m_print_errors == eLazyBoolYes) {
2942 flags |= eHandleCommandFlagPrintErrors;
2943 }
2944
2945 if (flags & eHandleCommandFlagPrintResult) {
2946 debugger.GetOutputFileSP()->Printf(format: "Executing commands in '%s'.\n",
2947 cmd_file_path.c_str());
2948 }
2949
2950 // Used for inheriting the right settings when "command source" might
2951 // have nested "command source" commands
2952 lldb::LockableStreamFileSP empty_stream_sp;
2953 m_command_source_flags.push_back(x: flags);
2954 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2955 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2956 empty_stream_sp, // Pass in an empty stream so we inherit the top
2957 // input reader output stream
2958 empty_stream_sp, // Pass in an empty stream so we inherit the top
2959 // input reader error stream
2960 flags,
2961 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2962 // or written
2963 debugger.GetPrompt(), llvm::StringRef(),
2964 false, // Not multi-line
2965 debugger.GetUseColor(), 0, *this));
2966 const bool old_async_execution = debugger.GetAsyncExecution();
2967
2968 // Set synchronous execution if we are not stopping on continue
2969 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2970 debugger.SetAsyncExecution(false);
2971
2972 m_command_source_depth++;
2973 m_command_source_dirs.push_back(x: cmd_file.CopyByRemovingLastPathComponent());
2974
2975 debugger.RunIOHandlerSync(reader_sp: io_handler_sp);
2976 if (!m_command_source_flags.empty())
2977 m_command_source_flags.pop_back();
2978
2979 m_command_source_dirs.pop_back();
2980 m_command_source_depth--;
2981
2982 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2983 debugger.SetAsyncExecution(old_async_execution);
2984}
2985
2986bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2987
2988void CommandInterpreter::SetSynchronous(bool value) {
2989 m_synchronous_execution = value;
2990}
2991
2992void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2993 llvm::StringRef prefix,
2994 llvm::StringRef help_text) {
2995 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2996
2997 size_t line_width_max = max_columns - prefix.size();
2998 if (line_width_max < 16)
2999 line_width_max = help_text.size() + prefix.size();
3000
3001 strm.IndentMore(amount: prefix.size());
3002 bool prefixed_yet = false;
3003 // Even if we have no help text we still want to emit the command name.
3004 if (help_text.empty())
3005 help_text = "No help text";
3006 while (!help_text.empty()) {
3007 // Prefix the first line, indent subsequent lines to line up
3008 if (!prefixed_yet) {
3009 strm << prefix;
3010 prefixed_yet = true;
3011 } else
3012 strm.Indent();
3013
3014 // Never print more than the maximum on one line.
3015 llvm::StringRef this_line = help_text.substr(Start: 0, N: line_width_max);
3016
3017 // Always break on an explicit newline.
3018 std::size_t first_newline = this_line.find_first_of(Chars: "\n");
3019
3020 // Don't break on space/tab unless the text is too long to fit on one line.
3021 std::size_t last_space = llvm::StringRef::npos;
3022 if (this_line.size() != help_text.size())
3023 last_space = this_line.find_last_of(Chars: " \t");
3024
3025 // Break at whichever condition triggered first.
3026 this_line = this_line.substr(Start: 0, N: std::min(a: first_newline, b: last_space));
3027 strm.PutCString(cstr: this_line);
3028 strm.EOL();
3029
3030 // Remove whitespace / newlines after breaking.
3031 help_text = help_text.drop_front(N: this_line.size()).ltrim();
3032 }
3033 strm.IndentLess(amount: prefix.size());
3034}
3035
3036void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
3037 llvm::StringRef word_text,
3038 llvm::StringRef separator,
3039 llvm::StringRef help_text,
3040 size_t max_word_len) {
3041 StreamString prefix_stream;
3042 prefix_stream.Printf(format: " %-*s %*s ", (int)max_word_len, word_text.data(),
3043 (int)separator.size(), separator.data());
3044 OutputFormattedHelpText(strm, prefix: prefix_stream.GetString(), help_text);
3045}
3046
3047void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
3048 llvm::StringRef separator,
3049 llvm::StringRef help_text,
3050 uint32_t max_word_len) {
3051 int indent_size = max_word_len + separator.size() + 2;
3052
3053 strm.IndentMore(amount: indent_size);
3054
3055 StreamString text_strm;
3056 text_strm.Printf(format: "%-*s ", (int)max_word_len, word_text.data());
3057 text_strm << separator << " " << help_text;
3058
3059 const uint32_t max_columns = m_debugger.GetTerminalWidth();
3060
3061 llvm::StringRef text = text_strm.GetString();
3062
3063 uint32_t chars_left = max_columns;
3064
3065 auto nextWordLength = [](llvm::StringRef S) {
3066 size_t pos = S.find(C: ' ');
3067 return pos == llvm::StringRef::npos ? S.size() : pos;
3068 };
3069
3070 while (!text.empty()) {
3071 if (text.front() == '\n' ||
3072 (text.front() == ' ' && nextWordLength(text.ltrim(Char: ' ')) > chars_left)) {
3073 strm.EOL();
3074 strm.Indent();
3075 chars_left = max_columns - indent_size;
3076 if (text.front() == '\n')
3077 text = text.drop_front();
3078 else
3079 text = text.ltrim(Char: ' ');
3080 } else {
3081 strm.PutChar(ch: text.front());
3082 --chars_left;
3083 text = text.drop_front();
3084 }
3085 }
3086
3087 strm.EOL();
3088 strm.IndentLess(amount: indent_size);
3089}
3090
3091void CommandInterpreter::FindCommandsForApropos(
3092 llvm::StringRef search_word, StringList &commands_found,
3093 StringList &commands_help, const CommandObject::CommandMap &command_map) {
3094 for (const auto &pair : command_map) {
3095 llvm::StringRef command_name = pair.first;
3096 CommandObject *cmd_obj = pair.second.get();
3097
3098 const bool search_short_help = true;
3099 const bool search_long_help = false;
3100 const bool search_syntax = false;
3101 const bool search_options = false;
3102 if (command_name.contains_insensitive(Other: search_word) ||
3103 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
3104 search_long_help, search_syntax,
3105 search_options)) {
3106 commands_found.AppendString(str: command_name);
3107 commands_help.AppendString(str: cmd_obj->GetHelp());
3108 }
3109
3110 if (auto *multiword_cmd = cmd_obj->GetAsMultiwordCommand()) {
3111 StringList subcommands_found;
3112 FindCommandsForApropos(search_word, commands_found&: subcommands_found, commands_help,
3113 command_map: multiword_cmd->GetSubcommandDictionary());
3114 for (const auto &subcommand_name : subcommands_found) {
3115 std::string qualified_name =
3116 (command_name + " " + subcommand_name).str();
3117 commands_found.AppendString(s: qualified_name);
3118 }
3119 }
3120 }
3121}
3122
3123void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
3124 StringList &commands_found,
3125 StringList &commands_help,
3126 bool search_builtin_commands,
3127 bool search_user_commands,
3128 bool search_alias_commands,
3129 bool search_user_mw_commands) {
3130 CommandObject::CommandMap::const_iterator pos;
3131
3132 if (search_builtin_commands)
3133 FindCommandsForApropos(search_word, commands_found, commands_help,
3134 command_map: m_command_dict);
3135
3136 if (search_user_commands)
3137 FindCommandsForApropos(search_word, commands_found, commands_help,
3138 command_map: m_user_dict);
3139
3140 if (search_user_mw_commands)
3141 FindCommandsForApropos(search_word, commands_found, commands_help,
3142 command_map: m_user_mw_dict);
3143
3144 if (search_alias_commands)
3145 FindCommandsForApropos(search_word, commands_found, commands_help,
3146 command_map: m_alias_dict);
3147}
3148
3149ExecutionContext CommandInterpreter::GetExecutionContext() const {
3150 return !m_overriden_exe_contexts.empty()
3151 ? m_overriden_exe_contexts.top()
3152 : m_debugger.GetSelectedExecutionContext();
3153}
3154
3155void CommandInterpreter::OverrideExecutionContext(
3156 const ExecutionContext &override_context) {
3157 m_overriden_exe_contexts.push(x: override_context);
3158}
3159
3160void CommandInterpreter::RestoreExecutionContext() {
3161 if (!m_overriden_exe_contexts.empty())
3162 m_overriden_exe_contexts.pop();
3163}
3164
3165void CommandInterpreter::GetProcessOutput() {
3166 if (ProcessSP process_sp = GetExecutionContext().GetProcessSP())
3167 m_debugger.FlushProcessOutput(process&: *process_sp, /*flush_stdout*/ true,
3168 /*flush_stderr*/ true);
3169}
3170
3171void CommandInterpreter::StartHandlingCommand() {
3172 auto idle_state = CommandHandlingState::eIdle;
3173 if (m_command_state.compare_exchange_strong(
3174 e&: idle_state, i: CommandHandlingState::eInProgress))
3175 lldbassert(m_iohandler_nesting_level == 0);
3176 else
3177 lldbassert(m_iohandler_nesting_level > 0);
3178 ++m_iohandler_nesting_level;
3179}
3180
3181void CommandInterpreter::FinishHandlingCommand() {
3182 lldbassert(m_iohandler_nesting_level > 0);
3183 if (--m_iohandler_nesting_level == 0) {
3184 auto prev_state = m_command_state.exchange(i: CommandHandlingState::eIdle);
3185 lldbassert(prev_state != CommandHandlingState::eIdle);
3186 }
3187}
3188
3189bool CommandInterpreter::InterruptCommand() {
3190 auto in_progress = CommandHandlingState::eInProgress;
3191 return m_command_state.compare_exchange_strong(
3192 e&: in_progress, i: CommandHandlingState::eInterrupted);
3193}
3194
3195bool CommandInterpreter::WasInterrupted() const {
3196 if (!m_debugger.IsIOHandlerThreadCurrentThread())
3197 return false;
3198
3199 bool was_interrupted =
3200 (m_command_state == CommandHandlingState::eInterrupted);
3201 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
3202 return was_interrupted;
3203}
3204
3205void CommandInterpreter::PrintCommandOutput(IOHandler &io_handler,
3206 llvm::StringRef str,
3207 bool is_stdout) {
3208
3209 lldb::LockableStreamFileSP stream = is_stdout
3210 ? io_handler.GetOutputStreamFileSP()
3211 : io_handler.GetErrorStreamFileSP();
3212 // Split the output into lines and poll for interrupt requests
3213 bool had_output = !str.empty();
3214 while (!str.empty()) {
3215 llvm::StringRef line;
3216 std::tie(args&: line, args&: str) = str.split(Separator: '\n');
3217 {
3218 LockedStreamFile stream_file = stream->Lock();
3219 stream_file.Write(src: line.data(), src_len: line.size());
3220 stream_file.Write(src: "\n", src_len: 1);
3221 }
3222 }
3223
3224 LockedStreamFile stream_file = stream->Lock();
3225 if (had_output &&
3226 INTERRUPT_REQUESTED(GetDebugger(), "Interrupted dumping command output"))
3227 stream_file.Printf(format: "\n... Interrupted.\n");
3228 stream_file.Flush();
3229}
3230
3231bool CommandInterpreter::EchoCommandNonInteractive(
3232 llvm::StringRef line, const Flags &io_handler_flags) const {
3233 if (!io_handler_flags.Test(bit: eHandleCommandFlagEchoCommand))
3234 return false;
3235
3236 llvm::StringRef command = line.trim();
3237 if (command.empty())
3238 return true;
3239
3240 if (command.front() == m_comment_char)
3241 return io_handler_flags.Test(bit: eHandleCommandFlagEchoCommentCommand);
3242
3243 return true;
3244}
3245
3246void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
3247 std::string &line) {
3248 // If we were interrupted, bail out...
3249 if (WasInterrupted())
3250 return;
3251
3252 const bool is_interactive = io_handler.GetIsInteractive();
3253 const bool allow_repeats =
3254 io_handler.GetFlags().Test(bit: eHandleCommandFlagAllowRepeats);
3255
3256 if (!is_interactive && !allow_repeats) {
3257 // When we are not interactive, don't execute blank lines. This will happen
3258 // sourcing a commands file. We don't want blank lines to repeat the
3259 // previous command and cause any errors to occur (like redefining an
3260 // alias, get an error and stop parsing the commands file).
3261 // But obey the AllowRepeats flag if the user has set it.
3262 if (line.empty())
3263 return;
3264 }
3265 if (!is_interactive) {
3266 // When using a non-interactive file handle (like when sourcing commands
3267 // from a file) we need to echo the command out so we don't just see the
3268 // command output and no command...
3269 if (EchoCommandNonInteractive(line, io_handler_flags: io_handler.GetFlags())) {
3270 LockedStreamFile locked_stream =
3271 io_handler.GetOutputStreamFileSP()->Lock();
3272 locked_stream.Printf(format: "%s%s\n", io_handler.GetPrompt(), line.c_str());
3273 }
3274 }
3275
3276 StartHandlingCommand();
3277
3278 ExecutionContext exe_ctx = m_debugger.GetSelectedExecutionContext();
3279 bool pushed_exe_ctx = false;
3280 if (exe_ctx.HasTargetScope()) {
3281 OverrideExecutionContext(override_context: exe_ctx);
3282 pushed_exe_ctx = true;
3283 }
3284 auto finalize = llvm::make_scope_exit(F: [this, pushed_exe_ctx]() {
3285 if (pushed_exe_ctx)
3286 RestoreExecutionContext();
3287 });
3288
3289 lldb_private::CommandReturnObject result(m_debugger.GetUseColor());
3290 HandleCommand(command_line: line.c_str(), lazy_add_to_history: eLazyBoolCalculate, result);
3291
3292 // Now emit the command output text from the command we just executed
3293 if ((result.Succeeded() &&
3294 io_handler.GetFlags().Test(bit: eHandleCommandFlagPrintResult)) ||
3295 io_handler.GetFlags().Test(bit: eHandleCommandFlagPrintErrors)) {
3296 auto DefaultPrintCallback = [&](const CommandReturnObject &result) {
3297 // Display any inline diagnostics first.
3298 const bool inline_diagnostics = !result.GetImmediateErrorStream() &&
3299 GetDebugger().GetShowInlineDiagnostics();
3300 if (inline_diagnostics) {
3301 unsigned prompt_len = m_debugger.GetPrompt().size();
3302 if (auto indent = result.GetDiagnosticIndent()) {
3303 std::string diags =
3304 result.GetInlineDiagnosticString(indent: prompt_len + *indent);
3305 PrintCommandOutput(io_handler, str: diags, is_stdout: true);
3306 }
3307 }
3308
3309 // Display any STDOUT/STDERR _prior_ to emitting the command result text.
3310 GetProcessOutput();
3311
3312 if (!result.GetImmediateOutputStream()) {
3313 llvm::StringRef output = result.GetOutputString();
3314 PrintCommandOutput(io_handler, str: output, is_stdout: true);
3315 }
3316
3317 // Now emit the command error text from the command we just executed.
3318 if (!result.GetImmediateErrorStream()) {
3319 std::string error = result.GetErrorString(with_diagnostics: !inline_diagnostics);
3320 PrintCommandOutput(io_handler, str: error, is_stdout: false);
3321 }
3322 };
3323
3324 if (m_print_callback) {
3325 const auto callback_result = m_print_callback(result);
3326 if (callback_result == eCommandReturnObjectPrintCallbackSkipped)
3327 DefaultPrintCallback(result);
3328 } else {
3329 DefaultPrintCallback(result);
3330 }
3331 }
3332
3333 FinishHandlingCommand();
3334
3335 switch (result.GetStatus()) {
3336 case eReturnStatusInvalid:
3337 case eReturnStatusSuccessFinishNoResult:
3338 case eReturnStatusSuccessFinishResult:
3339 case eReturnStatusStarted:
3340 break;
3341
3342 case eReturnStatusSuccessContinuingNoResult:
3343 case eReturnStatusSuccessContinuingResult:
3344 if (io_handler.GetFlags().Test(bit: eHandleCommandFlagStopOnContinue))
3345 io_handler.SetIsDone(true);
3346 break;
3347
3348 case eReturnStatusFailed:
3349 m_result.IncrementNumberOfErrors();
3350 if (io_handler.GetFlags().Test(bit: eHandleCommandFlagStopOnError)) {
3351 m_result.SetResult(lldb::eCommandInterpreterResultCommandError);
3352 io_handler.SetIsDone(true);
3353 }
3354 break;
3355
3356 case eReturnStatusQuit:
3357 m_result.SetResult(lldb::eCommandInterpreterResultQuitRequested);
3358 io_handler.SetIsDone(true);
3359 break;
3360 }
3361
3362 // Finally, if we're going to stop on crash, check that here:
3363 if (m_result.IsResult(result: lldb::eCommandInterpreterResultSuccess) &&
3364 result.GetDidChangeProcessState() &&
3365 io_handler.GetFlags().Test(bit: eHandleCommandFlagStopOnCrash) &&
3366 DidProcessStopAbnormally()) {
3367 io_handler.SetIsDone(true);
3368 m_result.SetResult(lldb::eCommandInterpreterResultInferiorCrash);
3369 }
3370}
3371
3372bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
3373 ExecutionContext exe_ctx(GetExecutionContext());
3374 Process *process = exe_ctx.GetProcessPtr();
3375
3376 if (InterruptCommand())
3377 return true;
3378
3379 if (process) {
3380 StateType state = process->GetState();
3381 if (StateIsRunningState(state)) {
3382 process->Halt();
3383 return true; // Don't do any updating when we are running
3384 }
3385 }
3386
3387 ScriptInterpreter *script_interpreter =
3388 m_debugger.GetScriptInterpreter(can_create: false);
3389 if (script_interpreter) {
3390 if (script_interpreter->Interrupt())
3391 return true;
3392 }
3393 return false;
3394}
3395
3396bool CommandInterpreter::SaveTranscript(
3397 CommandReturnObject &result, std::optional<std::string> output_file) {
3398 if (output_file == std::nullopt || output_file->empty()) {
3399 std::string now = llvm::to_string(Value: std::chrono::system_clock::now());
3400 llvm::replace(Range&: now, OldValue: ' ', NewValue: '_');
3401 // Can't have file name with colons on Windows
3402 llvm::replace(Range&: now, OldValue: ':', NewValue: '-');
3403 const std::string file_name = "lldb_session_" + now + ".log";
3404
3405 FileSpec save_location = GetSaveSessionDirectory();
3406
3407 if (!save_location)
3408 save_location = HostInfo::GetGlobalTempDir();
3409
3410 FileSystem::Instance().Resolve(file_spec&: save_location);
3411 save_location.AppendPathComponent(component: file_name);
3412 output_file = save_location.GetPath();
3413 }
3414
3415 auto error_out = [&](llvm::StringRef error_message, std::string description) {
3416 LLDB_LOG(GetLog(LLDBLog::Commands), "{0} ({1}:{2})", error_message,
3417 output_file, description);
3418 result.AppendErrorWithFormatv(
3419 format: "Failed to save session's transcripts to {0}!", args&: *output_file);
3420 return false;
3421 };
3422
3423 File::OpenOptions flags = File::eOpenOptionWriteOnly |
3424 File::eOpenOptionCanCreate |
3425 File::eOpenOptionTruncate;
3426
3427 auto opened_file = FileSystem::Instance().Open(file_spec: FileSpec(*output_file), options: flags);
3428
3429 if (!opened_file)
3430 return error_out("Unable to create file",
3431 llvm::toString(E: opened_file.takeError()));
3432
3433 FileUP file = std::move(opened_file.get());
3434
3435 size_t byte_size = m_transcript_stream.GetSize();
3436
3437 Status error = file->Write(buf: m_transcript_stream.GetData(), num_bytes&: byte_size);
3438
3439 if (error.Fail() || byte_size != m_transcript_stream.GetSize())
3440 return error_out("Unable to write to destination file",
3441 "Bytes written do not match transcript size.");
3442
3443 result.SetStatus(eReturnStatusSuccessFinishNoResult);
3444 result.AppendMessageWithFormat(format: "Session's transcripts saved to %s\n",
3445 output_file->c_str());
3446 if (!GetSaveTranscript())
3447 result.AppendError(
3448 in_string: "Note: the setting interpreter.save-transcript is set to false, so the "
3449 "transcript might not have been recorded.");
3450
3451 if (GetOpenTranscriptInEditor() && Host::IsInteractiveGraphicSession()) {
3452 const FileSpec file_spec;
3453 error = file->GetFileSpec(file_spec&: const_cast<FileSpec &>(file_spec));
3454 if (error.Success()) {
3455 if (llvm::Error e = Host::OpenFileInExternalEditor(
3456 editor: m_debugger.GetExternalEditor(), file_spec, line_no: 1))
3457 result.AppendError(in_string: llvm::toString(E: std::move(e)));
3458 }
3459 }
3460
3461 return true;
3462}
3463
3464bool CommandInterpreter::IsInteractive() {
3465 return (GetIOHandler() ? GetIOHandler()->GetIsInteractive() : false);
3466}
3467
3468FileSpec CommandInterpreter::GetCurrentSourceDir() {
3469 if (m_command_source_dirs.empty())
3470 return {};
3471 return m_command_source_dirs.back();
3472}
3473
3474void CommandInterpreter::GetLLDBCommandsFromIOHandler(
3475 const char *prompt, IOHandlerDelegate &delegate, void *baton) {
3476 Debugger &debugger = GetDebugger();
3477 IOHandlerSP io_handler_sp(
3478 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
3479 "lldb", // Name of input reader for history
3480 llvm::StringRef(prompt), // Prompt
3481 llvm::StringRef(), // Continuation prompt
3482 true, // Get multiple lines
3483 debugger.GetUseColor(),
3484 0, // Don't show line numbers
3485 delegate)); // IOHandlerDelegate
3486
3487 if (io_handler_sp) {
3488 io_handler_sp->SetUserData(baton);
3489 debugger.RunIOHandlerAsync(reader_sp: io_handler_sp);
3490 }
3491}
3492
3493void CommandInterpreter::GetPythonCommandsFromIOHandler(
3494 const char *prompt, IOHandlerDelegate &delegate, void *baton) {
3495 Debugger &debugger = GetDebugger();
3496 IOHandlerSP io_handler_sp(
3497 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
3498 "lldb-python", // Name of input reader for history
3499 llvm::StringRef(prompt), // Prompt
3500 llvm::StringRef(), // Continuation prompt
3501 true, // Get multiple lines
3502 debugger.GetUseColor(),
3503 0, // Don't show line numbers
3504 delegate)); // IOHandlerDelegate
3505
3506 if (io_handler_sp) {
3507 io_handler_sp->SetUserData(baton);
3508 debugger.RunIOHandlerAsync(reader_sp: io_handler_sp);
3509 }
3510}
3511
3512bool CommandInterpreter::IsActive() {
3513 return m_debugger.IsTopIOHandler(reader_sp: m_command_io_handler_sp);
3514}
3515
3516lldb::IOHandlerSP
3517CommandInterpreter::GetIOHandler(bool force_create,
3518 CommandInterpreterRunOptions *options) {
3519 // Always re-create the IOHandlerEditline in case the input changed. The old
3520 // instance might have had a non-interactive input and now it does or vice
3521 // versa.
3522 if (force_create || !m_command_io_handler_sp) {
3523 // Always re-create the IOHandlerEditline in case the input changed. The
3524 // old instance might have had a non-interactive input and now it does or
3525 // vice versa.
3526 uint32_t flags = 0;
3527
3528 if (options) {
3529 if (options->m_stop_on_continue == eLazyBoolYes)
3530 flags |= eHandleCommandFlagStopOnContinue;
3531 if (options->m_stop_on_error == eLazyBoolYes)
3532 flags |= eHandleCommandFlagStopOnError;
3533 if (options->m_stop_on_crash == eLazyBoolYes)
3534 flags |= eHandleCommandFlagStopOnCrash;
3535 if (options->m_echo_commands != eLazyBoolNo)
3536 flags |= eHandleCommandFlagEchoCommand;
3537 if (options->m_echo_comment_commands != eLazyBoolNo)
3538 flags |= eHandleCommandFlagEchoCommentCommand;
3539 if (options->m_print_results != eLazyBoolNo)
3540 flags |= eHandleCommandFlagPrintResult;
3541 if (options->m_print_errors != eLazyBoolNo)
3542 flags |= eHandleCommandFlagPrintErrors;
3543 if (options->m_allow_repeats == eLazyBoolYes)
3544 flags |= eHandleCommandFlagAllowRepeats;
3545 } else {
3546 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult |
3547 eHandleCommandFlagPrintErrors;
3548 }
3549
3550 m_command_io_handler_sp = std::make_shared<IOHandlerEditline>(
3551 args&: m_debugger, args: IOHandler::Type::CommandInterpreter,
3552 args: m_debugger.GetInputFileSP(), args: m_debugger.GetOutputStreamSP(),
3553 args: m_debugger.GetErrorStreamSP(), args&: flags, args: "lldb", args: m_debugger.GetPrompt(),
3554 args: llvm::StringRef(), // Continuation prompt
3555 args: false, // Don't enable multiple line input, just single line commands
3556 args: m_debugger.GetUseColor(),
3557 args: 0, // Don't show line numbers
3558 args&: *this); // IOHandlerDelegate
3559 }
3560 return m_command_io_handler_sp;
3561}
3562
3563CommandInterpreterRunResult CommandInterpreter::RunCommandInterpreter(
3564 CommandInterpreterRunOptions &options) {
3565 // Always re-create the command interpreter when we run it in case any file
3566 // handles have changed.
3567 bool force_create = true;
3568 m_debugger.RunIOHandlerAsync(reader_sp: GetIOHandler(force_create, options: &options));
3569 m_result = CommandInterpreterRunResult();
3570
3571 if (options.GetAutoHandleEvents())
3572 m_debugger.StartEventHandlerThread();
3573
3574 if (options.GetSpawnThread()) {
3575 m_debugger.StartIOHandlerThread();
3576 } else {
3577 // If the current thread is not managed by a host thread, we won't detect
3578 // that this IS the CommandInterpreter IOHandler thread, so make it so:
3579 HostThread new_io_handler_thread(Host::GetCurrentThread());
3580 HostThread old_io_handler_thread =
3581 m_debugger.SetIOHandlerThread(new_io_handler_thread);
3582 m_debugger.RunIOHandlers();
3583 m_debugger.SetIOHandlerThread(old_io_handler_thread);
3584
3585 if (options.GetAutoHandleEvents())
3586 m_debugger.StopEventHandlerThread();
3587 }
3588
3589 return m_result;
3590}
3591
3592CommandObject *
3593CommandInterpreter::ResolveCommandImpl(std::string &command_line,
3594 CommandReturnObject &result) {
3595 std::string scratch_command(command_line); // working copy so we don't modify
3596 // command_line unless we succeed
3597 CommandObject *cmd_obj = nullptr;
3598 StreamString revised_command_line;
3599 bool wants_raw_input = false;
3600 std::string next_word;
3601 StringList matches;
3602 bool done = false;
3603
3604 auto build_alias_cmd = [&](std::string &full_name) {
3605 revised_command_line.Clear();
3606 matches.Clear();
3607 std::string alias_result;
3608 cmd_obj =
3609 BuildAliasResult(alias_name: full_name, raw_input_string&: scratch_command, alias_result, result);
3610 revised_command_line.Printf(format: "%s", alias_result.c_str());
3611 if (cmd_obj) {
3612 wants_raw_input = cmd_obj->WantsRawCommandString();
3613 }
3614 };
3615
3616 while (!done) {
3617 char quote_char = '\0';
3618 std::string suffix;
3619 ExtractCommand(command_string&: scratch_command, command&: next_word, suffix, quote_char);
3620 if (cmd_obj == nullptr) {
3621 std::string full_name;
3622 bool is_alias = GetAliasFullName(cmd: next_word, full_name);
3623 cmd_obj = GetCommandObject(cmd_str: next_word, matches: &matches);
3624 bool is_real_command =
3625 (!is_alias) || (cmd_obj != nullptr && !cmd_obj->IsAlias());
3626 if (!is_real_command) {
3627 build_alias_cmd(full_name);
3628 } else {
3629 if (cmd_obj) {
3630 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
3631 revised_command_line.Printf(format: "%s", cmd_name.str().c_str());
3632 wants_raw_input = cmd_obj->WantsRawCommandString();
3633 } else {
3634 revised_command_line.Printf(format: "%s", next_word.c_str());
3635 }
3636 }
3637 } else {
3638 if (cmd_obj->IsMultiwordObject()) {
3639 CommandObject *sub_cmd_obj =
3640 cmd_obj->GetSubcommandObject(sub_cmd: next_word.c_str());
3641 if (sub_cmd_obj) {
3642 // The subcommand's name includes the parent command's name, so
3643 // restart rather than append to the revised_command_line.
3644 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3645 revised_command_line.Clear();
3646 revised_command_line.Printf(format: "%s", sub_cmd_name.str().c_str());
3647 cmd_obj = sub_cmd_obj;
3648 wants_raw_input = cmd_obj->WantsRawCommandString();
3649 } else {
3650 if (quote_char)
3651 revised_command_line.Printf(format: " %c%s%s%c", quote_char,
3652 next_word.c_str(), suffix.c_str(),
3653 quote_char);
3654 else
3655 revised_command_line.Printf(format: " %s%s", next_word.c_str(),
3656 suffix.c_str());
3657 done = true;
3658 }
3659 } else {
3660 if (quote_char)
3661 revised_command_line.Printf(format: " %c%s%s%c", quote_char,
3662 next_word.c_str(), suffix.c_str(),
3663 quote_char);
3664 else
3665 revised_command_line.Printf(format: " %s%s", next_word.c_str(),
3666 suffix.c_str());
3667 done = true;
3668 }
3669 }
3670
3671 if (cmd_obj == nullptr) {
3672 const size_t num_matches = matches.GetSize();
3673 if (matches.GetSize() > 1) {
3674 StringList alias_matches;
3675 GetAliasCommandObject(cmd: next_word, matches: &alias_matches);
3676
3677 if (alias_matches.GetSize() == 1) {
3678 std::string full_name;
3679 GetAliasFullName(cmd: alias_matches.GetStringAtIndex(idx: 0), full_name);
3680 build_alias_cmd(full_name);
3681 done = static_cast<bool>(cmd_obj);
3682 } else {
3683 StreamString error_msg;
3684 error_msg.Printf(format: "Ambiguous command '%s'. Possible matches:\n",
3685 next_word.c_str());
3686
3687 for (uint32_t i = 0; i < num_matches; ++i) {
3688 error_msg.Printf(format: "\t%s\n", matches.GetStringAtIndex(idx: i));
3689 }
3690 result.AppendRawError(in_string: error_msg.GetString());
3691 }
3692 } else {
3693 // We didn't have only one match, otherwise we wouldn't get here.
3694 lldbassert(num_matches == 0);
3695 result.AppendErrorWithFormat(format: "'%s' is not a valid command.\n",
3696 next_word.c_str());
3697 }
3698 if (!done)
3699 return nullptr;
3700 }
3701
3702 if (cmd_obj->IsMultiwordObject()) {
3703 if (!suffix.empty()) {
3704 result.AppendErrorWithFormat(
3705 format: "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3706 "might be invalid).\n",
3707 cmd_obj->GetCommandName().str().c_str(),
3708 next_word.empty() ? "" : next_word.c_str(),
3709 next_word.empty() ? " -- " : " ", suffix.c_str());
3710 return nullptr;
3711 }
3712 } else {
3713 // If we found a normal command, we are done
3714 done = true;
3715 if (!suffix.empty()) {
3716 switch (suffix[0]) {
3717 case '/':
3718 // GDB format suffixes
3719 {
3720 Options *command_options = cmd_obj->GetOptions();
3721 if (command_options &&
3722 command_options->SupportsLongOption(long_option: "gdb-format")) {
3723 std::string gdb_format_option("--gdb-format=");
3724 gdb_format_option += (suffix.c_str() + 1);
3725
3726 std::string cmd = std::string(revised_command_line.GetString());
3727 size_t arg_terminator_idx = FindArgumentTerminator(s: cmd);
3728 if (arg_terminator_idx != std::string::npos) {
3729 // Insert the gdb format option before the "--" that terminates
3730 // options
3731 gdb_format_option.append(n: 1, c: ' ');
3732 cmd.insert(pos1: arg_terminator_idx, str: gdb_format_option);
3733 revised_command_line.Clear();
3734 revised_command_line.PutCString(cstr: cmd);
3735 } else
3736 revised_command_line.Printf(format: " %s", gdb_format_option.c_str());
3737
3738 if (wants_raw_input &&
3739 FindArgumentTerminator(s: cmd) == std::string::npos)
3740 revised_command_line.PutCString(cstr: " --");
3741 } else {
3742 result.AppendErrorWithFormat(
3743 format: "the '%s' command doesn't support the --gdb-format option\n",
3744 cmd_obj->GetCommandName().str().c_str());
3745 return nullptr;
3746 }
3747 }
3748 break;
3749
3750 default:
3751 result.AppendErrorWithFormat(
3752 format: "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3753 return nullptr;
3754 }
3755 }
3756 }
3757 if (scratch_command.empty())
3758 done = true;
3759 }
3760
3761 if (!scratch_command.empty())
3762 revised_command_line.Printf(format: " %s", scratch_command.c_str());
3763
3764 if (cmd_obj != nullptr)
3765 command_line = std::string(revised_command_line.GetString());
3766
3767 return cmd_obj;
3768}
3769
3770llvm::json::Value CommandInterpreter::GetStatistics() {
3771 llvm::json::Object stats;
3772 for (const auto &command_usage : m_command_usages)
3773 stats.try_emplace(K: command_usage.getKey(), Args: command_usage.getValue());
3774 return stats;
3775}
3776
3777const StructuredData::Array &CommandInterpreter::GetTranscript() const {
3778 return m_transcript;
3779}
3780
3781void CommandInterpreter::SetPrintCallback(
3782 CommandReturnObjectCallback callback) {
3783 m_print_callback = callback;
3784}
3785

source code of lldb/source/Interpreter/CommandInterpreter.cpp