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