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