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