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