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