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. " 748 "If no host is specifed, localhost is assumed.", 749 "gdb-remote [<hostname>:]<portnum>", 2, 0, false)); 750 if (connect_gdb_remote_cmd_up) { 751 if (connect_gdb_remote_cmd_up->AddRegexCommand( 752 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$", 753 "process connect --plugin gdb-remote connect://%1:%2") && 754 connect_gdb_remote_cmd_up->AddRegexCommand( 755 "^([[:digit:]]+)$", 756 "process connect --plugin gdb-remote connect://localhost:%1")) { 757 CommandObjectSP command_sp(connect_gdb_remote_cmd_up.release()); 758 m_command_dict[std::string(command_sp->GetCommandName())] = command_sp; 759 } 760 } 761 762 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_up( 763 new CommandObjectRegexCommand( 764 *this, "kdp-remote", 765 "Connect to a process via remote KDP server. " 766 "If no UDP port is specified, port 41139 is " 767 "assumed.", 768 "kdp-remote <hostname>[:<portnum>]", 2, 0, false)); 769 if (connect_kdp_remote_cmd_up) { 770 if (connect_kdp_remote_cmd_up->AddRegexCommand( 771 "^([^:]+:[[:digit:]]+)$", 772 "process connect --plugin kdp-remote udp://%1") && 773 connect_kdp_remote_cmd_up->AddRegexCommand( 774 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) { 775 CommandObjectSP command_sp(connect_kdp_remote_cmd_up.release()); 776 m_command_dict[std::string(command_sp->GetCommandName())] = command_sp; 777 } 778 } 779 780 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_up( 781 new CommandObjectRegexCommand( 782 *this, "_regexp-bt", 783 "Show the current thread's call stack. Any numeric argument " 784 "displays at most that many " 785 "frames. The argument 'all' displays all threads. Use 'settings" 786 " set frame-format' to customize the printing of individual frames " 787 "and 'settings set thread-format' to customize the thread header.", 788 "bt [<digit> | all]", 2, 0, false)); 789 if (bt_regex_cmd_up) { 790 // accept but don't document "bt -c <number>" -- before bt was a regex 791 // command if you wanted to backtrace three frames you would do "bt -c 3" 792 // but the intention is to have this emulate the gdb "bt" command and so 793 // now "bt 3" is the preferred form, in line with gdb. 794 if (bt_regex_cmd_up->AddRegexCommand("^([[:digit:]]+)[[:space:]]*$", 795 "thread backtrace -c %1") && 796 bt_regex_cmd_up->AddRegexCommand("^-c ([[:digit:]]+)[[:space:]]*$", 797 "thread backtrace -c %1") && 798 bt_regex_cmd_up->AddRegexCommand("^all[[:space:]]*$", "thread backtrace all") && 799 bt_regex_cmd_up->AddRegexCommand("^[[:space:]]*$", "thread backtrace")) { 800 CommandObjectSP command_sp(bt_regex_cmd_up.release()); 801 m_command_dict[std::string(command_sp->GetCommandName())] = command_sp; 802 } 803 } 804 805 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_up( 806 new CommandObjectRegexCommand( 807 *this, "_regexp-list", 808 "List relevant source code using one of several shorthand formats.", 809 "\n" 810 "_regexp-list <file>:<line> // List around specific file/line\n" 811 "_regexp-list <line> // List current file around specified " 812 "line\n" 813 "_regexp-list <function-name> // List specified function\n" 814 "_regexp-list 0x<address> // List around specified address\n" 815 "_regexp-list -[<count>] // List previous <count> lines\n" 816 "_regexp-list // List subsequent lines", 817 2, CommandCompletions::eSourceFileCompletion, false)); 818 if (list_regex_cmd_up) { 819 if (list_regex_cmd_up->AddRegexCommand("^([0-9]+)[[:space:]]*$", 820 "source list --line %1") && 821 list_regex_cmd_up->AddRegexCommand( 822 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]" 823 "]*$", 824 "source list --file '%1' --line %2") && 825 list_regex_cmd_up->AddRegexCommand( 826 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", 827 "source list --address %1") && 828 list_regex_cmd_up->AddRegexCommand("^-[[:space:]]*$", 829 "source list --reverse") && 830 list_regex_cmd_up->AddRegexCommand( 831 "^-([[:digit:]]+)[[:space:]]*$", 832 "source list --reverse --count %1") && 833 list_regex_cmd_up->AddRegexCommand("^(.+)$", 834 "source list --name \"%1\"") && 835 list_regex_cmd_up->AddRegexCommand("^$", "source list")) { 836 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_up.release()); 837 m_command_dict[std::string(list_regex_cmd_sp->GetCommandName())] = 838 list_regex_cmd_sp; 839 } 840 } 841 842 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_up( 843 new CommandObjectRegexCommand( 844 *this, "_regexp-env", 845 "Shorthand for viewing and setting environment variables.", 846 "\n" 847 "_regexp-env // Show environment\n" 848 "_regexp-env <name>=<value> // Set an environment variable", 849 2, 0, false)); 850 if (env_regex_cmd_up) { 851 if (env_regex_cmd_up->AddRegexCommand("^$", 852 "settings show target.env-vars") && 853 env_regex_cmd_up->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", 854 "settings set target.env-vars %1")) { 855 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_up.release()); 856 m_command_dict[std::string(env_regex_cmd_sp->GetCommandName())] = 857 env_regex_cmd_sp; 858 } 859 } 860 861 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_up( 862 new CommandObjectRegexCommand( 863 *this, "_regexp-jump", "Set the program counter to a new address.", 864 "\n" 865 "_regexp-jump <line>\n" 866 "_regexp-jump +<line-offset> | -<line-offset>\n" 867 "_regexp-jump <file>:<line>\n" 868 "_regexp-jump *<addr>\n", 869 2, 0, false)); 870 if (jump_regex_cmd_up) { 871 if (jump_regex_cmd_up->AddRegexCommand("^\\*(.*)$", 872 "thread jump --addr %1") && 873 jump_regex_cmd_up->AddRegexCommand("^([0-9]+)$", 874 "thread jump --line %1") && 875 jump_regex_cmd_up->AddRegexCommand("^([^:]+):([0-9]+)$", 876 "thread jump --file %1 --line %2") && 877 jump_regex_cmd_up->AddRegexCommand("^([+\\-][0-9]+)$", 878 "thread jump --by %1")) { 879 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_up.release()); 880 m_command_dict[std::string(jump_regex_cmd_sp->GetCommandName())] = 881 jump_regex_cmd_sp; 882 } 883 } 884 } 885 886 int CommandInterpreter::GetCommandNamesMatchingPartialString( 887 const char *cmd_str, bool include_aliases, StringList &matches, 888 StringList &descriptions) { 889 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches, 890 &descriptions); 891 892 if (include_aliases) { 893 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches, 894 &descriptions); 895 } 896 897 return matches.GetSize(); 898 } 899 900 CommandObjectSP 901 CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases, 902 bool exact, StringList *matches, 903 StringList *descriptions) const { 904 CommandObjectSP command_sp; 905 906 std::string cmd = std::string(cmd_str); 907 908 if (HasCommands()) { 909 auto pos = m_command_dict.find(cmd); 910 if (pos != m_command_dict.end()) 911 command_sp = pos->second; 912 } 913 914 if (include_aliases && HasAliases()) { 915 auto alias_pos = m_alias_dict.find(cmd); 916 if (alias_pos != m_alias_dict.end()) 917 command_sp = alias_pos->second; 918 } 919 920 if (HasUserCommands()) { 921 auto pos = m_user_dict.find(cmd); 922 if (pos != m_user_dict.end()) 923 command_sp = pos->second; 924 } 925 926 if (!exact && !command_sp) { 927 // We will only get into here if we didn't find any exact matches. 928 929 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp; 930 931 StringList local_matches; 932 if (matches == nullptr) 933 matches = &local_matches; 934 935 unsigned int num_cmd_matches = 0; 936 unsigned int num_alias_matches = 0; 937 unsigned int num_user_matches = 0; 938 939 // Look through the command dictionaries one by one, and if we get only one 940 // match from any of them in toto, then return that, otherwise return an 941 // empty CommandObjectSP and the list of matches. 942 943 if (HasCommands()) { 944 num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str, 945 *matches, descriptions); 946 } 947 948 if (num_cmd_matches == 1) { 949 cmd.assign(matches->GetStringAtIndex(0)); 950 auto pos = m_command_dict.find(cmd); 951 if (pos != m_command_dict.end()) 952 real_match_sp = pos->second; 953 } 954 955 if (include_aliases && HasAliases()) { 956 num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str, 957 *matches, descriptions); 958 } 959 960 if (num_alias_matches == 1) { 961 cmd.assign(matches->GetStringAtIndex(num_cmd_matches)); 962 auto alias_pos = m_alias_dict.find(cmd); 963 if (alias_pos != m_alias_dict.end()) 964 alias_match_sp = alias_pos->second; 965 } 966 967 if (HasUserCommands()) { 968 num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str, 969 *matches, descriptions); 970 } 971 972 if (num_user_matches == 1) { 973 cmd.assign( 974 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches)); 975 976 auto pos = m_user_dict.find(cmd); 977 if (pos != m_user_dict.end()) 978 user_match_sp = pos->second; 979 } 980 981 // If we got exactly one match, return that, otherwise return the match 982 // list. 983 984 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) { 985 if (num_cmd_matches) 986 return real_match_sp; 987 else if (num_alias_matches) 988 return alias_match_sp; 989 else 990 return user_match_sp; 991 } 992 } else if (matches && command_sp) { 993 matches->AppendString(cmd_str); 994 if (descriptions) 995 descriptions->AppendString(command_sp->GetHelp()); 996 } 997 998 return command_sp; 999 } 1000 1001 bool CommandInterpreter::AddCommand(llvm::StringRef name, 1002 const lldb::CommandObjectSP &cmd_sp, 1003 bool can_replace) { 1004 if (cmd_sp.get()) 1005 lldbassert((this == &cmd_sp->GetCommandInterpreter()) && 1006 "tried to add a CommandObject from a different interpreter"); 1007 1008 if (name.empty()) 1009 return false; 1010 1011 std::string name_sstr(name); 1012 auto name_iter = m_command_dict.find(name_sstr); 1013 if (name_iter != m_command_dict.end()) { 1014 if (!can_replace || !name_iter->second->IsRemovable()) 1015 return false; 1016 name_iter->second = cmd_sp; 1017 } else { 1018 m_command_dict[name_sstr] = cmd_sp; 1019 } 1020 return true; 1021 } 1022 1023 bool CommandInterpreter::AddUserCommand(llvm::StringRef name, 1024 const lldb::CommandObjectSP &cmd_sp, 1025 bool can_replace) { 1026 if (cmd_sp.get()) 1027 lldbassert((this == &cmd_sp->GetCommandInterpreter()) && 1028 "tried to add a CommandObject from a different interpreter"); 1029 1030 if (!name.empty()) { 1031 // do not allow replacement of internal commands 1032 if (CommandExists(name)) { 1033 if (!can_replace) 1034 return false; 1035 if (!m_command_dict[std::string(name)]->IsRemovable()) 1036 return false; 1037 } 1038 1039 if (UserCommandExists(name)) { 1040 if (!can_replace) 1041 return false; 1042 if (!m_user_dict[std::string(name)]->IsRemovable()) 1043 return false; 1044 } 1045 1046 m_user_dict[std::string(name)] = cmd_sp; 1047 return true; 1048 } 1049 return false; 1050 } 1051 1052 CommandObjectSP 1053 CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str, 1054 bool include_aliases) const { 1055 // Break up the command string into words, in case it's a multi-word command. 1056 Args cmd_words(cmd_str); 1057 1058 if (cmd_str.empty()) 1059 return {}; 1060 1061 if (cmd_words.GetArgumentCount() == 1) 1062 return GetCommandSP(cmd_str, include_aliases, true); 1063 1064 // We have a multi-word command (seemingly), so we need to do more work. 1065 // First, get the cmd_obj_sp for the first word in the command. 1066 CommandObjectSP cmd_obj_sp = 1067 GetCommandSP(cmd_words.GetArgumentAtIndex(0), include_aliases, true); 1068 if (!cmd_obj_sp) 1069 return {}; 1070 1071 // Loop through the rest of the words in the command (everything passed in 1072 // was supposed to be part of a command name), and find the appropriate 1073 // sub-command SP for each command word.... 1074 size_t end = cmd_words.GetArgumentCount(); 1075 for (size_t i = 1; i < end; ++i) { 1076 if (!cmd_obj_sp->IsMultiwordObject()) { 1077 // We have more words in the command name, but we don't have a 1078 // multiword object. Fail and return. 1079 return {}; 1080 } 1081 1082 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(i)); 1083 if (!cmd_obj_sp) { 1084 // The sub-command name was invalid. Fail and return. 1085 return {}; 1086 } 1087 } 1088 1089 // We successfully looped through all the command words and got valid 1090 // command objects for them. 1091 return cmd_obj_sp; 1092 } 1093 1094 CommandObject * 1095 CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str, 1096 StringList *matches, 1097 StringList *descriptions) const { 1098 CommandObject *command_obj = 1099 GetCommandSP(cmd_str, false, true, matches, descriptions).get(); 1100 1101 // If we didn't find an exact match to the command string in the commands, 1102 // look in the aliases. 1103 1104 if (command_obj) 1105 return command_obj; 1106 1107 command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get(); 1108 1109 if (command_obj) 1110 return command_obj; 1111 1112 // If there wasn't an exact match then look for an inexact one in just the 1113 // commands 1114 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get(); 1115 1116 // Finally, if there wasn't an inexact match among the commands, look for an 1117 // inexact match in both the commands and aliases. 1118 1119 if (command_obj) { 1120 if (matches) 1121 matches->AppendString(command_obj->GetCommandName()); 1122 if (descriptions) 1123 descriptions->AppendString(command_obj->GetHelp()); 1124 return command_obj; 1125 } 1126 1127 return GetCommandSP(cmd_str, true, false, matches, descriptions).get(); 1128 } 1129 1130 bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const { 1131 return m_command_dict.find(std::string(cmd)) != m_command_dict.end(); 1132 } 1133 1134 bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd, 1135 std::string &full_name) const { 1136 bool exact_match = 1137 (m_alias_dict.find(std::string(cmd)) != m_alias_dict.end()); 1138 if (exact_match) { 1139 full_name.assign(std::string(cmd)); 1140 return exact_match; 1141 } else { 1142 StringList matches; 1143 size_t num_alias_matches; 1144 num_alias_matches = 1145 AddNamesMatchingPartialString(m_alias_dict, cmd, matches); 1146 if (num_alias_matches == 1) { 1147 // Make sure this isn't shadowing a command in the regular command space: 1148 StringList regular_matches; 1149 const bool include_aliases = false; 1150 const bool exact = false; 1151 CommandObjectSP cmd_obj_sp( 1152 GetCommandSP(cmd, include_aliases, exact, ®ular_matches)); 1153 if (cmd_obj_sp || regular_matches.GetSize() > 0) 1154 return false; 1155 else { 1156 full_name.assign(matches.GetStringAtIndex(0)); 1157 return true; 1158 } 1159 } else 1160 return false; 1161 } 1162 } 1163 1164 bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const { 1165 return m_alias_dict.find(std::string(cmd)) != m_alias_dict.end(); 1166 } 1167 1168 bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const { 1169 return m_user_dict.find(std::string(cmd)) != m_user_dict.end(); 1170 } 1171 1172 CommandAlias * 1173 CommandInterpreter::AddAlias(llvm::StringRef alias_name, 1174 lldb::CommandObjectSP &command_obj_sp, 1175 llvm::StringRef args_string) { 1176 if (command_obj_sp.get()) 1177 lldbassert((this == &command_obj_sp->GetCommandInterpreter()) && 1178 "tried to add a CommandObject from a different interpreter"); 1179 1180 std::unique_ptr<CommandAlias> command_alias_up( 1181 new CommandAlias(*this, command_obj_sp, args_string, alias_name)); 1182 1183 if (command_alias_up && command_alias_up->IsValid()) { 1184 m_alias_dict[std::string(alias_name)] = 1185 CommandObjectSP(command_alias_up.get()); 1186 return command_alias_up.release(); 1187 } 1188 1189 return nullptr; 1190 } 1191 1192 bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) { 1193 auto pos = m_alias_dict.find(std::string(alias_name)); 1194 if (pos != m_alias_dict.end()) { 1195 m_alias_dict.erase(pos); 1196 return true; 1197 } 1198 return false; 1199 } 1200 1201 bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) { 1202 auto pos = m_command_dict.find(std::string(cmd)); 1203 if (pos != m_command_dict.end()) { 1204 if (pos->second->IsRemovable()) { 1205 // Only regular expression objects or python commands are removable 1206 m_command_dict.erase(pos); 1207 return true; 1208 } 1209 } 1210 return false; 1211 } 1212 bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) { 1213 CommandObject::CommandMap::iterator pos = 1214 m_user_dict.find(std::string(alias_name)); 1215 if (pos != m_user_dict.end()) { 1216 m_user_dict.erase(pos); 1217 return true; 1218 } 1219 return false; 1220 } 1221 1222 void CommandInterpreter::GetHelp(CommandReturnObject &result, 1223 uint32_t cmd_types) { 1224 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue()); 1225 if (!help_prologue.empty()) { 1226 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(), 1227 help_prologue); 1228 } 1229 1230 CommandObject::CommandMap::const_iterator pos; 1231 size_t max_len = FindLongestCommandWord(m_command_dict); 1232 1233 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) { 1234 result.AppendMessage("Debugger commands:"); 1235 result.AppendMessage(""); 1236 1237 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) { 1238 if (!(cmd_types & eCommandTypesHidden) && 1239 (pos->first.compare(0, 1, "_") == 0)) 1240 continue; 1241 1242 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--", 1243 pos->second->GetHelp(), max_len); 1244 } 1245 result.AppendMessage(""); 1246 } 1247 1248 if (!m_alias_dict.empty() && 1249 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) { 1250 result.AppendMessageWithFormat( 1251 "Current command abbreviations " 1252 "(type '%shelp command alias' for more info):\n", 1253 GetCommandPrefix()); 1254 result.AppendMessage(""); 1255 max_len = FindLongestCommandWord(m_alias_dict); 1256 1257 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end(); 1258 ++alias_pos) { 1259 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--", 1260 alias_pos->second->GetHelp(), max_len); 1261 } 1262 result.AppendMessage(""); 1263 } 1264 1265 if (!m_user_dict.empty() && 1266 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) { 1267 result.AppendMessage("Current user-defined commands:"); 1268 result.AppendMessage(""); 1269 max_len = FindLongestCommandWord(m_user_dict); 1270 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) { 1271 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--", 1272 pos->second->GetHelp(), max_len); 1273 } 1274 result.AppendMessage(""); 1275 } 1276 1277 result.AppendMessageWithFormat( 1278 "For more information on any command, type '%shelp <command-name>'.\n", 1279 GetCommandPrefix()); 1280 } 1281 1282 CommandObject *CommandInterpreter::GetCommandObjectForCommand( 1283 llvm::StringRef &command_string) { 1284 // This function finds the final, lowest-level, alias-resolved command object 1285 // whose 'Execute' function will eventually be invoked by the given command 1286 // line. 1287 1288 CommandObject *cmd_obj = nullptr; 1289 size_t start = command_string.find_first_not_of(k_white_space); 1290 size_t end = 0; 1291 bool done = false; 1292 while (!done) { 1293 if (start != std::string::npos) { 1294 // Get the next word from command_string. 1295 end = command_string.find_first_of(k_white_space, start); 1296 if (end == std::string::npos) 1297 end = command_string.size(); 1298 std::string cmd_word = 1299 std::string(command_string.substr(start, end - start)); 1300 1301 if (cmd_obj == nullptr) 1302 // Since cmd_obj is NULL we are on our first time through this loop. 1303 // Check to see if cmd_word is a valid command or alias. 1304 cmd_obj = GetCommandObject(cmd_word); 1305 else if (cmd_obj->IsMultiwordObject()) { 1306 // Our current object is a multi-word object; see if the cmd_word is a 1307 // valid sub-command for our object. 1308 CommandObject *sub_cmd_obj = 1309 cmd_obj->GetSubcommandObject(cmd_word.c_str()); 1310 if (sub_cmd_obj) 1311 cmd_obj = sub_cmd_obj; 1312 else // cmd_word was not a valid sub-command word, so we are done 1313 done = true; 1314 } else 1315 // We have a cmd_obj and it is not a multi-word object, so we are done. 1316 done = true; 1317 1318 // If we didn't find a valid command object, or our command object is not 1319 // a multi-word object, or we are at the end of the command_string, then 1320 // we are done. Otherwise, find the start of the next word. 1321 1322 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || 1323 end >= command_string.size()) 1324 done = true; 1325 else 1326 start = command_string.find_first_not_of(k_white_space, end); 1327 } else 1328 // Unable to find any more words. 1329 done = true; 1330 } 1331 1332 command_string = command_string.substr(end); 1333 return cmd_obj; 1334 } 1335 1336 static const char *k_valid_command_chars = 1337 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"; 1338 static void StripLeadingSpaces(std::string &s) { 1339 if (!s.empty()) { 1340 size_t pos = s.find_first_not_of(k_white_space); 1341 if (pos == std::string::npos) 1342 s.clear(); 1343 else if (pos == 0) 1344 return; 1345 s.erase(0, pos); 1346 } 1347 } 1348 1349 static size_t FindArgumentTerminator(const std::string &s) { 1350 const size_t s_len = s.size(); 1351 size_t offset = 0; 1352 while (offset < s_len) { 1353 size_t pos = s.find("--", offset); 1354 if (pos == std::string::npos) 1355 break; 1356 if (pos > 0) { 1357 if (llvm::isSpace(s[pos - 1])) { 1358 // Check if the string ends "\s--" (where \s is a space character) or 1359 // if we have "\s--\s". 1360 if ((pos + 2 >= s_len) || llvm::isSpace(s[pos + 2])) { 1361 return pos; 1362 } 1363 } 1364 } 1365 offset = pos + 2; 1366 } 1367 return std::string::npos; 1368 } 1369 1370 static bool ExtractCommand(std::string &command_string, std::string &command, 1371 std::string &suffix, char "e_char) { 1372 command.clear(); 1373 suffix.clear(); 1374 StripLeadingSpaces(command_string); 1375 1376 bool result = false; 1377 quote_char = '\0'; 1378 1379 if (!command_string.empty()) { 1380 const char first_char = command_string[0]; 1381 if (first_char == '\'' || first_char == '"') { 1382 quote_char = first_char; 1383 const size_t end_quote_pos = command_string.find(quote_char, 1); 1384 if (end_quote_pos == std::string::npos) { 1385 command.swap(command_string); 1386 command_string.erase(); 1387 } else { 1388 command.assign(command_string, 1, end_quote_pos - 1); 1389 if (end_quote_pos + 1 < command_string.size()) 1390 command_string.erase(0, command_string.find_first_not_of( 1391 k_white_space, end_quote_pos + 1)); 1392 else 1393 command_string.erase(); 1394 } 1395 } else { 1396 const size_t first_space_pos = 1397 command_string.find_first_of(k_white_space); 1398 if (first_space_pos == std::string::npos) { 1399 command.swap(command_string); 1400 command_string.erase(); 1401 } else { 1402 command.assign(command_string, 0, first_space_pos); 1403 command_string.erase(0, command_string.find_first_not_of( 1404 k_white_space, first_space_pos)); 1405 } 1406 } 1407 result = true; 1408 } 1409 1410 if (!command.empty()) { 1411 // actual commands can't start with '-' or '_' 1412 if (command[0] != '-' && command[0] != '_') { 1413 size_t pos = command.find_first_not_of(k_valid_command_chars); 1414 if (pos > 0 && pos != std::string::npos) { 1415 suffix.assign(command.begin() + pos, command.end()); 1416 command.erase(pos); 1417 } 1418 } 1419 } 1420 1421 return result; 1422 } 1423 1424 CommandObject *CommandInterpreter::BuildAliasResult( 1425 llvm::StringRef alias_name, std::string &raw_input_string, 1426 std::string &alias_result, CommandReturnObject &result) { 1427 CommandObject *alias_cmd_obj = nullptr; 1428 Args cmd_args(raw_input_string); 1429 alias_cmd_obj = GetCommandObject(alias_name); 1430 StreamString result_str; 1431 1432 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) { 1433 alias_result.clear(); 1434 return alias_cmd_obj; 1435 } 1436 std::pair<CommandObjectSP, OptionArgVectorSP> desugared = 1437 ((CommandAlias *)alias_cmd_obj)->Desugar(); 1438 OptionArgVectorSP option_arg_vector_sp = desugared.second; 1439 alias_cmd_obj = desugared.first.get(); 1440 std::string alias_name_str = std::string(alias_name); 1441 if ((cmd_args.GetArgumentCount() == 0) || 1442 (alias_name_str != cmd_args.GetArgumentAtIndex(0))) 1443 cmd_args.Unshift(alias_name_str); 1444 1445 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str()); 1446 1447 if (!option_arg_vector_sp.get()) { 1448 alias_result = std::string(result_str.GetString()); 1449 return alias_cmd_obj; 1450 } 1451 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 1452 1453 int value_type; 1454 std::string option; 1455 std::string value; 1456 for (const auto &entry : *option_arg_vector) { 1457 std::tie(option, value_type, value) = entry; 1458 if (option == "<argument>") { 1459 result_str.Printf(" %s", value.c_str()); 1460 continue; 1461 } 1462 1463 result_str.Printf(" %s", option.c_str()); 1464 if (value_type == OptionParser::eNoArgument) 1465 continue; 1466 1467 if (value_type != OptionParser::eOptionalArgument) 1468 result_str.Printf(" "); 1469 int index = GetOptionArgumentPosition(value.c_str()); 1470 if (index == 0) 1471 result_str.Printf("%s", value.c_str()); 1472 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) { 1473 1474 result.AppendErrorWithFormat("Not enough arguments provided; you " 1475 "need at least %d arguments to use " 1476 "this alias.\n", 1477 index); 1478 return nullptr; 1479 } else { 1480 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index)); 1481 if (strpos != std::string::npos) 1482 raw_input_string = raw_input_string.erase( 1483 strpos, strlen(cmd_args.GetArgumentAtIndex(index))); 1484 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index)); 1485 } 1486 } 1487 1488 alias_result = std::string(result_str.GetString()); 1489 return alias_cmd_obj; 1490 } 1491 1492 Status CommandInterpreter::PreprocessCommand(std::string &command) { 1493 // The command preprocessor needs to do things to the command line before any 1494 // parsing of arguments or anything else is done. The only current stuff that 1495 // gets preprocessed is anything enclosed in backtick ('`') characters is 1496 // evaluated as an expression and the result of the expression must be a 1497 // scalar that can be substituted into the command. An example would be: 1498 // (lldb) memory read `$rsp + 20` 1499 Status error; // Status for any expressions that might not evaluate 1500 size_t start_backtick; 1501 size_t pos = 0; 1502 while ((start_backtick = command.find('`', pos)) != std::string::npos) { 1503 // Stop if an error was encountered during the previous iteration. 1504 if (error.Fail()) 1505 break; 1506 1507 if (start_backtick > 0 && command[start_backtick - 1] == '\\') { 1508 // The backtick was preceded by a '\' character, remove the slash and 1509 // don't treat the backtick as the start of an expression. 1510 command.erase(start_backtick - 1, 1); 1511 // No need to add one to start_backtick since we just deleted a char. 1512 pos = start_backtick; 1513 continue; 1514 } 1515 1516 const size_t expr_content_start = start_backtick + 1; 1517 const size_t end_backtick = command.find('`', expr_content_start); 1518 1519 if (end_backtick == std::string::npos) { 1520 // Stop if there's no end backtick. 1521 break; 1522 } 1523 1524 if (end_backtick == expr_content_start) { 1525 // Skip over empty expression. (two backticks in a row) 1526 command.erase(start_backtick, 2); 1527 continue; 1528 } 1529 1530 std::string expr_str(command, expr_content_start, 1531 end_backtick - expr_content_start); 1532 1533 ExecutionContext exe_ctx(GetExecutionContext()); 1534 1535 // Get a dummy target to allow for calculator mode while processing 1536 // backticks. This also helps break the infinite loop caused when target is 1537 // null. 1538 Target *exe_target = exe_ctx.GetTargetPtr(); 1539 Target &target = exe_target ? *exe_target : m_debugger.GetDummyTarget(); 1540 1541 ValueObjectSP expr_result_valobj_sp; 1542 1543 EvaluateExpressionOptions options; 1544 options.SetCoerceToId(false); 1545 options.SetUnwindOnError(true); 1546 options.SetIgnoreBreakpoints(true); 1547 options.SetKeepInMemory(false); 1548 options.SetTryAllThreads(true); 1549 options.SetTimeout(llvm::None); 1550 1551 ExpressionResults expr_result = 1552 target.EvaluateExpression(expr_str.c_str(), exe_ctx.GetFramePtr(), 1553 expr_result_valobj_sp, options); 1554 1555 if (expr_result == eExpressionCompleted) { 1556 Scalar scalar; 1557 if (expr_result_valobj_sp) 1558 expr_result_valobj_sp = 1559 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable( 1560 expr_result_valobj_sp->GetDynamicValueType(), true); 1561 if (expr_result_valobj_sp->ResolveValue(scalar)) { 1562 command.erase(start_backtick, end_backtick - start_backtick + 1); 1563 StreamString value_strm; 1564 const bool show_type = false; 1565 scalar.GetValue(&value_strm, show_type); 1566 size_t value_string_size = value_strm.GetSize(); 1567 if (value_string_size) { 1568 command.insert(start_backtick, std::string(value_strm.GetString())); 1569 pos = start_backtick + value_string_size; 1570 continue; 1571 } else { 1572 error.SetErrorStringWithFormat("expression value didn't result " 1573 "in a scalar value for the " 1574 "expression '%s'", 1575 expr_str.c_str()); 1576 break; 1577 } 1578 } else { 1579 error.SetErrorStringWithFormat("expression value didn't result " 1580 "in a scalar value for the " 1581 "expression '%s'", 1582 expr_str.c_str()); 1583 break; 1584 } 1585 1586 continue; 1587 } 1588 1589 if (expr_result_valobj_sp) 1590 error = expr_result_valobj_sp->GetError(); 1591 1592 if (error.Success()) { 1593 switch (expr_result) { 1594 case eExpressionSetupError: 1595 error.SetErrorStringWithFormat( 1596 "expression setup error for the expression '%s'", expr_str.c_str()); 1597 break; 1598 case eExpressionParseError: 1599 error.SetErrorStringWithFormat( 1600 "expression parse error for the expression '%s'", expr_str.c_str()); 1601 break; 1602 case eExpressionResultUnavailable: 1603 error.SetErrorStringWithFormat( 1604 "expression error fetching result for the expression '%s'", 1605 expr_str.c_str()); 1606 break; 1607 case eExpressionCompleted: 1608 break; 1609 case eExpressionDiscarded: 1610 error.SetErrorStringWithFormat( 1611 "expression discarded for the expression '%s'", expr_str.c_str()); 1612 break; 1613 case eExpressionInterrupted: 1614 error.SetErrorStringWithFormat( 1615 "expression interrupted for the expression '%s'", expr_str.c_str()); 1616 break; 1617 case eExpressionHitBreakpoint: 1618 error.SetErrorStringWithFormat( 1619 "expression hit breakpoint for the expression '%s'", 1620 expr_str.c_str()); 1621 break; 1622 case eExpressionTimedOut: 1623 error.SetErrorStringWithFormat( 1624 "expression timed out for the expression '%s'", expr_str.c_str()); 1625 break; 1626 case eExpressionStoppedForDebug: 1627 error.SetErrorStringWithFormat("expression stop at entry point " 1628 "for debugging for the " 1629 "expression '%s'", 1630 expr_str.c_str()); 1631 break; 1632 case eExpressionThreadVanished: 1633 error.SetErrorStringWithFormat( 1634 "expression thread vanished for the expression '%s'", 1635 expr_str.c_str()); 1636 break; 1637 } 1638 } 1639 } 1640 return error; 1641 } 1642 1643 bool CommandInterpreter::HandleCommand(const char *command_line, 1644 LazyBool lazy_add_to_history, 1645 const ExecutionContext &override_context, 1646 CommandReturnObject &result) { 1647 1648 OverrideExecutionContext(override_context); 1649 bool status = HandleCommand(command_line, lazy_add_to_history, result); 1650 RestoreExecutionContext(); 1651 return status; 1652 } 1653 1654 bool CommandInterpreter::HandleCommand(const char *command_line, 1655 LazyBool lazy_add_to_history, 1656 CommandReturnObject &result) { 1657 1658 std::string command_string(command_line); 1659 std::string original_command_string(command_line); 1660 1661 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS)); 1662 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")", 1663 command_line); 1664 1665 LLDB_LOGF(log, "Processing command: %s", command_line); 1666 LLDB_SCOPED_TIMERF("Processing command: %s.", command_line); 1667 1668 if (WasInterrupted()) { 1669 result.AppendError("interrupted"); 1670 return false; 1671 } 1672 1673 bool add_to_history; 1674 if (lazy_add_to_history == eLazyBoolCalculate) 1675 add_to_history = (m_command_source_depth == 0); 1676 else 1677 add_to_history = (lazy_add_to_history == eLazyBoolYes); 1678 1679 m_transcript_stream << "(lldb) " << command_line << '\n'; 1680 1681 bool empty_command = false; 1682 bool comment_command = false; 1683 if (command_string.empty()) 1684 empty_command = true; 1685 else { 1686 const char *k_space_characters = "\t\n\v\f\r "; 1687 1688 size_t non_space = command_string.find_first_not_of(k_space_characters); 1689 // Check for empty line or comment line (lines whose first non-space 1690 // character is the comment character for this interpreter) 1691 if (non_space == std::string::npos) 1692 empty_command = true; 1693 else if (command_string[non_space] == m_comment_char) 1694 comment_command = true; 1695 else if (command_string[non_space] == CommandHistory::g_repeat_char) { 1696 llvm::StringRef search_str(command_string); 1697 search_str = search_str.drop_front(non_space); 1698 if (auto hist_str = m_command_history.FindString(search_str)) { 1699 add_to_history = false; 1700 command_string = std::string(*hist_str); 1701 original_command_string = std::string(*hist_str); 1702 } else { 1703 result.AppendErrorWithFormat("Could not find entry: %s in history", 1704 command_string.c_str()); 1705 return false; 1706 } 1707 } 1708 } 1709 1710 if (empty_command) { 1711 if (!GetRepeatPreviousCommand()) { 1712 result.SetStatus(eReturnStatusSuccessFinishNoResult); 1713 return true; 1714 } 1715 1716 if (m_command_history.IsEmpty()) { 1717 result.AppendError("empty command"); 1718 return false; 1719 } 1720 1721 command_line = m_repeat_command.c_str(); 1722 command_string = command_line; 1723 original_command_string = command_line; 1724 if (m_repeat_command.empty()) { 1725 result.AppendError("No auto repeat."); 1726 return false; 1727 } 1728 1729 add_to_history = false; 1730 } else if (comment_command) { 1731 result.SetStatus(eReturnStatusSuccessFinishNoResult); 1732 return true; 1733 } 1734 1735 Status error(PreprocessCommand(command_string)); 1736 1737 if (error.Fail()) { 1738 result.AppendError(error.AsCString()); 1739 return false; 1740 } 1741 1742 // Phase 1. 1743 1744 // Before we do ANY kind of argument processing, we need to figure out what 1745 // the real/final command object is for the specified command. This gets 1746 // complicated by the fact that the user could have specified an alias, and, 1747 // in translating the alias, there may also be command options and/or even 1748 // data (including raw text strings) that need to be found and inserted into 1749 // the command line as part of the translation. So this first step is plain 1750 // look-up and replacement, resulting in: 1751 // 1. the command object whose Execute method will actually be called 1752 // 2. a revised command string, with all substitutions and replacements 1753 // taken care of 1754 // From 1 above, we can determine whether the Execute function wants raw 1755 // input or not. 1756 1757 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result); 1758 1759 // Although the user may have abbreviated the command, the command_string now 1760 // has the command expanded to the full name. For example, if the input was 1761 // "br s -n main", command_string is now "breakpoint set -n main". 1762 if (log) { 1763 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>"; 1764 LLDB_LOGF(log, "HandleCommand, cmd_obj : '%s'", command_name.str().c_str()); 1765 LLDB_LOGF(log, "HandleCommand, (revised) command_string: '%s'", 1766 command_string.c_str()); 1767 const bool wants_raw_input = 1768 (cmd_obj != nullptr) ? cmd_obj->WantsRawCommandString() : false; 1769 LLDB_LOGF(log, "HandleCommand, wants_raw_input:'%s'", 1770 wants_raw_input ? "True" : "False"); 1771 } 1772 1773 // Phase 2. 1774 // Take care of things like setting up the history command & calling the 1775 // appropriate Execute method on the CommandObject, with the appropriate 1776 // arguments. 1777 1778 if (cmd_obj != nullptr) { 1779 if (add_to_history) { 1780 Args command_args(command_string); 1781 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0); 1782 if (repeat_command != nullptr) 1783 m_repeat_command.assign(repeat_command); 1784 else 1785 m_repeat_command.assign(original_command_string); 1786 1787 m_command_history.AppendString(original_command_string); 1788 } 1789 1790 std::string remainder; 1791 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size(); 1792 if (actual_cmd_name_len < command_string.length()) 1793 remainder = command_string.substr(actual_cmd_name_len); 1794 1795 // Remove any initial spaces 1796 size_t pos = remainder.find_first_not_of(k_white_space); 1797 if (pos != 0 && pos != std::string::npos) 1798 remainder.erase(0, pos); 1799 1800 LLDB_LOGF( 1801 log, "HandleCommand, command line after removing command name(s): '%s'", 1802 remainder.c_str()); 1803 1804 cmd_obj->Execute(remainder.c_str(), result); 1805 } 1806 1807 LLDB_LOGF(log, "HandleCommand, command %s", 1808 (result.Succeeded() ? "succeeded" : "did not succeed")); 1809 1810 m_transcript_stream << result.GetOutputData(); 1811 m_transcript_stream << result.GetErrorData(); 1812 1813 return result.Succeeded(); 1814 } 1815 1816 void CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) { 1817 bool look_for_subcommand = false; 1818 1819 // For any of the command completions a unique match will be a complete word. 1820 1821 if (request.GetParsedLine().GetArgumentCount() == 0) { 1822 // We got nothing on the command line, so return the list of commands 1823 bool include_aliases = true; 1824 StringList new_matches, descriptions; 1825 GetCommandNamesMatchingPartialString("", include_aliases, new_matches, 1826 descriptions); 1827 request.AddCompletions(new_matches, descriptions); 1828 } else if (request.GetCursorIndex() == 0) { 1829 // The cursor is in the first argument, so just do a lookup in the 1830 // dictionary. 1831 StringList new_matches, new_descriptions; 1832 CommandObject *cmd_obj = 1833 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0), 1834 &new_matches, &new_descriptions); 1835 1836 if (new_matches.GetSize() && cmd_obj && cmd_obj->IsMultiwordObject() && 1837 new_matches.GetStringAtIndex(0) != nullptr && 1838 strcmp(request.GetParsedLine().GetArgumentAtIndex(0), 1839 new_matches.GetStringAtIndex(0)) == 0) { 1840 if (request.GetParsedLine().GetArgumentCount() != 1) { 1841 look_for_subcommand = true; 1842 new_matches.DeleteStringAtIndex(0); 1843 new_descriptions.DeleteStringAtIndex(0); 1844 request.AppendEmptyArgument(); 1845 } 1846 } 1847 request.AddCompletions(new_matches, new_descriptions); 1848 } 1849 1850 if (request.GetCursorIndex() > 0 || look_for_subcommand) { 1851 // We are completing further on into a commands arguments, so find the 1852 // command and tell it to complete the command. First see if there is a 1853 // matching initial command: 1854 CommandObject *command_object = 1855 GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0)); 1856 if (command_object) { 1857 request.ShiftArguments(); 1858 command_object->HandleCompletion(request); 1859 } 1860 } 1861 } 1862 1863 void CommandInterpreter::HandleCompletion(CompletionRequest &request) { 1864 1865 // Don't complete comments, and if the line we are completing is just the 1866 // history repeat character, substitute the appropriate history line. 1867 llvm::StringRef first_arg = request.GetParsedLine().GetArgumentAtIndex(0); 1868 1869 if (!first_arg.empty()) { 1870 if (first_arg.front() == m_comment_char) 1871 return; 1872 if (first_arg.front() == CommandHistory::g_repeat_char) { 1873 if (auto hist_str = m_command_history.FindString(first_arg)) 1874 request.AddCompletion(*hist_str, "Previous command history event", 1875 CompletionMode::RewriteLine); 1876 return; 1877 } 1878 } 1879 1880 HandleCompletionMatches(request); 1881 } 1882 1883 llvm::Optional<std::string> 1884 CommandInterpreter::GetAutoSuggestionForCommand(llvm::StringRef line) { 1885 if (line.empty()) 1886 return llvm::None; 1887 const size_t s = m_command_history.GetSize(); 1888 for (int i = s - 1; i >= 0; --i) { 1889 llvm::StringRef entry = m_command_history.GetStringAtIndex(i); 1890 if (entry.consume_front(line)) 1891 return entry.str(); 1892 } 1893 return llvm::None; 1894 } 1895 1896 void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) { 1897 EventSP prompt_change_event_sp( 1898 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt))); 1899 ; 1900 BroadcastEvent(prompt_change_event_sp); 1901 if (m_command_io_handler_sp) 1902 m_command_io_handler_sp->SetPrompt(new_prompt); 1903 } 1904 1905 bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) { 1906 // Check AutoConfirm first: 1907 if (m_debugger.GetAutoConfirm()) 1908 return default_answer; 1909 1910 IOHandlerConfirm *confirm = 1911 new IOHandlerConfirm(m_debugger, message, default_answer); 1912 IOHandlerSP io_handler_sp(confirm); 1913 m_debugger.RunIOHandlerSync(io_handler_sp); 1914 return confirm->GetResponse(); 1915 } 1916 1917 const CommandAlias * 1918 CommandInterpreter::GetAlias(llvm::StringRef alias_name) const { 1919 OptionArgVectorSP ret_val; 1920 1921 auto pos = m_alias_dict.find(std::string(alias_name)); 1922 if (pos != m_alias_dict.end()) 1923 return (CommandAlias *)pos->second.get(); 1924 1925 return nullptr; 1926 } 1927 1928 bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); } 1929 1930 bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); } 1931 1932 bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); } 1933 1934 bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); } 1935 1936 void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj, 1937 const char *alias_name, 1938 Args &cmd_args, 1939 std::string &raw_input_string, 1940 CommandReturnObject &result) { 1941 OptionArgVectorSP option_arg_vector_sp = 1942 GetAlias(alias_name)->GetOptionArguments(); 1943 1944 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString(); 1945 1946 // Make sure that the alias name is the 0th element in cmd_args 1947 std::string alias_name_str = alias_name; 1948 if (alias_name_str != cmd_args.GetArgumentAtIndex(0)) 1949 cmd_args.Unshift(alias_name_str); 1950 1951 Args new_args(alias_cmd_obj->GetCommandName()); 1952 if (new_args.GetArgumentCount() == 2) 1953 new_args.Shift(); 1954 1955 if (option_arg_vector_sp.get()) { 1956 if (wants_raw_input) { 1957 // We have a command that both has command options and takes raw input. 1958 // Make *sure* it has a " -- " in the right place in the 1959 // raw_input_string. 1960 size_t pos = raw_input_string.find(" -- "); 1961 if (pos == std::string::npos) { 1962 // None found; assume it goes at the beginning of the raw input string 1963 raw_input_string.insert(0, " -- "); 1964 } 1965 } 1966 1967 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 1968 const size_t old_size = cmd_args.GetArgumentCount(); 1969 std::vector<bool> used(old_size + 1, false); 1970 1971 used[0] = true; 1972 1973 int value_type; 1974 std::string option; 1975 std::string value; 1976 for (const auto &option_entry : *option_arg_vector) { 1977 std::tie(option, value_type, value) = option_entry; 1978 if (option == "<argument>") { 1979 if (!wants_raw_input || (value != "--")) { 1980 // Since we inserted this above, make sure we don't insert it twice 1981 new_args.AppendArgument(value); 1982 } 1983 continue; 1984 } 1985 1986 if (value_type != OptionParser::eOptionalArgument) 1987 new_args.AppendArgument(option); 1988 1989 if (value == "<no-argument>") 1990 continue; 1991 1992 int index = GetOptionArgumentPosition(value.c_str()); 1993 if (index == 0) { 1994 // value was NOT a positional argument; must be a real value 1995 if (value_type != OptionParser::eOptionalArgument) 1996 new_args.AppendArgument(value); 1997 else { 1998 new_args.AppendArgument(option + value); 1999 } 2000 2001 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) { 2002 result.AppendErrorWithFormat("Not enough arguments provided; you " 2003 "need at least %d arguments to use " 2004 "this alias.\n", 2005 index); 2006 return; 2007 } else { 2008 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string 2009 size_t strpos = 2010 raw_input_string.find(cmd_args.GetArgumentAtIndex(index)); 2011 if (strpos != std::string::npos) { 2012 raw_input_string = raw_input_string.erase( 2013 strpos, strlen(cmd_args.GetArgumentAtIndex(index))); 2014 } 2015 2016 if (value_type != OptionParser::eOptionalArgument) 2017 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index)); 2018 else { 2019 new_args.AppendArgument(option + cmd_args.GetArgumentAtIndex(index)); 2020 } 2021 used[index] = true; 2022 } 2023 } 2024 2025 for (auto entry : llvm::enumerate(cmd_args.entries())) { 2026 if (!used[entry.index()] && !wants_raw_input) 2027 new_args.AppendArgument(entry.value().ref()); 2028 } 2029 2030 cmd_args.Clear(); 2031 cmd_args.SetArguments(new_args.GetArgumentCount(), 2032 new_args.GetConstArgumentVector()); 2033 } else { 2034 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2035 // This alias was not created with any options; nothing further needs to be 2036 // done, unless it is a command that wants raw input, in which case we need 2037 // to clear the rest of the data from cmd_args, since its in the raw input 2038 // string. 2039 if (wants_raw_input) { 2040 cmd_args.Clear(); 2041 cmd_args.SetArguments(new_args.GetArgumentCount(), 2042 new_args.GetConstArgumentVector()); 2043 } 2044 return; 2045 } 2046 2047 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2048 return; 2049 } 2050 2051 int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) { 2052 int position = 0; // Any string that isn't an argument position, i.e. '%' 2053 // followed by an integer, gets a position 2054 // of zero. 2055 2056 const char *cptr = in_string; 2057 2058 // Does it start with '%' 2059 if (cptr[0] == '%') { 2060 ++cptr; 2061 2062 // Is the rest of it entirely digits? 2063 if (isdigit(cptr[0])) { 2064 const char *start = cptr; 2065 while (isdigit(cptr[0])) 2066 ++cptr; 2067 2068 // We've gotten to the end of the digits; are we at the end of the 2069 // string? 2070 if (cptr[0] == '\0') 2071 position = atoi(start); 2072 } 2073 } 2074 2075 return position; 2076 } 2077 2078 static void GetHomeInitFile(llvm::SmallVectorImpl<char> &init_file, 2079 llvm::StringRef suffix = {}) { 2080 std::string init_file_name = ".lldbinit"; 2081 if (!suffix.empty()) { 2082 init_file_name.append("-"); 2083 init_file_name.append(suffix.str()); 2084 } 2085 2086 FileSystem::Instance().GetHomeDirectory(init_file); 2087 llvm::sys::path::append(init_file, init_file_name); 2088 2089 FileSystem::Instance().Resolve(init_file); 2090 } 2091 2092 static void GetHomeREPLInitFile(llvm::SmallVectorImpl<char> &init_file) { 2093 LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs(); 2094 LanguageType language = eLanguageTypeUnknown; 2095 if (auto main_repl_language = repl_languages.GetSingularLanguage()) 2096 language = *main_repl_language; 2097 else 2098 return; 2099 2100 std::string init_file_name = 2101 (llvm::Twine(".lldbinit-") + 2102 llvm::Twine(Language::GetNameForLanguageType(language)) + 2103 llvm::Twine("-repl")) 2104 .str(); 2105 FileSystem::Instance().GetHomeDirectory(init_file); 2106 llvm::sys::path::append(init_file, init_file_name); 2107 FileSystem::Instance().Resolve(init_file); 2108 } 2109 2110 static void GetCwdInitFile(llvm::SmallVectorImpl<char> &init_file) { 2111 llvm::StringRef s = ".lldbinit"; 2112 init_file.assign(s.begin(), s.end()); 2113 FileSystem::Instance().Resolve(init_file); 2114 } 2115 2116 void CommandInterpreter::SourceInitFile(FileSpec file, 2117 CommandReturnObject &result) { 2118 assert(!m_skip_lldbinit_files); 2119 2120 if (!FileSystem::Instance().Exists(file)) { 2121 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2122 return; 2123 } 2124 2125 // Use HandleCommand to 'source' the given file; this will do the actual 2126 // broadcasting of the commands back to any appropriate listener (see 2127 // CommandObjectSource::Execute for more details). 2128 const bool saved_batch = SetBatchCommandMode(true); 2129 CommandInterpreterRunOptions options; 2130 options.SetSilent(true); 2131 options.SetPrintErrors(true); 2132 options.SetStopOnError(false); 2133 options.SetStopOnContinue(true); 2134 HandleCommandsFromFile(file, options, result); 2135 SetBatchCommandMode(saved_batch); 2136 } 2137 2138 void CommandInterpreter::SourceInitFileCwd(CommandReturnObject &result) { 2139 if (m_skip_lldbinit_files) { 2140 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2141 return; 2142 } 2143 2144 llvm::SmallString<128> init_file; 2145 GetCwdInitFile(init_file); 2146 if (!FileSystem::Instance().Exists(init_file)) { 2147 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2148 return; 2149 } 2150 2151 LoadCWDlldbinitFile should_load = 2152 Target::GetGlobalProperties().GetLoadCWDlldbinitFile(); 2153 2154 switch (should_load) { 2155 case eLoadCWDlldbinitFalse: 2156 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2157 break; 2158 case eLoadCWDlldbinitTrue: 2159 SourceInitFile(FileSpec(init_file.str()), result); 2160 break; 2161 case eLoadCWDlldbinitWarn: { 2162 llvm::SmallString<128> home_init_file; 2163 GetHomeInitFile(home_init_file); 2164 if (llvm::sys::path::parent_path(init_file) == 2165 llvm::sys::path::parent_path(home_init_file)) { 2166 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2167 } else { 2168 result.AppendError(InitFileWarning); 2169 } 2170 } 2171 } 2172 } 2173 2174 /// We will first see if there is an application specific ".lldbinit" file 2175 /// whose name is "~/.lldbinit" followed by a "-" and the name of the program. 2176 /// If this file doesn't exist, we fall back to the REPL init file or the 2177 /// default home init file in "~/.lldbinit". 2178 void CommandInterpreter::SourceInitFileHome(CommandReturnObject &result, 2179 bool is_repl) { 2180 if (m_skip_lldbinit_files) { 2181 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2182 return; 2183 } 2184 2185 llvm::SmallString<128> init_file; 2186 2187 if (is_repl) 2188 GetHomeREPLInitFile(init_file); 2189 2190 if (init_file.empty()) 2191 GetHomeInitFile(init_file); 2192 2193 if (!m_skip_app_init_files) { 2194 llvm::StringRef program_name = 2195 HostInfo::GetProgramFileSpec().GetFilename().GetStringRef(); 2196 llvm::SmallString<128> program_init_file; 2197 GetHomeInitFile(program_init_file, program_name); 2198 if (FileSystem::Instance().Exists(program_init_file)) 2199 init_file = program_init_file; 2200 } 2201 2202 SourceInitFile(FileSpec(init_file.str()), result); 2203 } 2204 2205 const char *CommandInterpreter::GetCommandPrefix() { 2206 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix(); 2207 return prefix == nullptr ? "" : prefix; 2208 } 2209 2210 PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) { 2211 PlatformSP platform_sp; 2212 if (prefer_target_platform) { 2213 ExecutionContext exe_ctx(GetExecutionContext()); 2214 Target *target = exe_ctx.GetTargetPtr(); 2215 if (target) 2216 platform_sp = target->GetPlatform(); 2217 } 2218 2219 if (!platform_sp) 2220 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform(); 2221 return platform_sp; 2222 } 2223 2224 bool CommandInterpreter::DidProcessStopAbnormally() const { 2225 auto exe_ctx = GetExecutionContext(); 2226 TargetSP target_sp = exe_ctx.GetTargetSP(); 2227 if (!target_sp) 2228 return false; 2229 2230 ProcessSP process_sp(target_sp->GetProcessSP()); 2231 if (!process_sp) 2232 return false; 2233 2234 if (eStateStopped != process_sp->GetState()) 2235 return false; 2236 2237 for (const auto &thread_sp : process_sp->GetThreadList().Threads()) { 2238 StopInfoSP stop_info = thread_sp->GetStopInfo(); 2239 if (!stop_info) 2240 return false; 2241 2242 const StopReason reason = stop_info->GetStopReason(); 2243 if (reason == eStopReasonException || 2244 reason == eStopReasonInstrumentation || 2245 reason == eStopReasonProcessorTrace) 2246 return true; 2247 2248 if (reason == eStopReasonSignal) { 2249 const auto stop_signal = static_cast<int32_t>(stop_info->GetValue()); 2250 UnixSignalsSP signals_sp = process_sp->GetUnixSignals(); 2251 if (!signals_sp || !signals_sp->SignalIsValid(stop_signal)) 2252 // The signal is unknown, treat it as abnormal. 2253 return true; 2254 2255 const auto sigint_num = signals_sp->GetSignalNumberFromName("SIGINT"); 2256 const auto sigstop_num = signals_sp->GetSignalNumberFromName("SIGSTOP"); 2257 if ((stop_signal != sigint_num) && (stop_signal != sigstop_num)) 2258 // The signal very likely implies a crash. 2259 return true; 2260 } 2261 } 2262 2263 return false; 2264 } 2265 2266 void 2267 CommandInterpreter::HandleCommands(const StringList &commands, 2268 const ExecutionContext &override_context, 2269 const CommandInterpreterRunOptions &options, 2270 CommandReturnObject &result) { 2271 2272 OverrideExecutionContext(override_context); 2273 HandleCommands(commands, options, result); 2274 RestoreExecutionContext(); 2275 } 2276 2277 void CommandInterpreter::HandleCommands(const StringList &commands, 2278 const CommandInterpreterRunOptions &options, 2279 CommandReturnObject &result) { 2280 size_t num_lines = commands.GetSize(); 2281 2282 // If we are going to continue past a "continue" then we need to run the 2283 // commands synchronously. Make sure you reset this value anywhere you return 2284 // from the function. 2285 2286 bool old_async_execution = m_debugger.GetAsyncExecution(); 2287 2288 if (!options.GetStopOnContinue()) { 2289 m_debugger.SetAsyncExecution(false); 2290 } 2291 2292 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) { 2293 const char *cmd = commands.GetStringAtIndex(idx); 2294 if (cmd[0] == '\0') 2295 continue; 2296 2297 if (options.GetEchoCommands()) { 2298 // TODO: Add Stream support. 2299 result.AppendMessageWithFormat("%s %s\n", 2300 m_debugger.GetPrompt().str().c_str(), cmd); 2301 } 2302 2303 CommandReturnObject tmp_result(m_debugger.GetUseColor()); 2304 tmp_result.SetInteractive(result.GetInteractive()); 2305 tmp_result.SetSuppressImmediateOutput(true); 2306 2307 // We might call into a regex or alias command, in which case the 2308 // add_to_history will get lost. This m_command_source_depth dingus is the 2309 // way we turn off adding to the history in that case, so set it up here. 2310 if (!options.GetAddToHistory()) 2311 m_command_source_depth++; 2312 bool success = HandleCommand(cmd, options.m_add_to_history, tmp_result); 2313 if (!options.GetAddToHistory()) 2314 m_command_source_depth--; 2315 2316 if (options.GetPrintResults()) { 2317 if (tmp_result.Succeeded()) 2318 result.AppendMessage(tmp_result.GetOutputData()); 2319 } 2320 2321 if (!success || !tmp_result.Succeeded()) { 2322 llvm::StringRef error_msg = tmp_result.GetErrorData(); 2323 if (error_msg.empty()) 2324 error_msg = "<unknown error>.\n"; 2325 if (options.GetStopOnError()) { 2326 result.AppendErrorWithFormat( 2327 "Aborting reading of commands after command #%" PRIu64 2328 ": '%s' failed with %s", 2329 (uint64_t)idx, cmd, error_msg.str().c_str()); 2330 m_debugger.SetAsyncExecution(old_async_execution); 2331 return; 2332 } else if (options.GetPrintResults()) { 2333 result.AppendMessageWithFormat( 2334 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd, 2335 error_msg.str().c_str()); 2336 } 2337 } 2338 2339 if (result.GetImmediateOutputStream()) 2340 result.GetImmediateOutputStream()->Flush(); 2341 2342 if (result.GetImmediateErrorStream()) 2343 result.GetImmediateErrorStream()->Flush(); 2344 2345 // N.B. Can't depend on DidChangeProcessState, because the state coming 2346 // into the command execution could be running (for instance in Breakpoint 2347 // Commands. So we check the return value to see if it is has running in 2348 // it. 2349 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) || 2350 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) { 2351 if (options.GetStopOnContinue()) { 2352 // If we caused the target to proceed, and we're going to stop in that 2353 // case, set the status in our real result before returning. This is 2354 // an error if the continue was not the last command in the set of 2355 // commands to be run. 2356 if (idx != num_lines - 1) 2357 result.AppendErrorWithFormat( 2358 "Aborting reading of commands after command #%" PRIu64 2359 ": '%s' continued the target.\n", 2360 (uint64_t)idx + 1, cmd); 2361 else 2362 result.AppendMessageWithFormat("Command #%" PRIu64 2363 " '%s' continued the target.\n", 2364 (uint64_t)idx + 1, cmd); 2365 2366 result.SetStatus(tmp_result.GetStatus()); 2367 m_debugger.SetAsyncExecution(old_async_execution); 2368 2369 return; 2370 } 2371 } 2372 2373 // Also check for "stop on crash here: 2374 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash() && 2375 DidProcessStopAbnormally()) { 2376 if (idx != num_lines - 1) 2377 result.AppendErrorWithFormat( 2378 "Aborting reading of commands after command #%" PRIu64 2379 ": '%s' stopped with a signal or exception.\n", 2380 (uint64_t)idx + 1, cmd); 2381 else 2382 result.AppendMessageWithFormat( 2383 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n", 2384 (uint64_t)idx + 1, cmd); 2385 2386 result.SetStatus(tmp_result.GetStatus()); 2387 m_debugger.SetAsyncExecution(old_async_execution); 2388 2389 return; 2390 } 2391 } 2392 2393 result.SetStatus(eReturnStatusSuccessFinishResult); 2394 m_debugger.SetAsyncExecution(old_async_execution); 2395 2396 return; 2397 } 2398 2399 // Make flags that we can pass into the IOHandler so our delegates can do the 2400 // right thing 2401 enum { 2402 eHandleCommandFlagStopOnContinue = (1u << 0), 2403 eHandleCommandFlagStopOnError = (1u << 1), 2404 eHandleCommandFlagEchoCommand = (1u << 2), 2405 eHandleCommandFlagEchoCommentCommand = (1u << 3), 2406 eHandleCommandFlagPrintResult = (1u << 4), 2407 eHandleCommandFlagPrintErrors = (1u << 5), 2408 eHandleCommandFlagStopOnCrash = (1u << 6) 2409 }; 2410 2411 void CommandInterpreter::HandleCommandsFromFile( 2412 FileSpec &cmd_file, const ExecutionContext &context, 2413 const CommandInterpreterRunOptions &options, CommandReturnObject &result) { 2414 OverrideExecutionContext(context); 2415 HandleCommandsFromFile(cmd_file, options, result); 2416 RestoreExecutionContext(); 2417 } 2418 2419 void CommandInterpreter::HandleCommandsFromFile(FileSpec &cmd_file, 2420 const CommandInterpreterRunOptions &options, CommandReturnObject &result) { 2421 if (!FileSystem::Instance().Exists(cmd_file)) { 2422 result.AppendErrorWithFormat( 2423 "Error reading commands from file %s - file not found.\n", 2424 cmd_file.GetFilename().AsCString("<Unknown>")); 2425 return; 2426 } 2427 2428 std::string cmd_file_path = cmd_file.GetPath(); 2429 auto input_file_up = 2430 FileSystem::Instance().Open(cmd_file, File::eOpenOptionReadOnly); 2431 if (!input_file_up) { 2432 std::string error = llvm::toString(input_file_up.takeError()); 2433 result.AppendErrorWithFormatv( 2434 "error: an error occurred read file '{0}': {1}\n", cmd_file_path, 2435 llvm::fmt_consume(input_file_up.takeError())); 2436 return; 2437 } 2438 FileSP input_file_sp = FileSP(std::move(input_file_up.get())); 2439 2440 Debugger &debugger = GetDebugger(); 2441 2442 uint32_t flags = 0; 2443 2444 if (options.m_stop_on_continue == eLazyBoolCalculate) { 2445 if (m_command_source_flags.empty()) { 2446 // Stop on continue by default 2447 flags |= eHandleCommandFlagStopOnContinue; 2448 } else if (m_command_source_flags.back() & 2449 eHandleCommandFlagStopOnContinue) { 2450 flags |= eHandleCommandFlagStopOnContinue; 2451 } 2452 } else if (options.m_stop_on_continue == eLazyBoolYes) { 2453 flags |= eHandleCommandFlagStopOnContinue; 2454 } 2455 2456 if (options.m_stop_on_error == eLazyBoolCalculate) { 2457 if (m_command_source_flags.empty()) { 2458 if (GetStopCmdSourceOnError()) 2459 flags |= eHandleCommandFlagStopOnError; 2460 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) { 2461 flags |= eHandleCommandFlagStopOnError; 2462 } 2463 } else if (options.m_stop_on_error == eLazyBoolYes) { 2464 flags |= eHandleCommandFlagStopOnError; 2465 } 2466 2467 // stop-on-crash can only be set, if it is present in all levels of 2468 // pushed flag sets. 2469 if (options.GetStopOnCrash()) { 2470 if (m_command_source_flags.empty()) { 2471 flags |= eHandleCommandFlagStopOnCrash; 2472 } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) { 2473 flags |= eHandleCommandFlagStopOnCrash; 2474 } 2475 } 2476 2477 if (options.m_echo_commands == eLazyBoolCalculate) { 2478 if (m_command_source_flags.empty()) { 2479 // Echo command by default 2480 flags |= eHandleCommandFlagEchoCommand; 2481 } else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) { 2482 flags |= eHandleCommandFlagEchoCommand; 2483 } 2484 } else if (options.m_echo_commands == eLazyBoolYes) { 2485 flags |= eHandleCommandFlagEchoCommand; 2486 } 2487 2488 // We will only ever ask for this flag, if we echo commands in general. 2489 if (options.m_echo_comment_commands == eLazyBoolCalculate) { 2490 if (m_command_source_flags.empty()) { 2491 // Echo comments by default 2492 flags |= eHandleCommandFlagEchoCommentCommand; 2493 } else if (m_command_source_flags.back() & 2494 eHandleCommandFlagEchoCommentCommand) { 2495 flags |= eHandleCommandFlagEchoCommentCommand; 2496 } 2497 } else if (options.m_echo_comment_commands == eLazyBoolYes) { 2498 flags |= eHandleCommandFlagEchoCommentCommand; 2499 } 2500 2501 if (options.m_print_results == eLazyBoolCalculate) { 2502 if (m_command_source_flags.empty()) { 2503 // Print output by default 2504 flags |= eHandleCommandFlagPrintResult; 2505 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) { 2506 flags |= eHandleCommandFlagPrintResult; 2507 } 2508 } else if (options.m_print_results == eLazyBoolYes) { 2509 flags |= eHandleCommandFlagPrintResult; 2510 } 2511 2512 if (options.m_print_errors == eLazyBoolCalculate) { 2513 if (m_command_source_flags.empty()) { 2514 // Print output by default 2515 flags |= eHandleCommandFlagPrintErrors; 2516 } else if (m_command_source_flags.back() & eHandleCommandFlagPrintErrors) { 2517 flags |= eHandleCommandFlagPrintErrors; 2518 } 2519 } else if (options.m_print_errors == eLazyBoolYes) { 2520 flags |= eHandleCommandFlagPrintErrors; 2521 } 2522 2523 if (flags & eHandleCommandFlagPrintResult) { 2524 debugger.GetOutputFile().Printf("Executing commands in '%s'.\n", 2525 cmd_file_path.c_str()); 2526 } 2527 2528 // Used for inheriting the right settings when "command source" might 2529 // have nested "command source" commands 2530 lldb::StreamFileSP empty_stream_sp; 2531 m_command_source_flags.push_back(flags); 2532 IOHandlerSP io_handler_sp(new IOHandlerEditline( 2533 debugger, IOHandler::Type::CommandInterpreter, input_file_sp, 2534 empty_stream_sp, // Pass in an empty stream so we inherit the top 2535 // input reader output stream 2536 empty_stream_sp, // Pass in an empty stream so we inherit the top 2537 // input reader error stream 2538 flags, 2539 nullptr, // Pass in NULL for "editline_name" so no history is saved, 2540 // or written 2541 debugger.GetPrompt(), llvm::StringRef(), 2542 false, // Not multi-line 2543 debugger.GetUseColor(), 0, *this, nullptr)); 2544 const bool old_async_execution = debugger.GetAsyncExecution(); 2545 2546 // Set synchronous execution if we are not stopping on continue 2547 if ((flags & eHandleCommandFlagStopOnContinue) == 0) 2548 debugger.SetAsyncExecution(false); 2549 2550 m_command_source_depth++; 2551 m_command_source_dirs.push_back(cmd_file.CopyByRemovingLastPathComponent()); 2552 2553 debugger.RunIOHandlerSync(io_handler_sp); 2554 if (!m_command_source_flags.empty()) 2555 m_command_source_flags.pop_back(); 2556 2557 m_command_source_dirs.pop_back(); 2558 m_command_source_depth--; 2559 2560 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2561 debugger.SetAsyncExecution(old_async_execution); 2562 } 2563 2564 bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; } 2565 2566 void CommandInterpreter::SetSynchronous(bool value) { 2567 // Asynchronous mode is not supported during reproducer replay. 2568 if (repro::Reproducer::Instance().GetLoader()) 2569 return; 2570 m_synchronous_execution = value; 2571 } 2572 2573 void CommandInterpreter::OutputFormattedHelpText(Stream &strm, 2574 llvm::StringRef prefix, 2575 llvm::StringRef help_text) { 2576 const uint32_t max_columns = m_debugger.GetTerminalWidth(); 2577 2578 size_t line_width_max = max_columns - prefix.size(); 2579 if (line_width_max < 16) 2580 line_width_max = help_text.size() + prefix.size(); 2581 2582 strm.IndentMore(prefix.size()); 2583 bool prefixed_yet = false; 2584 while (!help_text.empty()) { 2585 // Prefix the first line, indent subsequent lines to line up 2586 if (!prefixed_yet) { 2587 strm << prefix; 2588 prefixed_yet = true; 2589 } else 2590 strm.Indent(); 2591 2592 // Never print more than the maximum on one line. 2593 llvm::StringRef this_line = help_text.substr(0, line_width_max); 2594 2595 // Always break on an explicit newline. 2596 std::size_t first_newline = this_line.find_first_of("\n"); 2597 2598 // Don't break on space/tab unless the text is too long to fit on one line. 2599 std::size_t last_space = llvm::StringRef::npos; 2600 if (this_line.size() != help_text.size()) 2601 last_space = this_line.find_last_of(" \t"); 2602 2603 // Break at whichever condition triggered first. 2604 this_line = this_line.substr(0, std::min(first_newline, last_space)); 2605 strm.PutCString(this_line); 2606 strm.EOL(); 2607 2608 // Remove whitespace / newlines after breaking. 2609 help_text = help_text.drop_front(this_line.size()).ltrim(); 2610 } 2611 strm.IndentLess(prefix.size()); 2612 } 2613 2614 void CommandInterpreter::OutputFormattedHelpText(Stream &strm, 2615 llvm::StringRef word_text, 2616 llvm::StringRef separator, 2617 llvm::StringRef help_text, 2618 size_t max_word_len) { 2619 StreamString prefix_stream; 2620 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(), 2621 (int)separator.size(), separator.data()); 2622 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text); 2623 } 2624 2625 void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text, 2626 llvm::StringRef separator, 2627 llvm::StringRef help_text, 2628 uint32_t max_word_len) { 2629 int indent_size = max_word_len + separator.size() + 2; 2630 2631 strm.IndentMore(indent_size); 2632 2633 StreamString text_strm; 2634 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data()); 2635 text_strm << separator << " " << help_text; 2636 2637 const uint32_t max_columns = m_debugger.GetTerminalWidth(); 2638 2639 llvm::StringRef text = text_strm.GetString(); 2640 2641 uint32_t chars_left = max_columns; 2642 2643 auto nextWordLength = [](llvm::StringRef S) { 2644 size_t pos = S.find(' '); 2645 return pos == llvm::StringRef::npos ? S.size() : pos; 2646 }; 2647 2648 while (!text.empty()) { 2649 if (text.front() == '\n' || 2650 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) { 2651 strm.EOL(); 2652 strm.Indent(); 2653 chars_left = max_columns - indent_size; 2654 if (text.front() == '\n') 2655 text = text.drop_front(); 2656 else 2657 text = text.ltrim(' '); 2658 } else { 2659 strm.PutChar(text.front()); 2660 --chars_left; 2661 text = text.drop_front(); 2662 } 2663 } 2664 2665 strm.EOL(); 2666 strm.IndentLess(indent_size); 2667 } 2668 2669 void CommandInterpreter::FindCommandsForApropos( 2670 llvm::StringRef search_word, StringList &commands_found, 2671 StringList &commands_help, CommandObject::CommandMap &command_map) { 2672 CommandObject::CommandMap::const_iterator pos; 2673 2674 for (pos = command_map.begin(); pos != command_map.end(); ++pos) { 2675 llvm::StringRef command_name = pos->first; 2676 CommandObject *cmd_obj = pos->second.get(); 2677 2678 const bool search_short_help = true; 2679 const bool search_long_help = false; 2680 const bool search_syntax = false; 2681 const bool search_options = false; 2682 if (command_name.contains_insensitive(search_word) || 2683 cmd_obj->HelpTextContainsWord(search_word, search_short_help, 2684 search_long_help, search_syntax, 2685 search_options)) { 2686 commands_found.AppendString(cmd_obj->GetCommandName()); 2687 commands_help.AppendString(cmd_obj->GetHelp()); 2688 } 2689 2690 if (cmd_obj->IsMultiwordObject()) { 2691 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand(); 2692 FindCommandsForApropos(search_word, commands_found, commands_help, 2693 cmd_multiword->GetSubcommandDictionary()); 2694 } 2695 } 2696 } 2697 2698 void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word, 2699 StringList &commands_found, 2700 StringList &commands_help, 2701 bool search_builtin_commands, 2702 bool search_user_commands, 2703 bool search_alias_commands) { 2704 CommandObject::CommandMap::const_iterator pos; 2705 2706 if (search_builtin_commands) 2707 FindCommandsForApropos(search_word, commands_found, commands_help, 2708 m_command_dict); 2709 2710 if (search_user_commands) 2711 FindCommandsForApropos(search_word, commands_found, commands_help, 2712 m_user_dict); 2713 2714 if (search_alias_commands) 2715 FindCommandsForApropos(search_word, commands_found, commands_help, 2716 m_alias_dict); 2717 } 2718 2719 ExecutionContext CommandInterpreter::GetExecutionContext() const { 2720 return !m_overriden_exe_contexts.empty() 2721 ? m_overriden_exe_contexts.top() 2722 : m_debugger.GetSelectedExecutionContext(); 2723 } 2724 2725 void CommandInterpreter::OverrideExecutionContext( 2726 const ExecutionContext &override_context) { 2727 m_overriden_exe_contexts.push(override_context); 2728 } 2729 2730 void CommandInterpreter::RestoreExecutionContext() { 2731 if (!m_overriden_exe_contexts.empty()) 2732 m_overriden_exe_contexts.pop(); 2733 } 2734 2735 void CommandInterpreter::GetProcessOutput() { 2736 if (ProcessSP process_sp = GetExecutionContext().GetProcessSP()) 2737 m_debugger.FlushProcessOutput(*process_sp, /*flush_stdout*/ true, 2738 /*flush_stderr*/ true); 2739 } 2740 2741 void CommandInterpreter::StartHandlingCommand() { 2742 auto idle_state = CommandHandlingState::eIdle; 2743 if (m_command_state.compare_exchange_strong( 2744 idle_state, CommandHandlingState::eInProgress)) 2745 lldbassert(m_iohandler_nesting_level == 0); 2746 else 2747 lldbassert(m_iohandler_nesting_level > 0); 2748 ++m_iohandler_nesting_level; 2749 } 2750 2751 void CommandInterpreter::FinishHandlingCommand() { 2752 lldbassert(m_iohandler_nesting_level > 0); 2753 if (--m_iohandler_nesting_level == 0) { 2754 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle); 2755 lldbassert(prev_state != CommandHandlingState::eIdle); 2756 } 2757 } 2758 2759 bool CommandInterpreter::InterruptCommand() { 2760 auto in_progress = CommandHandlingState::eInProgress; 2761 return m_command_state.compare_exchange_strong( 2762 in_progress, CommandHandlingState::eInterrupted); 2763 } 2764 2765 bool CommandInterpreter::WasInterrupted() const { 2766 bool was_interrupted = 2767 (m_command_state == CommandHandlingState::eInterrupted); 2768 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0); 2769 return was_interrupted; 2770 } 2771 2772 void CommandInterpreter::PrintCommandOutput(Stream &stream, 2773 llvm::StringRef str) { 2774 // Split the output into lines and poll for interrupt requests 2775 const char *data = str.data(); 2776 size_t size = str.size(); 2777 while (size > 0 && !WasInterrupted()) { 2778 size_t chunk_size = 0; 2779 for (; chunk_size < size; ++chunk_size) { 2780 lldbassert(data[chunk_size] != '\0'); 2781 if (data[chunk_size] == '\n') { 2782 ++chunk_size; 2783 break; 2784 } 2785 } 2786 chunk_size = stream.Write(data, chunk_size); 2787 lldbassert(size >= chunk_size); 2788 data += chunk_size; 2789 size -= chunk_size; 2790 } 2791 if (size > 0) { 2792 stream.Printf("\n... Interrupted.\n"); 2793 } 2794 } 2795 2796 bool CommandInterpreter::EchoCommandNonInteractive( 2797 llvm::StringRef line, const Flags &io_handler_flags) const { 2798 if (!io_handler_flags.Test(eHandleCommandFlagEchoCommand)) 2799 return false; 2800 2801 llvm::StringRef command = line.trim(); 2802 if (command.empty()) 2803 return true; 2804 2805 if (command.front() == m_comment_char) 2806 return io_handler_flags.Test(eHandleCommandFlagEchoCommentCommand); 2807 2808 return true; 2809 } 2810 2811 void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler, 2812 std::string &line) { 2813 // If we were interrupted, bail out... 2814 if (WasInterrupted()) 2815 return; 2816 2817 const bool is_interactive = io_handler.GetIsInteractive(); 2818 if (!is_interactive) { 2819 // When we are not interactive, don't execute blank lines. This will happen 2820 // sourcing a commands file. We don't want blank lines to repeat the 2821 // previous command and cause any errors to occur (like redefining an 2822 // alias, get an error and stop parsing the commands file). 2823 if (line.empty()) 2824 return; 2825 2826 // When using a non-interactive file handle (like when sourcing commands 2827 // from a file) we need to echo the command out so we don't just see the 2828 // command output and no command... 2829 if (EchoCommandNonInteractive(line, io_handler.GetFlags())) 2830 io_handler.GetOutputStreamFileSP()->Printf( 2831 "%s%s\n", io_handler.GetPrompt(), line.c_str()); 2832 } 2833 2834 StartHandlingCommand(); 2835 2836 OverrideExecutionContext(m_debugger.GetSelectedExecutionContext()); 2837 auto finalize = llvm::make_scope_exit([this]() { 2838 RestoreExecutionContext(); 2839 }); 2840 2841 lldb_private::CommandReturnObject result(m_debugger.GetUseColor()); 2842 HandleCommand(line.c_str(), eLazyBoolCalculate, result); 2843 2844 // Now emit the command output text from the command we just executed 2845 if ((result.Succeeded() && 2846 io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) || 2847 io_handler.GetFlags().Test(eHandleCommandFlagPrintErrors)) { 2848 // Display any STDOUT/STDERR _prior_ to emitting the command result text 2849 GetProcessOutput(); 2850 2851 if (!result.GetImmediateOutputStream()) { 2852 llvm::StringRef output = result.GetOutputData(); 2853 PrintCommandOutput(*io_handler.GetOutputStreamFileSP(), output); 2854 } 2855 2856 // Now emit the command error text from the command we just executed 2857 if (!result.GetImmediateErrorStream()) { 2858 llvm::StringRef error = result.GetErrorData(); 2859 PrintCommandOutput(*io_handler.GetErrorStreamFileSP(), error); 2860 } 2861 } 2862 2863 FinishHandlingCommand(); 2864 2865 switch (result.GetStatus()) { 2866 case eReturnStatusInvalid: 2867 case eReturnStatusSuccessFinishNoResult: 2868 case eReturnStatusSuccessFinishResult: 2869 case eReturnStatusStarted: 2870 break; 2871 2872 case eReturnStatusSuccessContinuingNoResult: 2873 case eReturnStatusSuccessContinuingResult: 2874 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue)) 2875 io_handler.SetIsDone(true); 2876 break; 2877 2878 case eReturnStatusFailed: 2879 m_result.IncrementNumberOfErrors(); 2880 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError)) { 2881 m_result.SetResult(lldb::eCommandInterpreterResultCommandError); 2882 io_handler.SetIsDone(true); 2883 } 2884 break; 2885 2886 case eReturnStatusQuit: 2887 m_result.SetResult(lldb::eCommandInterpreterResultQuitRequested); 2888 io_handler.SetIsDone(true); 2889 break; 2890 } 2891 2892 // Finally, if we're going to stop on crash, check that here: 2893 if (m_result.IsResult(lldb::eCommandInterpreterResultSuccess) && 2894 result.GetDidChangeProcessState() && 2895 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash) && 2896 DidProcessStopAbnormally()) { 2897 io_handler.SetIsDone(true); 2898 m_result.SetResult(lldb::eCommandInterpreterResultInferiorCrash); 2899 } 2900 } 2901 2902 bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) { 2903 ExecutionContext exe_ctx(GetExecutionContext()); 2904 Process *process = exe_ctx.GetProcessPtr(); 2905 2906 if (InterruptCommand()) 2907 return true; 2908 2909 if (process) { 2910 StateType state = process->GetState(); 2911 if (StateIsRunningState(state)) { 2912 process->Halt(); 2913 return true; // Don't do any updating when we are running 2914 } 2915 } 2916 2917 ScriptInterpreter *script_interpreter = 2918 m_debugger.GetScriptInterpreter(false); 2919 if (script_interpreter) { 2920 if (script_interpreter->Interrupt()) 2921 return true; 2922 } 2923 return false; 2924 } 2925 2926 bool CommandInterpreter::SaveTranscript( 2927 CommandReturnObject &result, llvm::Optional<std::string> output_file) { 2928 if (output_file == llvm::None || output_file->empty()) { 2929 std::string now = llvm::to_string(std::chrono::system_clock::now()); 2930 std::replace(now.begin(), now.end(), ' ', '_'); 2931 const std::string file_name = "lldb_session_" + now + ".log"; 2932 2933 FileSpec save_location = GetSaveSessionDirectory(); 2934 2935 if (!save_location) 2936 save_location = HostInfo::GetGlobalTempDir(); 2937 2938 FileSystem::Instance().Resolve(save_location); 2939 save_location.AppendPathComponent(file_name); 2940 output_file = save_location.GetPath(); 2941 } 2942 2943 auto error_out = [&](llvm::StringRef error_message, std::string description) { 2944 LLDB_LOG(GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS), "{0} ({1}:{2})", 2945 error_message, output_file, description); 2946 result.AppendErrorWithFormatv( 2947 "Failed to save session's transcripts to {0}!", *output_file); 2948 return false; 2949 }; 2950 2951 File::OpenOptions flags = File::eOpenOptionWriteOnly | 2952 File::eOpenOptionCanCreate | 2953 File::eOpenOptionTruncate; 2954 2955 auto opened_file = FileSystem::Instance().Open(FileSpec(*output_file), flags); 2956 2957 if (!opened_file) 2958 return error_out("Unable to create file", 2959 llvm::toString(opened_file.takeError())); 2960 2961 FileUP file = std::move(opened_file.get()); 2962 2963 size_t byte_size = m_transcript_stream.GetSize(); 2964 2965 Status error = file->Write(m_transcript_stream.GetData(), byte_size); 2966 2967 if (error.Fail() || byte_size != m_transcript_stream.GetSize()) 2968 return error_out("Unable to write to destination file", 2969 "Bytes written do not match transcript size."); 2970 2971 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2972 result.AppendMessageWithFormat("Session's transcripts saved to %s\n", 2973 output_file->c_str()); 2974 2975 return true; 2976 } 2977 2978 FileSpec CommandInterpreter::GetCurrentSourceDir() { 2979 if (m_command_source_dirs.empty()) 2980 return {}; 2981 return m_command_source_dirs.back(); 2982 } 2983 2984 void CommandInterpreter::GetLLDBCommandsFromIOHandler( 2985 const char *prompt, IOHandlerDelegate &delegate, void *baton) { 2986 Debugger &debugger = GetDebugger(); 2987 IOHandlerSP io_handler_sp( 2988 new IOHandlerEditline(debugger, IOHandler::Type::CommandList, 2989 "lldb", // Name of input reader for history 2990 llvm::StringRef(prompt), // Prompt 2991 llvm::StringRef(), // Continuation prompt 2992 true, // Get multiple lines 2993 debugger.GetUseColor(), 2994 0, // Don't show line numbers 2995 delegate, // IOHandlerDelegate 2996 nullptr)); // FileShadowCollector 2997 2998 if (io_handler_sp) { 2999 io_handler_sp->SetUserData(baton); 3000 debugger.RunIOHandlerAsync(io_handler_sp); 3001 } 3002 } 3003 3004 void CommandInterpreter::GetPythonCommandsFromIOHandler( 3005 const char *prompt, IOHandlerDelegate &delegate, void *baton) { 3006 Debugger &debugger = GetDebugger(); 3007 IOHandlerSP io_handler_sp( 3008 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode, 3009 "lldb-python", // Name of input reader for history 3010 llvm::StringRef(prompt), // Prompt 3011 llvm::StringRef(), // Continuation prompt 3012 true, // Get multiple lines 3013 debugger.GetUseColor(), 3014 0, // Don't show line numbers 3015 delegate, // IOHandlerDelegate 3016 nullptr)); // FileShadowCollector 3017 3018 if (io_handler_sp) { 3019 io_handler_sp->SetUserData(baton); 3020 debugger.RunIOHandlerAsync(io_handler_sp); 3021 } 3022 } 3023 3024 bool CommandInterpreter::IsActive() { 3025 return m_debugger.IsTopIOHandler(m_command_io_handler_sp); 3026 } 3027 3028 lldb::IOHandlerSP 3029 CommandInterpreter::GetIOHandler(bool force_create, 3030 CommandInterpreterRunOptions *options) { 3031 // Always re-create the IOHandlerEditline in case the input changed. The old 3032 // instance might have had a non-interactive input and now it does or vice 3033 // versa. 3034 if (force_create || !m_command_io_handler_sp) { 3035 // Always re-create the IOHandlerEditline in case the input changed. The 3036 // old instance might have had a non-interactive input and now it does or 3037 // vice versa. 3038 uint32_t flags = 0; 3039 3040 if (options) { 3041 if (options->m_stop_on_continue == eLazyBoolYes) 3042 flags |= eHandleCommandFlagStopOnContinue; 3043 if (options->m_stop_on_error == eLazyBoolYes) 3044 flags |= eHandleCommandFlagStopOnError; 3045 if (options->m_stop_on_crash == eLazyBoolYes) 3046 flags |= eHandleCommandFlagStopOnCrash; 3047 if (options->m_echo_commands != eLazyBoolNo) 3048 flags |= eHandleCommandFlagEchoCommand; 3049 if (options->m_echo_comment_commands != eLazyBoolNo) 3050 flags |= eHandleCommandFlagEchoCommentCommand; 3051 if (options->m_print_results != eLazyBoolNo) 3052 flags |= eHandleCommandFlagPrintResult; 3053 if (options->m_print_errors != eLazyBoolNo) 3054 flags |= eHandleCommandFlagPrintErrors; 3055 } else { 3056 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult | 3057 eHandleCommandFlagPrintErrors; 3058 } 3059 3060 m_command_io_handler_sp = std::make_shared<IOHandlerEditline>( 3061 m_debugger, IOHandler::Type::CommandInterpreter, 3062 m_debugger.GetInputFileSP(), m_debugger.GetOutputStreamSP(), 3063 m_debugger.GetErrorStreamSP(), flags, "lldb", m_debugger.GetPrompt(), 3064 llvm::StringRef(), // Continuation prompt 3065 false, // Don't enable multiple line input, just single line commands 3066 m_debugger.GetUseColor(), 3067 0, // Don't show line numbers 3068 *this, // IOHandlerDelegate 3069 GetDebugger().GetInputRecorder()); 3070 } 3071 return m_command_io_handler_sp; 3072 } 3073 3074 CommandInterpreterRunResult CommandInterpreter::RunCommandInterpreter( 3075 CommandInterpreterRunOptions &options) { 3076 // Always re-create the command interpreter when we run it in case any file 3077 // handles have changed. 3078 bool force_create = true; 3079 m_debugger.RunIOHandlerAsync(GetIOHandler(force_create, &options)); 3080 m_result = CommandInterpreterRunResult(); 3081 3082 if (options.GetAutoHandleEvents()) 3083 m_debugger.StartEventHandlerThread(); 3084 3085 if (options.GetSpawnThread()) { 3086 m_debugger.StartIOHandlerThread(); 3087 } else { 3088 m_debugger.RunIOHandlers(); 3089 3090 if (options.GetAutoHandleEvents()) 3091 m_debugger.StopEventHandlerThread(); 3092 } 3093 3094 return m_result; 3095 } 3096 3097 CommandObject * 3098 CommandInterpreter::ResolveCommandImpl(std::string &command_line, 3099 CommandReturnObject &result) { 3100 std::string scratch_command(command_line); // working copy so we don't modify 3101 // command_line unless we succeed 3102 CommandObject *cmd_obj = nullptr; 3103 StreamString revised_command_line; 3104 bool wants_raw_input = false; 3105 std::string next_word; 3106 StringList matches; 3107 bool done = false; 3108 while (!done) { 3109 char quote_char = '\0'; 3110 std::string suffix; 3111 ExtractCommand(scratch_command, next_word, suffix, quote_char); 3112 if (cmd_obj == nullptr) { 3113 std::string full_name; 3114 bool is_alias = GetAliasFullName(next_word, full_name); 3115 cmd_obj = GetCommandObject(next_word, &matches); 3116 bool is_real_command = 3117 (!is_alias) || (cmd_obj != nullptr && !cmd_obj->IsAlias()); 3118 if (!is_real_command) { 3119 matches.Clear(); 3120 std::string alias_result; 3121 cmd_obj = 3122 BuildAliasResult(full_name, scratch_command, alias_result, result); 3123 revised_command_line.Printf("%s", alias_result.c_str()); 3124 if (cmd_obj) { 3125 wants_raw_input = cmd_obj->WantsRawCommandString(); 3126 } 3127 } else { 3128 if (cmd_obj) { 3129 llvm::StringRef cmd_name = cmd_obj->GetCommandName(); 3130 revised_command_line.Printf("%s", cmd_name.str().c_str()); 3131 wants_raw_input = cmd_obj->WantsRawCommandString(); 3132 } else { 3133 revised_command_line.Printf("%s", next_word.c_str()); 3134 } 3135 } 3136 } else { 3137 if (cmd_obj->IsMultiwordObject()) { 3138 CommandObject *sub_cmd_obj = 3139 cmd_obj->GetSubcommandObject(next_word.c_str()); 3140 if (sub_cmd_obj) { 3141 // The subcommand's name includes the parent command's name, so 3142 // restart rather than append to the revised_command_line. 3143 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName(); 3144 revised_command_line.Clear(); 3145 revised_command_line.Printf("%s", sub_cmd_name.str().c_str()); 3146 cmd_obj = sub_cmd_obj; 3147 wants_raw_input = cmd_obj->WantsRawCommandString(); 3148 } else { 3149 if (quote_char) 3150 revised_command_line.Printf(" %c%s%s%c", quote_char, 3151 next_word.c_str(), suffix.c_str(), 3152 quote_char); 3153 else 3154 revised_command_line.Printf(" %s%s", next_word.c_str(), 3155 suffix.c_str()); 3156 done = true; 3157 } 3158 } else { 3159 if (quote_char) 3160 revised_command_line.Printf(" %c%s%s%c", quote_char, 3161 next_word.c_str(), suffix.c_str(), 3162 quote_char); 3163 else 3164 revised_command_line.Printf(" %s%s", next_word.c_str(), 3165 suffix.c_str()); 3166 done = true; 3167 } 3168 } 3169 3170 if (cmd_obj == nullptr) { 3171 const size_t num_matches = matches.GetSize(); 3172 if (matches.GetSize() > 1) { 3173 StreamString error_msg; 3174 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n", 3175 next_word.c_str()); 3176 3177 for (uint32_t i = 0; i < num_matches; ++i) { 3178 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i)); 3179 } 3180 result.AppendRawError(error_msg.GetString()); 3181 } else { 3182 // We didn't have only one match, otherwise we wouldn't get here. 3183 lldbassert(num_matches == 0); 3184 result.AppendErrorWithFormat("'%s' is not a valid command.\n", 3185 next_word.c_str()); 3186 } 3187 return nullptr; 3188 } 3189 3190 if (cmd_obj->IsMultiwordObject()) { 3191 if (!suffix.empty()) { 3192 result.AppendErrorWithFormat( 3193 "command '%s' did not recognize '%s%s%s' as valid (subcommand " 3194 "might be invalid).\n", 3195 cmd_obj->GetCommandName().str().c_str(), 3196 next_word.empty() ? "" : next_word.c_str(), 3197 next_word.empty() ? " -- " : " ", suffix.c_str()); 3198 return nullptr; 3199 } 3200 } else { 3201 // If we found a normal command, we are done 3202 done = true; 3203 if (!suffix.empty()) { 3204 switch (suffix[0]) { 3205 case '/': 3206 // GDB format suffixes 3207 { 3208 Options *command_options = cmd_obj->GetOptions(); 3209 if (command_options && 3210 command_options->SupportsLongOption("gdb-format")) { 3211 std::string gdb_format_option("--gdb-format="); 3212 gdb_format_option += (suffix.c_str() + 1); 3213 3214 std::string cmd = std::string(revised_command_line.GetString()); 3215 size_t arg_terminator_idx = FindArgumentTerminator(cmd); 3216 if (arg_terminator_idx != std::string::npos) { 3217 // Insert the gdb format option before the "--" that terminates 3218 // options 3219 gdb_format_option.append(1, ' '); 3220 cmd.insert(arg_terminator_idx, gdb_format_option); 3221 revised_command_line.Clear(); 3222 revised_command_line.PutCString(cmd); 3223 } else 3224 revised_command_line.Printf(" %s", gdb_format_option.c_str()); 3225 3226 if (wants_raw_input && 3227 FindArgumentTerminator(cmd) == std::string::npos) 3228 revised_command_line.PutCString(" --"); 3229 } else { 3230 result.AppendErrorWithFormat( 3231 "the '%s' command doesn't support the --gdb-format option\n", 3232 cmd_obj->GetCommandName().str().c_str()); 3233 return nullptr; 3234 } 3235 } 3236 break; 3237 3238 default: 3239 result.AppendErrorWithFormat( 3240 "unknown command shorthand suffix: '%s'\n", suffix.c_str()); 3241 return nullptr; 3242 } 3243 } 3244 } 3245 if (scratch_command.empty()) 3246 done = true; 3247 } 3248 3249 if (!scratch_command.empty()) 3250 revised_command_line.Printf(" %s", scratch_command.c_str()); 3251 3252 if (cmd_obj != nullptr) 3253 command_line = std::string(revised_command_line.GetString()); 3254 3255 return cmd_obj; 3256 } 3257