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