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