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