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