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