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