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