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