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