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 specified, 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().Clone(); 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_string); 1891 std::string real_original_command_string(command_string); 1892 1893 Log *log = GetLog(LLDBLog::Commands); 1894 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")", 1895 command_line); 1896 1897 LLDB_LOGF(log, "Processing command: %s", command_line); 1898 LLDB_SCOPED_TIMERF("Processing command: %s.", command_line); 1899 1900 if (INTERRUPT_REQUESTED(GetDebugger(), "Interrupted initiating command")) { 1901 result.AppendError("... Interrupted"); 1902 return false; 1903 } 1904 1905 bool add_to_history; 1906 if (lazy_add_to_history == eLazyBoolCalculate) 1907 add_to_history = (m_command_source_depth == 0); 1908 else 1909 add_to_history = (lazy_add_to_history == eLazyBoolYes); 1910 1911 // The same `transcript_item` will be used below to add output and error of 1912 // the command. 1913 StructuredData::DictionarySP transcript_item; 1914 if (GetSaveTranscript()) { 1915 m_transcript_stream << "(lldb) " << command_line << '\n'; 1916 1917 transcript_item = std::make_shared<StructuredData::Dictionary>(); 1918 transcript_item->AddStringItem("command", command_line); 1919 transcript_item->AddIntegerItem( 1920 "timestampInEpochSeconds", 1921 std::chrono::duration_cast<std::chrono::seconds>( 1922 std::chrono::system_clock::now().time_since_epoch()) 1923 .count()); 1924 m_transcript.AddItem(transcript_item); 1925 } 1926 1927 bool empty_command = false; 1928 bool comment_command = false; 1929 if (command_string.empty()) 1930 empty_command = true; 1931 else { 1932 const char *k_space_characters = "\t\n\v\f\r "; 1933 1934 size_t non_space = command_string.find_first_not_of(k_space_characters); 1935 // Check for empty line or comment line (lines whose first non-space 1936 // character is the comment character for this interpreter) 1937 if (non_space == std::string::npos) 1938 empty_command = true; 1939 else if (command_string[non_space] == m_comment_char) 1940 comment_command = true; 1941 else if (command_string[non_space] == CommandHistory::g_repeat_char) { 1942 llvm::StringRef search_str(command_string); 1943 search_str = search_str.drop_front(non_space); 1944 if (auto hist_str = m_command_history.FindString(search_str)) { 1945 add_to_history = false; 1946 command_string = std::string(*hist_str); 1947 original_command_string = std::string(*hist_str); 1948 } else { 1949 result.AppendErrorWithFormat("Could not find entry: %s in history", 1950 command_string.c_str()); 1951 return false; 1952 } 1953 } 1954 } 1955 1956 if (empty_command) { 1957 if (!GetRepeatPreviousCommand()) { 1958 result.SetStatus(eReturnStatusSuccessFinishNoResult); 1959 return true; 1960 } 1961 1962 if (m_command_history.IsEmpty()) { 1963 result.AppendError("empty command"); 1964 return false; 1965 } 1966 1967 command_line = m_repeat_command.c_str(); 1968 command_string = command_line; 1969 original_command_string = command_line; 1970 if (m_repeat_command.empty()) { 1971 result.AppendError("No auto repeat."); 1972 return false; 1973 } 1974 1975 add_to_history = false; 1976 } else if (comment_command) { 1977 result.SetStatus(eReturnStatusSuccessFinishNoResult); 1978 return true; 1979 } 1980 1981 // Phase 1. 1982 1983 // Before we do ANY kind of argument processing, we need to figure out what 1984 // the real/final command object is for the specified command. This gets 1985 // complicated by the fact that the user could have specified an alias, and, 1986 // in translating the alias, there may also be command options and/or even 1987 // data (including raw text strings) that need to be found and inserted into 1988 // the command line as part of the translation. So this first step is plain 1989 // look-up and replacement, resulting in: 1990 // 1. the command object whose Execute method will actually be called 1991 // 2. a revised command string, with all substitutions and replacements 1992 // taken care of 1993 // From 1 above, we can determine whether the Execute function wants raw 1994 // input or not. 1995 1996 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result); 1997 1998 // We have to preprocess the whole command string for Raw commands, since we 1999 // don't know the structure of the command. For parsed commands, we only 2000 // treat backticks as quote characters specially. 2001 // FIXME: We probably want to have raw commands do their own preprocessing. 2002 // For instance, I don't think people expect substitution in expr expressions. 2003 if (cmd_obj && cmd_obj->WantsRawCommandString()) { 2004 Status error(PreprocessCommand(command_string)); 2005 2006 if (error.Fail()) { 2007 result.AppendError(error.AsCString()); 2008 return false; 2009 } 2010 } 2011 2012 // Although the user may have abbreviated the command, the command_string now 2013 // has the command expanded to the full name. For example, if the input was 2014 // "br s -n main", command_string is now "breakpoint set -n main". 2015 if (log) { 2016 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>"; 2017 LLDB_LOGF(log, "HandleCommand, cmd_obj : '%s'", command_name.str().c_str()); 2018 LLDB_LOGF(log, "HandleCommand, (revised) command_string: '%s'", 2019 command_string.c_str()); 2020 const bool wants_raw_input = 2021 (cmd_obj != nullptr) ? cmd_obj->WantsRawCommandString() : false; 2022 LLDB_LOGF(log, "HandleCommand, wants_raw_input:'%s'", 2023 wants_raw_input ? "True" : "False"); 2024 } 2025 2026 // Phase 2. 2027 // Take care of things like setting up the history command & calling the 2028 // appropriate Execute method on the CommandObject, with the appropriate 2029 // arguments. 2030 StatsDuration execute_time; 2031 if (cmd_obj != nullptr) { 2032 bool generate_repeat_command = add_to_history; 2033 // If we got here when empty_command was true, then this command is a 2034 // stored "repeat command" which we should give a chance to produce it's 2035 // repeat command, even though we don't add repeat commands to the history. 2036 generate_repeat_command |= empty_command; 2037 // For `command regex`, the regex command (ex `bt`) is added to history, but 2038 // the resolved command (ex `thread backtrace`) is _not_ added to history. 2039 // However, the resolved command must be given the opportunity to provide a 2040 // repeat command. `force_repeat_command` supports this case. 2041 generate_repeat_command |= force_repeat_command; 2042 if (generate_repeat_command) { 2043 Args command_args(command_string); 2044 std::optional<std::string> repeat_command = 2045 cmd_obj->GetRepeatCommand(command_args, 0); 2046 if (repeat_command) { 2047 LLDB_LOGF(log, "Repeat command: %s", repeat_command->data()); 2048 m_repeat_command.assign(*repeat_command); 2049 } else { 2050 m_repeat_command.assign(original_command_string); 2051 } 2052 } 2053 2054 if (add_to_history) 2055 m_command_history.AppendString(original_command_string); 2056 2057 std::string remainder; 2058 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size(); 2059 if (actual_cmd_name_len < command_string.length()) 2060 remainder = command_string.substr(actual_cmd_name_len); 2061 2062 // Remove any initial spaces 2063 size_t pos = remainder.find_first_not_of(k_white_space); 2064 if (pos != 0 && pos != std::string::npos) 2065 remainder.erase(0, pos); 2066 2067 LLDB_LOGF( 2068 log, "HandleCommand, command line after removing command name(s): '%s'", 2069 remainder.c_str()); 2070 2071 // To test whether or not transcript should be saved, `transcript_item` is 2072 // used instead of `GetSaveTrasncript()`. This is because the latter will 2073 // fail when the command is "settings set interpreter.save-transcript true". 2074 if (transcript_item) { 2075 transcript_item->AddStringItem("commandName", cmd_obj->GetCommandName()); 2076 transcript_item->AddStringItem("commandArguments", remainder); 2077 } 2078 2079 ElapsedTime elapsed(execute_time); 2080 cmd_obj->SetOriginalCommandString(real_original_command_string); 2081 cmd_obj->Execute(remainder.c_str(), result); 2082 } 2083 2084 LLDB_LOGF(log, "HandleCommand, command %s", 2085 (result.Succeeded() ? "succeeded" : "did not succeed")); 2086 2087 // To test whether or not transcript should be saved, `transcript_item` is 2088 // used instead of `GetSaveTrasncript()`. This is because the latter will 2089 // fail when the command is "settings set interpreter.save-transcript true". 2090 if (transcript_item) { 2091 m_transcript_stream << result.GetOutputData(); 2092 m_transcript_stream << result.GetErrorData(); 2093 2094 transcript_item->AddStringItem("output", result.GetOutputData()); 2095 transcript_item->AddStringItem("error", result.GetErrorData()); 2096 transcript_item->AddFloatItem("durationInSeconds", 2097 execute_time.get().count()); 2098 } 2099 2100 return result.Succeeded(); 2101 } 2102 2103 void CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) { 2104 bool look_for_subcommand = false; 2105 2106 // For any of the command completions a unique match will be a complete word. 2107 2108 if (request.GetParsedLine().GetArgumentCount() == 0) { 2109 // We got nothing on the command line, so return the list of commands 2110 bool include_aliases = true; 2111 StringList new_matches, descriptions; 2112 GetCommandNamesMatchingPartialString("", include_aliases, new_matches, 2113 descriptions); 2114 request.AddCompletions(new_matches, descriptions); 2115 } else if (request.GetCursorIndex() == 0) { 2116 // The cursor is in the first argument, so just do a lookup in the 2117 // dictionary. 2118 StringList new_matches, new_descriptions; 2119 CommandObject *cmd_obj = 2120 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0), 2121 &new_matches, &new_descriptions); 2122 2123 if (new_matches.GetSize() && cmd_obj && cmd_obj->IsMultiwordObject() && 2124 new_matches.GetStringAtIndex(0) != nullptr && 2125 strcmp(request.GetParsedLine().GetArgumentAtIndex(0), 2126 new_matches.GetStringAtIndex(0)) == 0) { 2127 if (request.GetParsedLine().GetArgumentCount() != 1) { 2128 look_for_subcommand = true; 2129 new_matches.DeleteStringAtIndex(0); 2130 new_descriptions.DeleteStringAtIndex(0); 2131 request.AppendEmptyArgument(); 2132 } 2133 } 2134 request.AddCompletions(new_matches, new_descriptions); 2135 } 2136 2137 if (request.GetCursorIndex() > 0 || look_for_subcommand) { 2138 // We are completing further on into a commands arguments, so find the 2139 // command and tell it to complete the command. First see if there is a 2140 // matching initial command: 2141 CommandObject *command_object = 2142 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0)); 2143 if (command_object) { 2144 request.ShiftArguments(); 2145 command_object->HandleCompletion(request); 2146 } 2147 } 2148 } 2149 2150 void CommandInterpreter::HandleCompletion(CompletionRequest &request) { 2151 2152 // Don't complete comments, and if the line we are completing is just the 2153 // history repeat character, substitute the appropriate history line. 2154 llvm::StringRef first_arg = request.GetParsedLine().GetArgumentAtIndex(0); 2155 2156 if (!first_arg.empty()) { 2157 if (first_arg.front() == m_comment_char) 2158 return; 2159 if (first_arg.front() == CommandHistory::g_repeat_char) { 2160 if (auto hist_str = m_command_history.FindString(first_arg)) 2161 request.AddCompletion(*hist_str, "Previous command history event", 2162 CompletionMode::RewriteLine); 2163 return; 2164 } 2165 } 2166 2167 HandleCompletionMatches(request); 2168 } 2169 2170 std::optional<std::string> 2171 CommandInterpreter::GetAutoSuggestionForCommand(llvm::StringRef line) { 2172 if (line.empty()) 2173 return std::nullopt; 2174 const size_t s = m_command_history.GetSize(); 2175 for (int i = s - 1; i >= 0; --i) { 2176 llvm::StringRef entry = m_command_history.GetStringAtIndex(i); 2177 if (entry.consume_front(line)) 2178 return entry.str(); 2179 } 2180 return std::nullopt; 2181 } 2182 2183 void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) { 2184 EventSP prompt_change_event_sp( 2185 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt))); 2186 ; 2187 BroadcastEvent(prompt_change_event_sp); 2188 if (m_command_io_handler_sp) 2189 m_command_io_handler_sp->SetPrompt(new_prompt); 2190 } 2191 2192 bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) { 2193 // Check AutoConfirm first: 2194 if (m_debugger.GetAutoConfirm()) 2195 return default_answer; 2196 2197 IOHandlerConfirm *confirm = 2198 new IOHandlerConfirm(m_debugger, message, default_answer); 2199 IOHandlerSP io_handler_sp(confirm); 2200 m_debugger.RunIOHandlerSync(io_handler_sp); 2201 return confirm->GetResponse(); 2202 } 2203 2204 const CommandAlias * 2205 CommandInterpreter::GetAlias(llvm::StringRef alias_name) const { 2206 OptionArgVectorSP ret_val; 2207 2208 auto pos = m_alias_dict.find(std::string(alias_name)); 2209 if (pos != m_alias_dict.end()) 2210 return (CommandAlias *)pos->second.get(); 2211 2212 return nullptr; 2213 } 2214 2215 bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); } 2216 2217 bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); } 2218 2219 bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); } 2220 2221 bool CommandInterpreter::HasUserMultiwordCommands() const { 2222 return (!m_user_mw_dict.empty()); 2223 } 2224 2225 bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); } 2226 2227 void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj, 2228 const char *alias_name, 2229 Args &cmd_args, 2230 std::string &raw_input_string, 2231 CommandReturnObject &result) { 2232 OptionArgVectorSP option_arg_vector_sp = 2233 GetAlias(alias_name)->GetOptionArguments(); 2234 2235 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString(); 2236 2237 // Make sure that the alias name is the 0th element in cmd_args 2238 std::string alias_name_str = alias_name; 2239 if (alias_name_str != cmd_args.GetArgumentAtIndex(0)) 2240 cmd_args.Unshift(alias_name_str); 2241 2242 Args new_args(alias_cmd_obj->GetCommandName()); 2243 if (new_args.GetArgumentCount() == 2) 2244 new_args.Shift(); 2245 2246 if (option_arg_vector_sp.get()) { 2247 if (wants_raw_input) { 2248 // We have a command that both has command options and takes raw input. 2249 // Make *sure* it has a " -- " in the right place in the 2250 // raw_input_string. 2251 size_t pos = raw_input_string.find(" -- "); 2252 if (pos == std::string::npos) { 2253 // None found; assume it goes at the beginning of the raw input string 2254 raw_input_string.insert(0, " -- "); 2255 } 2256 } 2257 2258 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 2259 const size_t old_size = cmd_args.GetArgumentCount(); 2260 std::vector<bool> used(old_size + 1, false); 2261 2262 used[0] = true; 2263 2264 int value_type; 2265 std::string option; 2266 std::string value; 2267 for (const auto &option_entry : *option_arg_vector) { 2268 std::tie(option, value_type, value) = option_entry; 2269 if (option == g_argument) { 2270 if (!wants_raw_input || (value != "--")) { 2271 // Since we inserted this above, make sure we don't insert it twice 2272 new_args.AppendArgument(value); 2273 } 2274 continue; 2275 } 2276 2277 if (value_type != OptionParser::eOptionalArgument) 2278 new_args.AppendArgument(option); 2279 2280 if (value == g_no_argument) 2281 continue; 2282 2283 int index = GetOptionArgumentPosition(value.c_str()); 2284 if (index == 0) { 2285 // value was NOT a positional argument; must be a real value 2286 if (value_type != OptionParser::eOptionalArgument) 2287 new_args.AppendArgument(value); 2288 else { 2289 new_args.AppendArgument(option + value); 2290 } 2291 2292 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) { 2293 result.AppendErrorWithFormat("Not enough arguments provided; you " 2294 "need at least %d arguments to use " 2295 "this alias.\n", 2296 index); 2297 return; 2298 } else { 2299 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string 2300 size_t strpos = 2301 raw_input_string.find(cmd_args.GetArgumentAtIndex(index)); 2302 if (strpos != std::string::npos) { 2303 raw_input_string = raw_input_string.erase( 2304 strpos, strlen(cmd_args.GetArgumentAtIndex(index))); 2305 } 2306 2307 if (value_type != OptionParser::eOptionalArgument) 2308 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index)); 2309 else { 2310 new_args.AppendArgument(option + cmd_args.GetArgumentAtIndex(index)); 2311 } 2312 used[index] = true; 2313 } 2314 } 2315 2316 for (auto entry : llvm::enumerate(cmd_args.entries())) { 2317 if (!used[entry.index()] && !wants_raw_input) 2318 new_args.AppendArgument(entry.value().ref()); 2319 } 2320 2321 cmd_args.Clear(); 2322 cmd_args.SetArguments(new_args.GetArgumentCount(), 2323 new_args.GetConstArgumentVector()); 2324 } else { 2325 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2326 // This alias was not created with any options; nothing further needs to be 2327 // done, unless it is a command that wants raw input, in which case we need 2328 // to clear the rest of the data from cmd_args, since its in the raw input 2329 // string. 2330 if (wants_raw_input) { 2331 cmd_args.Clear(); 2332 cmd_args.SetArguments(new_args.GetArgumentCount(), 2333 new_args.GetConstArgumentVector()); 2334 } 2335 return; 2336 } 2337 2338 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2339 } 2340 2341 int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) { 2342 int position = 0; // Any string that isn't an argument position, i.e. '%' 2343 // followed by an integer, gets a position 2344 // of zero. 2345 2346 const char *cptr = in_string; 2347 2348 // Does it start with '%' 2349 if (cptr[0] == '%') { 2350 ++cptr; 2351 2352 // Is the rest of it entirely digits? 2353 if (isdigit(cptr[0])) { 2354 const char *start = cptr; 2355 while (isdigit(cptr[0])) 2356 ++cptr; 2357 2358 // We've gotten to the end of the digits; are we at the end of the 2359 // string? 2360 if (cptr[0] == '\0') 2361 position = atoi(start); 2362 } 2363 } 2364 2365 return position; 2366 } 2367 2368 static void GetHomeInitFile(llvm::SmallVectorImpl<char> &init_file, 2369 llvm::StringRef suffix = {}) { 2370 std::string init_file_name = ".lldbinit"; 2371 if (!suffix.empty()) { 2372 init_file_name.append("-"); 2373 init_file_name.append(suffix.str()); 2374 } 2375 2376 FileSystem::Instance().GetHomeDirectory(init_file); 2377 llvm::sys::path::append(init_file, init_file_name); 2378 2379 FileSystem::Instance().Resolve(init_file); 2380 } 2381 2382 static void GetHomeREPLInitFile(llvm::SmallVectorImpl<char> &init_file, 2383 LanguageType language) { 2384 if (language == eLanguageTypeUnknown) { 2385 LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs(); 2386 if (auto main_repl_language = repl_languages.GetSingularLanguage()) 2387 language = *main_repl_language; 2388 else 2389 return; 2390 } 2391 2392 std::string init_file_name = 2393 (llvm::Twine(".lldbinit-") + 2394 llvm::Twine(Language::GetNameForLanguageType(language)) + 2395 llvm::Twine("-repl")) 2396 .str(); 2397 FileSystem::Instance().GetHomeDirectory(init_file); 2398 llvm::sys::path::append(init_file, init_file_name); 2399 FileSystem::Instance().Resolve(init_file); 2400 } 2401 2402 static void GetCwdInitFile(llvm::SmallVectorImpl<char> &init_file) { 2403 llvm::StringRef s = ".lldbinit"; 2404 init_file.assign(s.begin(), s.end()); 2405 FileSystem::Instance().Resolve(init_file); 2406 } 2407 2408 void CommandInterpreter::SourceInitFile(FileSpec file, 2409 CommandReturnObject &result) { 2410 assert(!m_skip_lldbinit_files); 2411 2412 if (!FileSystem::Instance().Exists(file)) { 2413 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2414 return; 2415 } 2416 2417 // Use HandleCommand to 'source' the given file; this will do the actual 2418 // broadcasting of the commands back to any appropriate listener (see 2419 // CommandObjectSource::Execute for more details). 2420 const bool saved_batch = SetBatchCommandMode(true); 2421 CommandInterpreterRunOptions options; 2422 options.SetSilent(true); 2423 options.SetPrintErrors(true); 2424 options.SetStopOnError(false); 2425 options.SetStopOnContinue(true); 2426 HandleCommandsFromFile(file, options, result); 2427 SetBatchCommandMode(saved_batch); 2428 } 2429 2430 void CommandInterpreter::SourceInitFileCwd(CommandReturnObject &result) { 2431 if (m_skip_lldbinit_files) { 2432 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2433 return; 2434 } 2435 2436 llvm::SmallString<128> init_file; 2437 GetCwdInitFile(init_file); 2438 if (!FileSystem::Instance().Exists(init_file)) { 2439 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2440 return; 2441 } 2442 2443 LoadCWDlldbinitFile should_load = 2444 Target::GetGlobalProperties().GetLoadCWDlldbinitFile(); 2445 2446 switch (should_load) { 2447 case eLoadCWDlldbinitFalse: 2448 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2449 break; 2450 case eLoadCWDlldbinitTrue: 2451 SourceInitFile(FileSpec(init_file.str()), result); 2452 break; 2453 case eLoadCWDlldbinitWarn: { 2454 llvm::SmallString<128> home_init_file; 2455 GetHomeInitFile(home_init_file); 2456 if (llvm::sys::path::parent_path(init_file) == 2457 llvm::sys::path::parent_path(home_init_file)) { 2458 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2459 } else { 2460 result.AppendError(InitFileWarning); 2461 } 2462 } 2463 } 2464 } 2465 2466 /// We will first see if there is an application specific ".lldbinit" file 2467 /// whose name is "~/.lldbinit" followed by a "-" and the name of the program. 2468 /// If this file doesn't exist, we fall back to the REPL init file or the 2469 /// default home init file in "~/.lldbinit". 2470 void CommandInterpreter::SourceInitFileHome(CommandReturnObject &result, 2471 bool is_repl) { 2472 if (m_skip_lldbinit_files) { 2473 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2474 return; 2475 } 2476 2477 llvm::SmallString<128> init_file; 2478 2479 if (is_repl) 2480 GetHomeREPLInitFile(init_file, GetDebugger().GetREPLLanguage()); 2481 2482 if (init_file.empty()) 2483 GetHomeInitFile(init_file); 2484 2485 if (!m_skip_app_init_files) { 2486 llvm::StringRef program_name = 2487 HostInfo::GetProgramFileSpec().GetFilename().GetStringRef(); 2488 llvm::SmallString<128> program_init_file; 2489 GetHomeInitFile(program_init_file, program_name); 2490 if (FileSystem::Instance().Exists(program_init_file)) 2491 init_file = program_init_file; 2492 } 2493 2494 SourceInitFile(FileSpec(init_file.str()), result); 2495 } 2496 2497 void CommandInterpreter::SourceInitFileGlobal(CommandReturnObject &result) { 2498 #ifdef LLDB_GLOBAL_INIT_DIRECTORY 2499 if (!m_skip_lldbinit_files) { 2500 FileSpec init_file(LLDB_GLOBAL_INIT_DIRECTORY); 2501 if (init_file) 2502 init_file.MakeAbsolute(HostInfo::GetShlibDir()); 2503 2504 init_file.AppendPathComponent("lldbinit"); 2505 SourceInitFile(init_file, result); 2506 return; 2507 } 2508 #endif 2509 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2510 } 2511 2512 const char *CommandInterpreter::GetCommandPrefix() { 2513 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix(); 2514 return prefix == nullptr ? "" : prefix; 2515 } 2516 2517 PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) { 2518 PlatformSP platform_sp; 2519 if (prefer_target_platform) { 2520 ExecutionContext exe_ctx(GetExecutionContext()); 2521 Target *target = exe_ctx.GetTargetPtr(); 2522 if (target) 2523 platform_sp = target->GetPlatform(); 2524 } 2525 2526 if (!platform_sp) 2527 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform(); 2528 return platform_sp; 2529 } 2530 2531 bool CommandInterpreter::DidProcessStopAbnormally() const { 2532 auto exe_ctx = GetExecutionContext(); 2533 TargetSP target_sp = exe_ctx.GetTargetSP(); 2534 if (!target_sp) 2535 return false; 2536 2537 ProcessSP process_sp(target_sp->GetProcessSP()); 2538 if (!process_sp) 2539 return false; 2540 2541 if (eStateStopped != process_sp->GetState()) 2542 return false; 2543 2544 for (const auto &thread_sp : process_sp->GetThreadList().Threads()) { 2545 StopInfoSP stop_info = thread_sp->GetStopInfo(); 2546 if (!stop_info) { 2547 // If there's no stop_info, keep iterating through the other threads; 2548 // it's enough that any thread has got a stop_info that indicates 2549 // an abnormal stop, to consider the process to be stopped abnormally. 2550 continue; 2551 } 2552 2553 const StopReason reason = stop_info->GetStopReason(); 2554 if (reason == eStopReasonException || 2555 reason == eStopReasonInstrumentation || 2556 reason == eStopReasonProcessorTrace || reason == eStopReasonInterrupt || 2557 reason == eStopReasonHistoryBoundary) 2558 return true; 2559 2560 if (reason == eStopReasonSignal) { 2561 const auto stop_signal = static_cast<int32_t>(stop_info->GetValue()); 2562 UnixSignalsSP signals_sp = process_sp->GetUnixSignals(); 2563 if (!signals_sp || !signals_sp->SignalIsValid(stop_signal)) 2564 // The signal is unknown, treat it as abnormal. 2565 return true; 2566 2567 const auto sigint_num = signals_sp->GetSignalNumberFromName("SIGINT"); 2568 const auto sigstop_num = signals_sp->GetSignalNumberFromName("SIGSTOP"); 2569 if ((stop_signal != sigint_num) && (stop_signal != sigstop_num)) 2570 // The signal very likely implies a crash. 2571 return true; 2572 } 2573 } 2574 2575 return false; 2576 } 2577 2578 void 2579 CommandInterpreter::HandleCommands(const StringList &commands, 2580 const ExecutionContext &override_context, 2581 const CommandInterpreterRunOptions &options, 2582 CommandReturnObject &result) { 2583 2584 OverrideExecutionContext(override_context); 2585 HandleCommands(commands, options, result); 2586 RestoreExecutionContext(); 2587 } 2588 2589 void CommandInterpreter::HandleCommands(const StringList &commands, 2590 const CommandInterpreterRunOptions &options, 2591 CommandReturnObject &result) { 2592 size_t num_lines = commands.GetSize(); 2593 2594 // If we are going to continue past a "continue" then we need to run the 2595 // commands synchronously. Make sure you reset this value anywhere you return 2596 // from the function. 2597 2598 bool old_async_execution = m_debugger.GetAsyncExecution(); 2599 2600 if (!options.GetStopOnContinue()) { 2601 m_debugger.SetAsyncExecution(false); 2602 } 2603 2604 for (size_t idx = 0; idx < num_lines; idx++) { 2605 const char *cmd = commands.GetStringAtIndex(idx); 2606 if (cmd[0] == '\0') 2607 continue; 2608 2609 if (options.GetEchoCommands()) { 2610 // TODO: Add Stream support. 2611 result.AppendMessageWithFormat("%s %s\n", 2612 m_debugger.GetPrompt().str().c_str(), cmd); 2613 } 2614 2615 CommandReturnObject tmp_result(m_debugger.GetUseColor()); 2616 tmp_result.SetInteractive(result.GetInteractive()); 2617 tmp_result.SetSuppressImmediateOutput(true); 2618 2619 // We might call into a regex or alias command, in which case the 2620 // add_to_history will get lost. This m_command_source_depth dingus is the 2621 // way we turn off adding to the history in that case, so set it up here. 2622 if (!options.GetAddToHistory()) 2623 m_command_source_depth++; 2624 bool success = HandleCommand(cmd, options.m_add_to_history, tmp_result); 2625 if (!options.GetAddToHistory()) 2626 m_command_source_depth--; 2627 2628 if (options.GetPrintResults()) { 2629 if (tmp_result.Succeeded()) 2630 result.AppendMessage(tmp_result.GetOutputData()); 2631 } 2632 2633 if (!success || !tmp_result.Succeeded()) { 2634 llvm::StringRef error_msg = tmp_result.GetErrorData(); 2635 if (error_msg.empty()) 2636 error_msg = "<unknown error>.\n"; 2637 if (options.GetStopOnError()) { 2638 result.AppendErrorWithFormat( 2639 "Aborting reading of commands after command #%" PRIu64 2640 ": '%s' failed with %s", 2641 (uint64_t)idx, cmd, error_msg.str().c_str()); 2642 m_debugger.SetAsyncExecution(old_async_execution); 2643 return; 2644 } else if (options.GetPrintResults()) { 2645 result.AppendMessageWithFormat( 2646 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd, 2647 error_msg.str().c_str()); 2648 } 2649 } 2650 2651 if (result.GetImmediateOutputStream()) 2652 result.GetImmediateOutputStream()->Flush(); 2653 2654 if (result.GetImmediateErrorStream()) 2655 result.GetImmediateErrorStream()->Flush(); 2656 2657 // N.B. Can't depend on DidChangeProcessState, because the state coming 2658 // into the command execution could be running (for instance in Breakpoint 2659 // Commands. So we check the return value to see if it is has running in 2660 // it. 2661 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) || 2662 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) { 2663 if (options.GetStopOnContinue()) { 2664 // If we caused the target to proceed, and we're going to stop in that 2665 // case, set the status in our real result before returning. This is 2666 // an error if the continue was not the last command in the set of 2667 // commands to be run. 2668 if (idx != num_lines - 1) 2669 result.AppendErrorWithFormat( 2670 "Aborting reading of commands after command #%" PRIu64 2671 ": '%s' continued the target.\n", 2672 (uint64_t)idx + 1, cmd); 2673 else 2674 result.AppendMessageWithFormat("Command #%" PRIu64 2675 " '%s' continued the target.\n", 2676 (uint64_t)idx + 1, cmd); 2677 2678 result.SetStatus(tmp_result.GetStatus()); 2679 m_debugger.SetAsyncExecution(old_async_execution); 2680 2681 return; 2682 } 2683 } 2684 2685 // Also check for "stop on crash here: 2686 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash() && 2687 DidProcessStopAbnormally()) { 2688 if (idx != num_lines - 1) 2689 result.AppendErrorWithFormat( 2690 "Aborting reading of commands after command #%" PRIu64 2691 ": '%s' stopped with a signal or exception.\n", 2692 (uint64_t)idx + 1, cmd); 2693 else 2694 result.AppendMessageWithFormat( 2695 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n", 2696 (uint64_t)idx + 1, cmd); 2697 2698 result.SetStatus(tmp_result.GetStatus()); 2699 m_debugger.SetAsyncExecution(old_async_execution); 2700 2701 return; 2702 } 2703 } 2704 2705 result.SetStatus(eReturnStatusSuccessFinishResult); 2706 m_debugger.SetAsyncExecution(old_async_execution); 2707 } 2708 2709 // Make flags that we can pass into the IOHandler so our delegates can do the 2710 // right thing 2711 enum { 2712 eHandleCommandFlagStopOnContinue = (1u << 0), 2713 eHandleCommandFlagStopOnError = (1u << 1), 2714 eHandleCommandFlagEchoCommand = (1u << 2), 2715 eHandleCommandFlagEchoCommentCommand = (1u << 3), 2716 eHandleCommandFlagPrintResult = (1u << 4), 2717 eHandleCommandFlagPrintErrors = (1u << 5), 2718 eHandleCommandFlagStopOnCrash = (1u << 6), 2719 eHandleCommandFlagAllowRepeats = (1u << 7) 2720 }; 2721 2722 void CommandInterpreter::HandleCommandsFromFile( 2723 FileSpec &cmd_file, const ExecutionContext &context, 2724 const CommandInterpreterRunOptions &options, CommandReturnObject &result) { 2725 OverrideExecutionContext(context); 2726 HandleCommandsFromFile(cmd_file, options, result); 2727 RestoreExecutionContext(); 2728 } 2729 2730 void CommandInterpreter::HandleCommandsFromFile(FileSpec &cmd_file, 2731 const CommandInterpreterRunOptions &options, CommandReturnObject &result) { 2732 if (!FileSystem::Instance().Exists(cmd_file)) { 2733 result.AppendErrorWithFormat( 2734 "Error reading commands from file %s - file not found.\n", 2735 cmd_file.GetFilename().AsCString("<Unknown>")); 2736 return; 2737 } 2738 2739 std::string cmd_file_path = cmd_file.GetPath(); 2740 auto input_file_up = 2741 FileSystem::Instance().Open(cmd_file, File::eOpenOptionReadOnly); 2742 if (!input_file_up) { 2743 std::string error = llvm::toString(input_file_up.takeError()); 2744 result.AppendErrorWithFormatv( 2745 "error: an error occurred read file '{0}': {1}\n", cmd_file_path, 2746 llvm::fmt_consume(input_file_up.takeError())); 2747 return; 2748 } 2749 FileSP input_file_sp = FileSP(std::move(input_file_up.get())); 2750 2751 Debugger &debugger = GetDebugger(); 2752 2753 uint32_t flags = 0; 2754 2755 if (options.m_stop_on_continue == eLazyBoolCalculate) { 2756 if (m_command_source_flags.empty()) { 2757 // Stop on continue by default 2758 flags |= eHandleCommandFlagStopOnContinue; 2759 } else if (m_command_source_flags.back() & 2760 eHandleCommandFlagStopOnContinue) { 2761 flags |= eHandleCommandFlagStopOnContinue; 2762 } 2763 } else if (options.m_stop_on_continue == eLazyBoolYes) { 2764 flags |= eHandleCommandFlagStopOnContinue; 2765 } 2766 2767 if (options.m_stop_on_error == eLazyBoolCalculate) { 2768 if (m_command_source_flags.empty()) { 2769 if (GetStopCmdSourceOnError()) 2770 flags |= eHandleCommandFlagStopOnError; 2771 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) { 2772 flags |= eHandleCommandFlagStopOnError; 2773 } 2774 } else if (options.m_stop_on_error == eLazyBoolYes) { 2775 flags |= eHandleCommandFlagStopOnError; 2776 } 2777 2778 // stop-on-crash can only be set, if it is present in all levels of 2779 // pushed flag sets. 2780 if (options.GetStopOnCrash()) { 2781 if (m_command_source_flags.empty()) { 2782 flags |= eHandleCommandFlagStopOnCrash; 2783 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) { 2784 flags |= eHandleCommandFlagStopOnCrash; 2785 } 2786 } 2787 2788 if (options.m_echo_commands == eLazyBoolCalculate) { 2789 if (m_command_source_flags.empty()) { 2790 // Echo command by default 2791 flags |= eHandleCommandFlagEchoCommand; 2792 } else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) { 2793 flags |= eHandleCommandFlagEchoCommand; 2794 } 2795 } else if (options.m_echo_commands == eLazyBoolYes) { 2796 flags |= eHandleCommandFlagEchoCommand; 2797 } 2798 2799 // We will only ever ask for this flag, if we echo commands in general. 2800 if (options.m_echo_comment_commands == eLazyBoolCalculate) { 2801 if (m_command_source_flags.empty()) { 2802 // Echo comments by default 2803 flags |= eHandleCommandFlagEchoCommentCommand; 2804 } else if (m_command_source_flags.back() & 2805 eHandleCommandFlagEchoCommentCommand) { 2806 flags |= eHandleCommandFlagEchoCommentCommand; 2807 } 2808 } else if (options.m_echo_comment_commands == eLazyBoolYes) { 2809 flags |= eHandleCommandFlagEchoCommentCommand; 2810 } 2811 2812 if (options.m_print_results == eLazyBoolCalculate) { 2813 if (m_command_source_flags.empty()) { 2814 // Print output by default 2815 flags |= eHandleCommandFlagPrintResult; 2816 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) { 2817 flags |= eHandleCommandFlagPrintResult; 2818 } 2819 } else if (options.m_print_results == eLazyBoolYes) { 2820 flags |= eHandleCommandFlagPrintResult; 2821 } 2822 2823 if (options.m_print_errors == eLazyBoolCalculate) { 2824 if (m_command_source_flags.empty()) { 2825 // Print output by default 2826 flags |= eHandleCommandFlagPrintErrors; 2827 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintErrors) { 2828 flags |= eHandleCommandFlagPrintErrors; 2829 } 2830 } else if (options.m_print_errors == eLazyBoolYes) { 2831 flags |= eHandleCommandFlagPrintErrors; 2832 } 2833 2834 if (flags & eHandleCommandFlagPrintResult) { 2835 debugger.GetOutputFile().Printf("Executing commands in '%s'.\n", 2836 cmd_file_path.c_str()); 2837 } 2838 2839 // Used for inheriting the right settings when "command source" might 2840 // have nested "command source" commands 2841 lldb::StreamFileSP empty_stream_sp; 2842 m_command_source_flags.push_back(flags); 2843 IOHandlerSP io_handler_sp(new IOHandlerEditline( 2844 debugger, IOHandler::Type::CommandInterpreter, input_file_sp, 2845 empty_stream_sp, // Pass in an empty stream so we inherit the top 2846 // input reader output stream 2847 empty_stream_sp, // Pass in an empty stream so we inherit the top 2848 // input reader error stream 2849 flags, 2850 nullptr, // Pass in NULL for "editline_name" so no history is saved, 2851 // or written 2852 debugger.GetPrompt(), llvm::StringRef(), 2853 false, // Not multi-line 2854 debugger.GetUseColor(), 0, *this)); 2855 const bool old_async_execution = debugger.GetAsyncExecution(); 2856 2857 // Set synchronous execution if we are not stopping on continue 2858 if ((flags & eHandleCommandFlagStopOnContinue) == 0) 2859 debugger.SetAsyncExecution(false); 2860 2861 m_command_source_depth++; 2862 m_command_source_dirs.push_back(cmd_file.CopyByRemovingLastPathComponent()); 2863 2864 debugger.RunIOHandlerSync(io_handler_sp); 2865 if (!m_command_source_flags.empty()) 2866 m_command_source_flags.pop_back(); 2867 2868 m_command_source_dirs.pop_back(); 2869 m_command_source_depth--; 2870 2871 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2872 debugger.SetAsyncExecution(old_async_execution); 2873 } 2874 2875 bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; } 2876 2877 void CommandInterpreter::SetSynchronous(bool value) { 2878 m_synchronous_execution = value; 2879 } 2880 2881 void CommandInterpreter::OutputFormattedHelpText(Stream &strm, 2882 llvm::StringRef prefix, 2883 llvm::StringRef help_text) { 2884 const uint32_t max_columns = m_debugger.GetTerminalWidth(); 2885 2886 size_t line_width_max = max_columns - prefix.size(); 2887 if (line_width_max < 16) 2888 line_width_max = help_text.size() + prefix.size(); 2889 2890 strm.IndentMore(prefix.size()); 2891 bool prefixed_yet = false; 2892 // Even if we have no help text we still want to emit the command name. 2893 if (help_text.empty()) 2894 help_text = "No help text"; 2895 while (!help_text.empty()) { 2896 // Prefix the first line, indent subsequent lines to line up 2897 if (!prefixed_yet) { 2898 strm << prefix; 2899 prefixed_yet = true; 2900 } else 2901 strm.Indent(); 2902 2903 // Never print more than the maximum on one line. 2904 llvm::StringRef this_line = help_text.substr(0, line_width_max); 2905 2906 // Always break on an explicit newline. 2907 std::size_t first_newline = this_line.find_first_of("\n"); 2908 2909 // Don't break on space/tab unless the text is too long to fit on one line. 2910 std::size_t last_space = llvm::StringRef::npos; 2911 if (this_line.size() != help_text.size()) 2912 last_space = this_line.find_last_of(" \t"); 2913 2914 // Break at whichever condition triggered first. 2915 this_line = this_line.substr(0, std::min(first_newline, last_space)); 2916 strm.PutCString(this_line); 2917 strm.EOL(); 2918 2919 // Remove whitespace / newlines after breaking. 2920 help_text = help_text.drop_front(this_line.size()).ltrim(); 2921 } 2922 strm.IndentLess(prefix.size()); 2923 } 2924 2925 void CommandInterpreter::OutputFormattedHelpText(Stream &strm, 2926 llvm::StringRef word_text, 2927 llvm::StringRef separator, 2928 llvm::StringRef help_text, 2929 size_t max_word_len) { 2930 StreamString prefix_stream; 2931 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(), 2932 (int)separator.size(), separator.data()); 2933 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text); 2934 } 2935 2936 void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text, 2937 llvm::StringRef separator, 2938 llvm::StringRef help_text, 2939 uint32_t max_word_len) { 2940 int indent_size = max_word_len + separator.size() + 2; 2941 2942 strm.IndentMore(indent_size); 2943 2944 StreamString text_strm; 2945 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data()); 2946 text_strm << separator << " " << help_text; 2947 2948 const uint32_t max_columns = m_debugger.GetTerminalWidth(); 2949 2950 llvm::StringRef text = text_strm.GetString(); 2951 2952 uint32_t chars_left = max_columns; 2953 2954 auto nextWordLength = [](llvm::StringRef S) { 2955 size_t pos = S.find(' '); 2956 return pos == llvm::StringRef::npos ? S.size() : pos; 2957 }; 2958 2959 while (!text.empty()) { 2960 if (text.front() == '\n' || 2961 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) { 2962 strm.EOL(); 2963 strm.Indent(); 2964 chars_left = max_columns - indent_size; 2965 if (text.front() == '\n') 2966 text = text.drop_front(); 2967 else 2968 text = text.ltrim(' '); 2969 } else { 2970 strm.PutChar(text.front()); 2971 --chars_left; 2972 text = text.drop_front(); 2973 } 2974 } 2975 2976 strm.EOL(); 2977 strm.IndentLess(indent_size); 2978 } 2979 2980 void CommandInterpreter::FindCommandsForApropos( 2981 llvm::StringRef search_word, StringList &commands_found, 2982 StringList &commands_help, const CommandObject::CommandMap &command_map) { 2983 for (const auto &pair : command_map) { 2984 llvm::StringRef command_name = pair.first; 2985 CommandObject *cmd_obj = pair.second.get(); 2986 2987 const bool search_short_help = true; 2988 const bool search_long_help = false; 2989 const bool search_syntax = false; 2990 const bool search_options = false; 2991 if (command_name.contains_insensitive(search_word) || 2992 cmd_obj->HelpTextContainsWord(search_word, search_short_help, 2993 search_long_help, search_syntax, 2994 search_options)) { 2995 commands_found.AppendString(command_name); 2996 commands_help.AppendString(cmd_obj->GetHelp()); 2997 } 2998 2999 if (auto *multiword_cmd = cmd_obj->GetAsMultiwordCommand()) { 3000 StringList subcommands_found; 3001 FindCommandsForApropos(search_word, subcommands_found, commands_help, 3002 multiword_cmd->GetSubcommandDictionary()); 3003 for (const auto &subcommand_name : subcommands_found) { 3004 std::string qualified_name = 3005 (command_name + " " + subcommand_name).str(); 3006 commands_found.AppendString(qualified_name); 3007 } 3008 } 3009 } 3010 } 3011 3012 void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word, 3013 StringList &commands_found, 3014 StringList &commands_help, 3015 bool search_builtin_commands, 3016 bool search_user_commands, 3017 bool search_alias_commands, 3018 bool search_user_mw_commands) { 3019 CommandObject::CommandMap::const_iterator pos; 3020 3021 if (search_builtin_commands) 3022 FindCommandsForApropos(search_word, commands_found, commands_help, 3023 m_command_dict); 3024 3025 if (search_user_commands) 3026 FindCommandsForApropos(search_word, commands_found, commands_help, 3027 m_user_dict); 3028 3029 if (search_user_mw_commands) 3030 FindCommandsForApropos(search_word, commands_found, commands_help, 3031 m_user_mw_dict); 3032 3033 if (search_alias_commands) 3034 FindCommandsForApropos(search_word, commands_found, commands_help, 3035 m_alias_dict); 3036 } 3037 3038 ExecutionContext CommandInterpreter::GetExecutionContext() const { 3039 return !m_overriden_exe_contexts.empty() 3040 ? m_overriden_exe_contexts.top() 3041 : m_debugger.GetSelectedExecutionContext(); 3042 } 3043 3044 void CommandInterpreter::OverrideExecutionContext( 3045 const ExecutionContext &override_context) { 3046 m_overriden_exe_contexts.push(override_context); 3047 } 3048 3049 void CommandInterpreter::RestoreExecutionContext() { 3050 if (!m_overriden_exe_contexts.empty()) 3051 m_overriden_exe_contexts.pop(); 3052 } 3053 3054 void CommandInterpreter::GetProcessOutput() { 3055 if (ProcessSP process_sp = GetExecutionContext().GetProcessSP()) 3056 m_debugger.FlushProcessOutput(*process_sp, /*flush_stdout*/ true, 3057 /*flush_stderr*/ true); 3058 } 3059 3060 void CommandInterpreter::StartHandlingCommand() { 3061 auto idle_state = CommandHandlingState::eIdle; 3062 if (m_command_state.compare_exchange_strong( 3063 idle_state, CommandHandlingState::eInProgress)) 3064 lldbassert(m_iohandler_nesting_level == 0); 3065 else 3066 lldbassert(m_iohandler_nesting_level > 0); 3067 ++m_iohandler_nesting_level; 3068 } 3069 3070 void CommandInterpreter::FinishHandlingCommand() { 3071 lldbassert(m_iohandler_nesting_level > 0); 3072 if (--m_iohandler_nesting_level == 0) { 3073 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle); 3074 lldbassert(prev_state != CommandHandlingState::eIdle); 3075 } 3076 } 3077 3078 bool CommandInterpreter::InterruptCommand() { 3079 auto in_progress = CommandHandlingState::eInProgress; 3080 return m_command_state.compare_exchange_strong( 3081 in_progress, CommandHandlingState::eInterrupted); 3082 } 3083 3084 bool CommandInterpreter::WasInterrupted() const { 3085 if (!m_debugger.IsIOHandlerThreadCurrentThread()) 3086 return false; 3087 3088 bool was_interrupted = 3089 (m_command_state == CommandHandlingState::eInterrupted); 3090 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0); 3091 return was_interrupted; 3092 } 3093 3094 void CommandInterpreter::PrintCommandOutput(IOHandler &io_handler, 3095 llvm::StringRef str, 3096 bool is_stdout) { 3097 3098 lldb::StreamFileSP stream = is_stdout ? io_handler.GetOutputStreamFileSP() 3099 : io_handler.GetErrorStreamFileSP(); 3100 // Split the output into lines and poll for interrupt requests 3101 bool had_output = !str.empty(); 3102 while (!str.empty()) { 3103 llvm::StringRef line; 3104 std::tie(line, str) = str.split('\n'); 3105 { 3106 std::lock_guard<std::recursive_mutex> guard(io_handler.GetOutputMutex()); 3107 stream->Write(line.data(), line.size()); 3108 stream->Write("\n", 1); 3109 } 3110 } 3111 3112 std::lock_guard<std::recursive_mutex> guard(io_handler.GetOutputMutex()); 3113 if (had_output && 3114 INTERRUPT_REQUESTED(GetDebugger(), "Interrupted dumping command output")) 3115 stream->Printf("\n... Interrupted.\n"); 3116 stream->Flush(); 3117 } 3118 3119 bool CommandInterpreter::EchoCommandNonInteractive( 3120 llvm::StringRef line, const Flags &io_handler_flags) const { 3121 if (!io_handler_flags.Test(eHandleCommandFlagEchoCommand)) 3122 return false; 3123 3124 llvm::StringRef command = line.trim(); 3125 if (command.empty()) 3126 return true; 3127 3128 if (command.front() == m_comment_char) 3129 return io_handler_flags.Test(eHandleCommandFlagEchoCommentCommand); 3130 3131 return true; 3132 } 3133 3134 void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler, 3135 std::string &line) { 3136 // If we were interrupted, bail out... 3137 if (WasInterrupted()) 3138 return; 3139 3140 const bool is_interactive = io_handler.GetIsInteractive(); 3141 const bool allow_repeats = 3142 io_handler.GetFlags().Test(eHandleCommandFlagAllowRepeats); 3143 3144 if (!is_interactive && !allow_repeats) { 3145 // When we are not interactive, don't execute blank lines. This will happen 3146 // sourcing a commands file. We don't want blank lines to repeat the 3147 // previous command and cause any errors to occur (like redefining an 3148 // alias, get an error and stop parsing the commands file). 3149 // But obey the AllowRepeats flag if the user has set it. 3150 if (line.empty()) 3151 return; 3152 } 3153 if (!is_interactive) { 3154 // When using a non-interactive file handle (like when sourcing commands 3155 // from a file) we need to echo the command out so we don't just see the 3156 // command output and no command... 3157 if (EchoCommandNonInteractive(line, io_handler.GetFlags())) { 3158 std::lock_guard<std::recursive_mutex> guard(io_handler.GetOutputMutex()); 3159 io_handler.GetOutputStreamFileSP()->Printf( 3160 "%s%s\n", io_handler.GetPrompt(), line.c_str()); 3161 } 3162 } 3163 3164 StartHandlingCommand(); 3165 3166 ExecutionContext exe_ctx = m_debugger.GetSelectedExecutionContext(); 3167 bool pushed_exe_ctx = false; 3168 if (exe_ctx.HasTargetScope()) { 3169 OverrideExecutionContext(exe_ctx); 3170 pushed_exe_ctx = true; 3171 } 3172 auto finalize = llvm::make_scope_exit([this, pushed_exe_ctx]() { 3173 if (pushed_exe_ctx) 3174 RestoreExecutionContext(); 3175 }); 3176 3177 lldb_private::CommandReturnObject result(m_debugger.GetUseColor()); 3178 HandleCommand(line.c_str(), eLazyBoolCalculate, result); 3179 3180 // Now emit the command output text from the command we just executed 3181 if ((result.Succeeded() && 3182 io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) || 3183 io_handler.GetFlags().Test(eHandleCommandFlagPrintErrors)) { 3184 // Display any STDOUT/STDERR _prior_ to emitting the command result text 3185 GetProcessOutput(); 3186 3187 if (!result.GetImmediateOutputStream()) { 3188 llvm::StringRef output = result.GetOutputData(); 3189 PrintCommandOutput(io_handler, output, true); 3190 } 3191 3192 // Now emit the command error text from the command we just executed 3193 if (!result.GetImmediateErrorStream()) { 3194 llvm::StringRef error = result.GetErrorData(); 3195 PrintCommandOutput(io_handler, error, false); 3196 } 3197 } 3198 3199 FinishHandlingCommand(); 3200 3201 switch (result.GetStatus()) { 3202 case eReturnStatusInvalid: 3203 case eReturnStatusSuccessFinishNoResult: 3204 case eReturnStatusSuccessFinishResult: 3205 case eReturnStatusStarted: 3206 break; 3207 3208 case eReturnStatusSuccessContinuingNoResult: 3209 case eReturnStatusSuccessContinuingResult: 3210 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue)) 3211 io_handler.SetIsDone(true); 3212 break; 3213 3214 case eReturnStatusFailed: 3215 m_result.IncrementNumberOfErrors(); 3216 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError)) { 3217 m_result.SetResult(lldb::eCommandInterpreterResultCommandError); 3218 io_handler.SetIsDone(true); 3219 } 3220 break; 3221 3222 case eReturnStatusQuit: 3223 m_result.SetResult(lldb::eCommandInterpreterResultQuitRequested); 3224 io_handler.SetIsDone(true); 3225 break; 3226 } 3227 3228 // Finally, if we're going to stop on crash, check that here: 3229 if (m_result.IsResult(lldb::eCommandInterpreterResultSuccess) && 3230 result.GetDidChangeProcessState() && 3231 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash) && 3232 DidProcessStopAbnormally()) { 3233 io_handler.SetIsDone(true); 3234 m_result.SetResult(lldb::eCommandInterpreterResultInferiorCrash); 3235 } 3236 } 3237 3238 bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) { 3239 ExecutionContext exe_ctx(GetExecutionContext()); 3240 Process *process = exe_ctx.GetProcessPtr(); 3241 3242 if (InterruptCommand()) 3243 return true; 3244 3245 if (process) { 3246 StateType state = process->GetState(); 3247 if (StateIsRunningState(state)) { 3248 process->Halt(); 3249 return true; // Don't do any updating when we are running 3250 } 3251 } 3252 3253 ScriptInterpreter *script_interpreter = 3254 m_debugger.GetScriptInterpreter(false); 3255 if (script_interpreter) { 3256 if (script_interpreter->Interrupt()) 3257 return true; 3258 } 3259 return false; 3260 } 3261 3262 bool CommandInterpreter::SaveTranscript( 3263 CommandReturnObject &result, std::optional<std::string> output_file) { 3264 if (output_file == std::nullopt || output_file->empty()) { 3265 std::string now = llvm::to_string(std::chrono::system_clock::now()); 3266 std::replace(now.begin(), now.end(), ' ', '_'); 3267 // Can't have file name with colons on Windows 3268 std::replace(now.begin(), now.end(), ':', '-'); 3269 const std::string file_name = "lldb_session_" + now + ".log"; 3270 3271 FileSpec save_location = GetSaveSessionDirectory(); 3272 3273 if (!save_location) 3274 save_location = HostInfo::GetGlobalTempDir(); 3275 3276 FileSystem::Instance().Resolve(save_location); 3277 save_location.AppendPathComponent(file_name); 3278 output_file = save_location.GetPath(); 3279 } 3280 3281 auto error_out = [&](llvm::StringRef error_message, std::string description) { 3282 LLDB_LOG(GetLog(LLDBLog::Commands), "{0} ({1}:{2})", error_message, 3283 output_file, description); 3284 result.AppendErrorWithFormatv( 3285 "Failed to save session's transcripts to {0}!", *output_file); 3286 return false; 3287 }; 3288 3289 File::OpenOptions flags = File::eOpenOptionWriteOnly | 3290 File::eOpenOptionCanCreate | 3291 File::eOpenOptionTruncate; 3292 3293 auto opened_file = FileSystem::Instance().Open(FileSpec(*output_file), flags); 3294 3295 if (!opened_file) 3296 return error_out("Unable to create file", 3297 llvm::toString(opened_file.takeError())); 3298 3299 FileUP file = std::move(opened_file.get()); 3300 3301 size_t byte_size = m_transcript_stream.GetSize(); 3302 3303 Status error = file->Write(m_transcript_stream.GetData(), byte_size); 3304 3305 if (error.Fail() || byte_size != m_transcript_stream.GetSize()) 3306 return error_out("Unable to write to destination file", 3307 "Bytes written do not match transcript size."); 3308 3309 result.SetStatus(eReturnStatusSuccessFinishNoResult); 3310 result.AppendMessageWithFormat("Session's transcripts saved to %s\n", 3311 output_file->c_str()); 3312 if (!GetSaveTranscript()) 3313 result.AppendError( 3314 "Note: the setting interpreter.save-transcript is set to false, so the " 3315 "transcript might not have been recorded."); 3316 3317 if (GetOpenTranscriptInEditor() && Host::IsInteractiveGraphicSession()) { 3318 const FileSpec file_spec; 3319 error = file->GetFileSpec(const_cast<FileSpec &>(file_spec)); 3320 if (error.Success()) { 3321 if (llvm::Error e = Host::OpenFileInExternalEditor( 3322 m_debugger.GetExternalEditor(), file_spec, 1)) 3323 result.AppendError(llvm::toString(std::move(e))); 3324 } 3325 } 3326 3327 return true; 3328 } 3329 3330 bool CommandInterpreter::IsInteractive() { 3331 return (GetIOHandler() ? GetIOHandler()->GetIsInteractive() : false); 3332 } 3333 3334 FileSpec CommandInterpreter::GetCurrentSourceDir() { 3335 if (m_command_source_dirs.empty()) 3336 return {}; 3337 return m_command_source_dirs.back(); 3338 } 3339 3340 void CommandInterpreter::GetLLDBCommandsFromIOHandler( 3341 const char *prompt, IOHandlerDelegate &delegate, void *baton) { 3342 Debugger &debugger = GetDebugger(); 3343 IOHandlerSP io_handler_sp( 3344 new IOHandlerEditline(debugger, IOHandler::Type::CommandList, 3345 "lldb", // Name of input reader for history 3346 llvm::StringRef(prompt), // Prompt 3347 llvm::StringRef(), // Continuation prompt 3348 true, // Get multiple lines 3349 debugger.GetUseColor(), 3350 0, // Don't show line numbers 3351 delegate)); // IOHandlerDelegate 3352 3353 if (io_handler_sp) { 3354 io_handler_sp->SetUserData(baton); 3355 debugger.RunIOHandlerAsync(io_handler_sp); 3356 } 3357 } 3358 3359 void CommandInterpreter::GetPythonCommandsFromIOHandler( 3360 const char *prompt, IOHandlerDelegate &delegate, void *baton) { 3361 Debugger &debugger = GetDebugger(); 3362 IOHandlerSP io_handler_sp( 3363 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode, 3364 "lldb-python", // Name of input reader for history 3365 llvm::StringRef(prompt), // Prompt 3366 llvm::StringRef(), // Continuation prompt 3367 true, // Get multiple lines 3368 debugger.GetUseColor(), 3369 0, // Don't show line numbers 3370 delegate)); // IOHandlerDelegate 3371 3372 if (io_handler_sp) { 3373 io_handler_sp->SetUserData(baton); 3374 debugger.RunIOHandlerAsync(io_handler_sp); 3375 } 3376 } 3377 3378 bool CommandInterpreter::IsActive() { 3379 return m_debugger.IsTopIOHandler(m_command_io_handler_sp); 3380 } 3381 3382 lldb::IOHandlerSP 3383 CommandInterpreter::GetIOHandler(bool force_create, 3384 CommandInterpreterRunOptions *options) { 3385 // Always re-create the IOHandlerEditline in case the input changed. The old 3386 // instance might have had a non-interactive input and now it does or vice 3387 // versa. 3388 if (force_create || !m_command_io_handler_sp) { 3389 // Always re-create the IOHandlerEditline in case the input changed. The 3390 // old instance might have had a non-interactive input and now it does or 3391 // vice versa. 3392 uint32_t flags = 0; 3393 3394 if (options) { 3395 if (options->m_stop_on_continue == eLazyBoolYes) 3396 flags |= eHandleCommandFlagStopOnContinue; 3397 if (options->m_stop_on_error == eLazyBoolYes) 3398 flags |= eHandleCommandFlagStopOnError; 3399 if (options->m_stop_on_crash == eLazyBoolYes) 3400 flags |= eHandleCommandFlagStopOnCrash; 3401 if (options->m_echo_commands != eLazyBoolNo) 3402 flags |= eHandleCommandFlagEchoCommand; 3403 if (options->m_echo_comment_commands != eLazyBoolNo) 3404 flags |= eHandleCommandFlagEchoCommentCommand; 3405 if (options->m_print_results != eLazyBoolNo) 3406 flags |= eHandleCommandFlagPrintResult; 3407 if (options->m_print_errors != eLazyBoolNo) 3408 flags |= eHandleCommandFlagPrintErrors; 3409 if (options->m_allow_repeats == eLazyBoolYes) 3410 flags |= eHandleCommandFlagAllowRepeats; 3411 } else { 3412 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult | 3413 eHandleCommandFlagPrintErrors; 3414 } 3415 3416 m_command_io_handler_sp = std::make_shared<IOHandlerEditline>( 3417 m_debugger, IOHandler::Type::CommandInterpreter, 3418 m_debugger.GetInputFileSP(), m_debugger.GetOutputStreamSP(), 3419 m_debugger.GetErrorStreamSP(), flags, "lldb", m_debugger.GetPrompt(), 3420 llvm::StringRef(), // Continuation prompt 3421 false, // Don't enable multiple line input, just single line commands 3422 m_debugger.GetUseColor(), 3423 0, // Don't show line numbers 3424 *this); // IOHandlerDelegate 3425 } 3426 return m_command_io_handler_sp; 3427 } 3428 3429 CommandInterpreterRunResult CommandInterpreter::RunCommandInterpreter( 3430 CommandInterpreterRunOptions &options) { 3431 // Always re-create the command interpreter when we run it in case any file 3432 // handles have changed. 3433 bool force_create = true; 3434 m_debugger.RunIOHandlerAsync(GetIOHandler(force_create, &options)); 3435 m_result = CommandInterpreterRunResult(); 3436 3437 if (options.GetAutoHandleEvents()) 3438 m_debugger.StartEventHandlerThread(); 3439 3440 if (options.GetSpawnThread()) { 3441 m_debugger.StartIOHandlerThread(); 3442 } else { 3443 // If the current thread is not managed by a host thread, we won't detect 3444 // that this IS the CommandInterpreter IOHandler thread, so make it so: 3445 HostThread new_io_handler_thread(Host::GetCurrentThread()); 3446 HostThread old_io_handler_thread = 3447 m_debugger.SetIOHandlerThread(new_io_handler_thread); 3448 m_debugger.RunIOHandlers(); 3449 m_debugger.SetIOHandlerThread(old_io_handler_thread); 3450 3451 if (options.GetAutoHandleEvents()) 3452 m_debugger.StopEventHandlerThread(); 3453 } 3454 3455 return m_result; 3456 } 3457 3458 CommandObject * 3459 CommandInterpreter::ResolveCommandImpl(std::string &command_line, 3460 CommandReturnObject &result) { 3461 std::string scratch_command(command_line); // working copy so we don't modify 3462 // command_line unless we succeed 3463 CommandObject *cmd_obj = nullptr; 3464 StreamString revised_command_line; 3465 bool wants_raw_input = false; 3466 std::string next_word; 3467 StringList matches; 3468 bool done = false; 3469 3470 auto build_alias_cmd = [&](std::string &full_name) { 3471 revised_command_line.Clear(); 3472 matches.Clear(); 3473 std::string alias_result; 3474 cmd_obj = 3475 BuildAliasResult(full_name, scratch_command, alias_result, result); 3476 revised_command_line.Printf("%s", alias_result.c_str()); 3477 if (cmd_obj) { 3478 wants_raw_input = cmd_obj->WantsRawCommandString(); 3479 } 3480 }; 3481 3482 while (!done) { 3483 char quote_char = '\0'; 3484 std::string suffix; 3485 ExtractCommand(scratch_command, next_word, suffix, quote_char); 3486 if (cmd_obj == nullptr) { 3487 std::string full_name; 3488 bool is_alias = GetAliasFullName(next_word, full_name); 3489 cmd_obj = GetCommandObject(next_word, &matches); 3490 bool is_real_command = 3491 (!is_alias) || (cmd_obj != nullptr && !cmd_obj->IsAlias()); 3492 if (!is_real_command) { 3493 build_alias_cmd(full_name); 3494 } else { 3495 if (cmd_obj) { 3496 llvm::StringRef cmd_name = cmd_obj->GetCommandName(); 3497 revised_command_line.Printf("%s", cmd_name.str().c_str()); 3498 wants_raw_input = cmd_obj->WantsRawCommandString(); 3499 } else { 3500 revised_command_line.Printf("%s", next_word.c_str()); 3501 } 3502 } 3503 } else { 3504 if (cmd_obj->IsMultiwordObject()) { 3505 CommandObject *sub_cmd_obj = 3506 cmd_obj->GetSubcommandObject(next_word.c_str()); 3507 if (sub_cmd_obj) { 3508 // The subcommand's name includes the parent command's name, so 3509 // restart rather than append to the revised_command_line. 3510 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName(); 3511 revised_command_line.Clear(); 3512 revised_command_line.Printf("%s", sub_cmd_name.str().c_str()); 3513 cmd_obj = sub_cmd_obj; 3514 wants_raw_input = cmd_obj->WantsRawCommandString(); 3515 } else { 3516 if (quote_char) 3517 revised_command_line.Printf(" %c%s%s%c", quote_char, 3518 next_word.c_str(), suffix.c_str(), 3519 quote_char); 3520 else 3521 revised_command_line.Printf(" %s%s", next_word.c_str(), 3522 suffix.c_str()); 3523 done = true; 3524 } 3525 } else { 3526 if (quote_char) 3527 revised_command_line.Printf(" %c%s%s%c", quote_char, 3528 next_word.c_str(), suffix.c_str(), 3529 quote_char); 3530 else 3531 revised_command_line.Printf(" %s%s", next_word.c_str(), 3532 suffix.c_str()); 3533 done = true; 3534 } 3535 } 3536 3537 if (cmd_obj == nullptr) { 3538 const size_t num_matches = matches.GetSize(); 3539 if (matches.GetSize() > 1) { 3540 StringList alias_matches; 3541 GetAliasCommandObject(next_word, &alias_matches); 3542 3543 if (alias_matches.GetSize() == 1) { 3544 std::string full_name; 3545 GetAliasFullName(alias_matches.GetStringAtIndex(0), full_name); 3546 build_alias_cmd(full_name); 3547 done = static_cast<bool>(cmd_obj); 3548 } else { 3549 StreamString error_msg; 3550 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n", 3551 next_word.c_str()); 3552 3553 for (uint32_t i = 0; i < num_matches; ++i) { 3554 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i)); 3555 } 3556 result.AppendRawError(error_msg.GetString()); 3557 } 3558 } else { 3559 // We didn't have only one match, otherwise we wouldn't get here. 3560 lldbassert(num_matches == 0); 3561 result.AppendErrorWithFormat("'%s' is not a valid command.\n", 3562 next_word.c_str()); 3563 } 3564 if (!done) 3565 return nullptr; 3566 } 3567 3568 if (cmd_obj->IsMultiwordObject()) { 3569 if (!suffix.empty()) { 3570 result.AppendErrorWithFormat( 3571 "command '%s' did not recognize '%s%s%s' as valid (subcommand " 3572 "might be invalid).\n", 3573 cmd_obj->GetCommandName().str().c_str(), 3574 next_word.empty() ? "" : next_word.c_str(), 3575 next_word.empty() ? " -- " : " ", suffix.c_str()); 3576 return nullptr; 3577 } 3578 } else { 3579 // If we found a normal command, we are done 3580 done = true; 3581 if (!suffix.empty()) { 3582 switch (suffix[0]) { 3583 case '/': 3584 // GDB format suffixes 3585 { 3586 Options *command_options = cmd_obj->GetOptions(); 3587 if (command_options && 3588 command_options->SupportsLongOption("gdb-format")) { 3589 std::string gdb_format_option("--gdb-format="); 3590 gdb_format_option += (suffix.c_str() + 1); 3591 3592 std::string cmd = std::string(revised_command_line.GetString()); 3593 size_t arg_terminator_idx = FindArgumentTerminator(cmd); 3594 if (arg_terminator_idx != std::string::npos) { 3595 // Insert the gdb format option before the "--" that terminates 3596 // options 3597 gdb_format_option.append(1, ' '); 3598 cmd.insert(arg_terminator_idx, gdb_format_option); 3599 revised_command_line.Clear(); 3600 revised_command_line.PutCString(cmd); 3601 } else 3602 revised_command_line.Printf(" %s", gdb_format_option.c_str()); 3603 3604 if (wants_raw_input && 3605 FindArgumentTerminator(cmd) == std::string::npos) 3606 revised_command_line.PutCString(" --"); 3607 } else { 3608 result.AppendErrorWithFormat( 3609 "the '%s' command doesn't support the --gdb-format option\n", 3610 cmd_obj->GetCommandName().str().c_str()); 3611 return nullptr; 3612 } 3613 } 3614 break; 3615 3616 default: 3617 result.AppendErrorWithFormat( 3618 "unknown command shorthand suffix: '%s'\n", suffix.c_str()); 3619 return nullptr; 3620 } 3621 } 3622 } 3623 if (scratch_command.empty()) 3624 done = true; 3625 } 3626 3627 if (!scratch_command.empty()) 3628 revised_command_line.Printf(" %s", scratch_command.c_str()); 3629 3630 if (cmd_obj != nullptr) 3631 command_line = std::string(revised_command_line.GetString()); 3632 3633 return cmd_obj; 3634 } 3635 3636 llvm::json::Value CommandInterpreter::GetStatistics() { 3637 llvm::json::Object stats; 3638 for (const auto &command_usage : m_command_usages) 3639 stats.try_emplace(command_usage.getKey(), command_usage.getValue()); 3640 return stats; 3641 } 3642 3643 const StructuredData::Array &CommandInterpreter::GetTranscript() const { 3644 return m_transcript; 3645 } 3646