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