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