1 //===-- CommandInterpreter.h ------------------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #ifndef LLDB_INTERPRETER_COMMANDINTERPRETER_H 10 #define LLDB_INTERPRETER_COMMANDINTERPRETER_H 11 12 #include "lldb/Core/Debugger.h" 13 #include "lldb/Core/IOHandler.h" 14 #include "lldb/Interpreter/CommandAlias.h" 15 #include "lldb/Interpreter/CommandHistory.h" 16 #include "lldb/Interpreter/CommandObject.h" 17 #include "lldb/Interpreter/ScriptInterpreter.h" 18 #include "lldb/Utility/Args.h" 19 #include "lldb/Utility/Broadcaster.h" 20 #include "lldb/Utility/CompletionRequest.h" 21 #include "lldb/Utility/Event.h" 22 #include "lldb/Utility/Log.h" 23 #include "lldb/Utility/StreamString.h" 24 #include "lldb/Utility/StringList.h" 25 #include "lldb/Utility/StructuredData.h" 26 #include "lldb/lldb-forward.h" 27 #include "lldb/lldb-private.h" 28 29 #include <mutex> 30 #include <optional> 31 #include <stack> 32 #include <unordered_map> 33 34 namespace lldb_private { 35 class CommandInterpreter; 36 37 class CommandInterpreterRunResult { 38 public: 39 CommandInterpreterRunResult() = default; 40 GetNumErrors()41 uint32_t GetNumErrors() const { return m_num_errors; } 42 GetResult()43 lldb::CommandInterpreterResult GetResult() const { return m_result; } 44 IsResult(lldb::CommandInterpreterResult result)45 bool IsResult(lldb::CommandInterpreterResult result) { 46 return m_result == result; 47 } 48 49 protected: 50 friend CommandInterpreter; 51 IncrementNumberOfErrors()52 void IncrementNumberOfErrors() { m_num_errors++; } 53 SetResult(lldb::CommandInterpreterResult result)54 void SetResult(lldb::CommandInterpreterResult result) { m_result = result; } 55 56 private: 57 int m_num_errors = 0; 58 lldb::CommandInterpreterResult m_result = 59 lldb::eCommandInterpreterResultSuccess; 60 }; 61 62 class CommandInterpreterRunOptions { 63 public: 64 /// Construct a CommandInterpreterRunOptions object. This class is used to 65 /// control all the instances where we run multiple commands, e.g. 66 /// HandleCommands, HandleCommandsFromFile, RunCommandInterpreter. 67 /// 68 /// The meanings of the options in this object are: 69 /// 70 /// \param[in] stop_on_continue 71 /// If \b true, execution will end on the first command that causes the 72 /// process in the execution context to continue. If \b false, we won't 73 /// check the execution status. 74 /// \param[in] stop_on_error 75 /// If \b true, execution will end on the first command that causes an 76 /// error. 77 /// \param[in] stop_on_crash 78 /// If \b true, when a command causes the target to run, and the end of the 79 /// run is a signal or exception, stop executing the commands. 80 /// \param[in] echo_commands 81 /// If \b true, echo the command before executing it. If \b false, execute 82 /// silently. 83 /// \param[in] echo_comments 84 /// If \b true, echo command even if it is a pure comment line. If 85 /// \b false, print no ouput in this case. This setting has an effect only 86 /// if echo_commands is \b true. 87 /// \param[in] print_results 88 /// If \b true and the command succeeds, print the results of the command 89 /// after executing it. If \b false, execute silently. 90 /// \param[in] print_errors 91 /// If \b true and the command fails, print the results of the command 92 /// after executing it. If \b false, execute silently. 93 /// \param[in] add_to_history 94 /// If \b true add the commands to the command history. If \b false, don't 95 /// add them. 96 /// \param[in] handle_repeats 97 /// If \b true then treat empty lines as repeat commands even if the 98 /// interpreter is non-interactive. CommandInterpreterRunOptions(LazyBool stop_on_continue,LazyBool stop_on_error,LazyBool stop_on_crash,LazyBool echo_commands,LazyBool echo_comments,LazyBool print_results,LazyBool print_errors,LazyBool add_to_history,LazyBool handle_repeats)99 CommandInterpreterRunOptions(LazyBool stop_on_continue, 100 LazyBool stop_on_error, LazyBool stop_on_crash, 101 LazyBool echo_commands, LazyBool echo_comments, 102 LazyBool print_results, LazyBool print_errors, 103 LazyBool add_to_history, 104 LazyBool handle_repeats) 105 : m_stop_on_continue(stop_on_continue), m_stop_on_error(stop_on_error), 106 m_stop_on_crash(stop_on_crash), m_echo_commands(echo_commands), 107 m_echo_comment_commands(echo_comments), m_print_results(print_results), 108 m_print_errors(print_errors), m_add_to_history(add_to_history), 109 m_allow_repeats(handle_repeats) {} 110 111 CommandInterpreterRunOptions() = default; 112 SetSilent(bool silent)113 void SetSilent(bool silent) { 114 LazyBool value = silent ? eLazyBoolNo : eLazyBoolYes; 115 116 m_print_results = value; 117 m_print_errors = value; 118 m_echo_commands = value; 119 m_echo_comment_commands = value; 120 m_add_to_history = value; 121 } 122 // These return the default behaviors if the behavior is not 123 // eLazyBoolCalculate. But I've also left the ivars public since for 124 // different ways of running the interpreter you might want to force 125 // different defaults... In that case, just grab the LazyBool ivars directly 126 // and do what you want with eLazyBoolCalculate. GetStopOnContinue()127 bool GetStopOnContinue() const { return DefaultToNo(m_stop_on_continue); } 128 SetStopOnContinue(bool stop_on_continue)129 void SetStopOnContinue(bool stop_on_continue) { 130 m_stop_on_continue = stop_on_continue ? eLazyBoolYes : eLazyBoolNo; 131 } 132 GetStopOnError()133 bool GetStopOnError() const { return DefaultToNo(m_stop_on_error); } 134 SetStopOnError(bool stop_on_error)135 void SetStopOnError(bool stop_on_error) { 136 m_stop_on_error = stop_on_error ? eLazyBoolYes : eLazyBoolNo; 137 } 138 GetStopOnCrash()139 bool GetStopOnCrash() const { return DefaultToNo(m_stop_on_crash); } 140 SetStopOnCrash(bool stop_on_crash)141 void SetStopOnCrash(bool stop_on_crash) { 142 m_stop_on_crash = stop_on_crash ? eLazyBoolYes : eLazyBoolNo; 143 } 144 GetEchoCommands()145 bool GetEchoCommands() const { return DefaultToYes(m_echo_commands); } 146 SetEchoCommands(bool echo_commands)147 void SetEchoCommands(bool echo_commands) { 148 m_echo_commands = echo_commands ? eLazyBoolYes : eLazyBoolNo; 149 } 150 GetEchoCommentCommands()151 bool GetEchoCommentCommands() const { 152 return DefaultToYes(m_echo_comment_commands); 153 } 154 SetEchoCommentCommands(bool echo_comments)155 void SetEchoCommentCommands(bool echo_comments) { 156 m_echo_comment_commands = echo_comments ? eLazyBoolYes : eLazyBoolNo; 157 } 158 GetPrintResults()159 bool GetPrintResults() const { return DefaultToYes(m_print_results); } 160 SetPrintResults(bool print_results)161 void SetPrintResults(bool print_results) { 162 m_print_results = print_results ? eLazyBoolYes : eLazyBoolNo; 163 } 164 GetPrintErrors()165 bool GetPrintErrors() const { return DefaultToYes(m_print_errors); } 166 SetPrintErrors(bool print_errors)167 void SetPrintErrors(bool print_errors) { 168 m_print_errors = print_errors ? eLazyBoolYes : eLazyBoolNo; 169 } 170 GetAddToHistory()171 bool GetAddToHistory() const { return DefaultToYes(m_add_to_history); } 172 SetAddToHistory(bool add_to_history)173 void SetAddToHistory(bool add_to_history) { 174 m_add_to_history = add_to_history ? eLazyBoolYes : eLazyBoolNo; 175 } 176 GetAutoHandleEvents()177 bool GetAutoHandleEvents() const { 178 return DefaultToYes(m_auto_handle_events); 179 } 180 SetAutoHandleEvents(bool auto_handle_events)181 void SetAutoHandleEvents(bool auto_handle_events) { 182 m_auto_handle_events = auto_handle_events ? eLazyBoolYes : eLazyBoolNo; 183 } 184 GetSpawnThread()185 bool GetSpawnThread() const { return DefaultToNo(m_spawn_thread); } 186 SetSpawnThread(bool spawn_thread)187 void SetSpawnThread(bool spawn_thread) { 188 m_spawn_thread = spawn_thread ? eLazyBoolYes : eLazyBoolNo; 189 } 190 GetAllowRepeats()191 bool GetAllowRepeats() const { return DefaultToNo(m_allow_repeats); } 192 SetAllowRepeats(bool allow_repeats)193 void SetAllowRepeats(bool allow_repeats) { 194 m_allow_repeats = allow_repeats ? eLazyBoolYes : eLazyBoolNo; 195 } 196 197 LazyBool m_stop_on_continue = eLazyBoolCalculate; 198 LazyBool m_stop_on_error = eLazyBoolCalculate; 199 LazyBool m_stop_on_crash = eLazyBoolCalculate; 200 LazyBool m_echo_commands = eLazyBoolCalculate; 201 LazyBool m_echo_comment_commands = eLazyBoolCalculate; 202 LazyBool m_print_results = eLazyBoolCalculate; 203 LazyBool m_print_errors = eLazyBoolCalculate; 204 LazyBool m_add_to_history = eLazyBoolCalculate; 205 LazyBool m_auto_handle_events; 206 LazyBool m_spawn_thread; 207 LazyBool m_allow_repeats = eLazyBoolCalculate; 208 209 private: DefaultToYes(LazyBool flag)210 static bool DefaultToYes(LazyBool flag) { 211 switch (flag) { 212 case eLazyBoolNo: 213 return false; 214 default: 215 return true; 216 } 217 } 218 DefaultToNo(LazyBool flag)219 static bool DefaultToNo(LazyBool flag) { 220 switch (flag) { 221 case eLazyBoolYes: 222 return true; 223 default: 224 return false; 225 } 226 } 227 }; 228 229 class CommandInterpreter : public Broadcaster, 230 public Properties, 231 public IOHandlerDelegate { 232 public: 233 enum { 234 eBroadcastBitThreadShouldExit = (1 << 0), 235 eBroadcastBitResetPrompt = (1 << 1), 236 eBroadcastBitQuitCommandReceived = (1 << 2), // User entered quit 237 eBroadcastBitAsynchronousOutputData = (1 << 3), 238 eBroadcastBitAsynchronousErrorData = (1 << 4) 239 }; 240 241 /// Tristate boolean to manage children omission warnings. 242 enum ChildrenOmissionWarningStatus { 243 eNoOmission = 0, ///< No children were omitted. 244 eUnwarnedOmission = 1, ///< Children omitted, and not yet notified. 245 eWarnedOmission = 2 ///< Children omitted and notified. 246 }; 247 248 enum CommandTypes { 249 eCommandTypesBuiltin = 0x0001, //< native commands such as "frame" 250 eCommandTypesUserDef = 0x0002, //< scripted commands 251 eCommandTypesUserMW = 0x0004, //< multiword commands (command containers) 252 eCommandTypesAliases = 0x0008, //< aliases such as "po" 253 eCommandTypesHidden = 0x0010, //< commands prefixed with an underscore 254 eCommandTypesAllThem = 0xFFFF //< all commands 255 }; 256 257 // The CommandAlias and CommandInterpreter both have a hand in 258 // substituting for alias commands. They work by writing special tokens 259 // in the template form of the Alias command, and then detecting them when the 260 // command is executed. These are the special tokens: 261 static const char *g_no_argument; 262 static const char *g_need_argument; 263 static const char *g_argument; 264 265 CommandInterpreter(Debugger &debugger, bool synchronous_execution); 266 267 ~CommandInterpreter() override = default; 268 269 // These two functions fill out the Broadcaster interface: 270 271 static llvm::StringRef GetStaticBroadcasterClass(); 272 GetBroadcasterClass()273 llvm::StringRef GetBroadcasterClass() const override { 274 return GetStaticBroadcasterClass(); 275 } 276 277 void SourceInitFileCwd(CommandReturnObject &result); 278 void SourceInitFileHome(CommandReturnObject &result, bool is_repl); 279 void SourceInitFileGlobal(CommandReturnObject &result); 280 281 bool AddCommand(llvm::StringRef name, const lldb::CommandObjectSP &cmd_sp, 282 bool can_replace); 283 284 Status AddUserCommand(llvm::StringRef name, 285 const lldb::CommandObjectSP &cmd_sp, bool can_replace); 286 287 lldb::CommandObjectSP GetCommandSPExact(llvm::StringRef cmd, 288 bool include_aliases = false) const; 289 290 CommandObject *GetCommandObject(llvm::StringRef cmd, 291 StringList *matches = nullptr, 292 StringList *descriptions = nullptr) const; 293 294 CommandObject *GetUserCommandObject(llvm::StringRef cmd, 295 StringList *matches = nullptr, 296 StringList *descriptions = nullptr) const; 297 298 /// Determine whether a root level, built-in command with this name exists. 299 bool CommandExists(llvm::StringRef cmd) const; 300 301 /// Determine whether an alias command with this name exists 302 bool AliasExists(llvm::StringRef cmd) const; 303 304 /// Determine whether a root-level user command with this name exists. 305 bool UserCommandExists(llvm::StringRef cmd) const; 306 307 /// Determine whether a root-level user multiword command with this name 308 /// exists. 309 bool UserMultiwordCommandExists(llvm::StringRef cmd) const; 310 311 /// Look up the command pointed to by path encoded in the arguments of 312 /// the incoming command object. If all the path components exist 313 /// and are all actual commands - not aliases, and the leaf command is a 314 /// multiword command, return the command. Otherwise return nullptr, and put 315 /// a useful diagnostic in the Status object. 316 /// 317 /// \param[in] path 318 /// An Args object holding the path in its arguments 319 /// \param[in] leaf_is_command 320 /// If true, return the container of the leaf name rather than looking up 321 /// the whole path as a leaf command. The leaf needn't exist in this case. 322 /// \param[in,out] result 323 /// If the path is not found, this error shows where we got off track. 324 /// \return 325 /// If found, a pointer to the CommandObjectMultiword pointed to by path, 326 /// or to the container of the leaf element is is_leaf_command. 327 /// Returns nullptr under two circumstances: 328 /// 1) The command in not found (check error.Fail) 329 /// 2) is_leaf is true and the path has only a leaf. We don't have a 330 /// dummy "contains everything MWC, so we return null here, but 331 /// in this case error.Success is true. 332 333 CommandObjectMultiword *VerifyUserMultiwordCmdPath(Args &path, 334 bool leaf_is_command, 335 Status &result); 336 337 CommandAlias *AddAlias(llvm::StringRef alias_name, 338 lldb::CommandObjectSP &command_obj_sp, 339 llvm::StringRef args_string = llvm::StringRef()); 340 341 /// Remove a command if it is removable (python or regex command). If \b force 342 /// is provided, the command is removed regardless of its removable status. 343 bool RemoveCommand(llvm::StringRef cmd, bool force = false); 344 345 bool RemoveAlias(llvm::StringRef alias_name); 346 347 bool GetAliasFullName(llvm::StringRef cmd, std::string &full_name) const; 348 349 bool RemoveUserMultiword(llvm::StringRef multiword_name); 350 351 // Do we want to allow top-level user multiword commands to be deleted? RemoveAllUserMultiword()352 void RemoveAllUserMultiword() { m_user_mw_dict.clear(); } 353 354 bool RemoveUser(llvm::StringRef alias_name); 355 RemoveAllUser()356 void RemoveAllUser() { m_user_dict.clear(); } 357 358 const CommandAlias *GetAlias(llvm::StringRef alias_name) const; 359 360 CommandObject *BuildAliasResult(llvm::StringRef alias_name, 361 std::string &raw_input_string, 362 std::string &alias_result, 363 CommandReturnObject &result); 364 365 bool HandleCommand(const char *command_line, LazyBool add_to_history, 366 const ExecutionContext &override_context, 367 CommandReturnObject &result); 368 369 bool HandleCommand(const char *command_line, LazyBool add_to_history, 370 CommandReturnObject &result, 371 bool force_repeat_command = false); 372 373 bool InterruptCommand(); 374 375 /// Execute a list of commands in sequence. 376 /// 377 /// \param[in] commands 378 /// The list of commands to execute. 379 /// \param[in,out] context 380 /// The execution context in which to run the commands. 381 /// \param[in] options 382 /// This object holds the options used to control when to stop, whether to 383 /// execute commands, 384 /// etc. 385 /// \param[out] result 386 /// This is marked as succeeding with no output if all commands execute 387 /// safely, 388 /// and failed with some explanation if we aborted executing the commands 389 /// at some point. 390 void HandleCommands(const StringList &commands, 391 const ExecutionContext &context, 392 const CommandInterpreterRunOptions &options, 393 CommandReturnObject &result); 394 395 void HandleCommands(const StringList &commands, 396 const CommandInterpreterRunOptions &options, 397 CommandReturnObject &result); 398 399 /// Execute a list of commands from a file. 400 /// 401 /// \param[in] file 402 /// The file from which to read in commands. 403 /// \param[in,out] context 404 /// The execution context in which to run the commands. 405 /// \param[in] options 406 /// This object holds the options used to control when to stop, whether to 407 /// execute commands, 408 /// etc. 409 /// \param[out] result 410 /// This is marked as succeeding with no output if all commands execute 411 /// safely, 412 /// and failed with some explanation if we aborted executing the commands 413 /// at some point. 414 void HandleCommandsFromFile(FileSpec &file, const ExecutionContext &context, 415 const CommandInterpreterRunOptions &options, 416 CommandReturnObject &result); 417 418 void HandleCommandsFromFile(FileSpec &file, 419 const CommandInterpreterRunOptions &options, 420 CommandReturnObject &result); 421 422 CommandObject *GetCommandObjectForCommand(llvm::StringRef &command_line); 423 424 /// Returns the auto-suggestion string that should be added to the given 425 /// command line. 426 std::optional<std::string> GetAutoSuggestionForCommand(llvm::StringRef line); 427 428 // This handles command line completion. 429 void HandleCompletion(CompletionRequest &request); 430 431 // This version just returns matches, and doesn't compute the substring. It 432 // is here so the Help command can call it for the first argument. 433 void HandleCompletionMatches(CompletionRequest &request); 434 435 int GetCommandNamesMatchingPartialString(const char *cmd_cstr, 436 bool include_aliases, 437 StringList &matches, 438 StringList &descriptions); 439 440 void GetHelp(CommandReturnObject &result, 441 uint32_t types = eCommandTypesAllThem); 442 443 void GetAliasHelp(const char *alias_name, StreamString &help_string); 444 445 void OutputFormattedHelpText(Stream &strm, llvm::StringRef prefix, 446 llvm::StringRef help_text); 447 448 void OutputFormattedHelpText(Stream &stream, llvm::StringRef command_word, 449 llvm::StringRef separator, 450 llvm::StringRef help_text, size_t max_word_len); 451 452 // this mimics OutputFormattedHelpText but it does perform a much simpler 453 // formatting, basically ensuring line alignment. This is only good if you 454 // have some complicated layout for your help text and want as little help as 455 // reasonable in properly displaying it. Most of the times, you simply want 456 // to type some text and have it printed in a reasonable way on screen. If 457 // so, use OutputFormattedHelpText 458 void OutputHelpText(Stream &stream, llvm::StringRef command_word, 459 llvm::StringRef separator, llvm::StringRef help_text, 460 uint32_t max_word_len); 461 GetDebugger()462 Debugger &GetDebugger() { return m_debugger; } 463 464 ExecutionContext GetExecutionContext() const; 465 466 lldb::PlatformSP GetPlatform(bool prefer_target_platform); 467 468 const char *ProcessEmbeddedScriptCommands(const char *arg); 469 470 void UpdatePrompt(llvm::StringRef prompt); 471 472 bool Confirm(llvm::StringRef message, bool default_answer); 473 474 void LoadCommandDictionary(); 475 476 void Initialize(); 477 478 void Clear(); 479 480 bool HasCommands() const; 481 482 bool HasAliases() const; 483 484 bool HasUserCommands() const; 485 486 bool HasUserMultiwordCommands() const; 487 488 bool HasAliasOptions() const; 489 490 void BuildAliasCommandArgs(CommandObject *alias_cmd_obj, 491 const char *alias_name, Args &cmd_args, 492 std::string &raw_input_string, 493 CommandReturnObject &result); 494 495 /// Picks the number out of a string of the form "%NNN", otherwise return 0. 496 int GetOptionArgumentPosition(const char *in_string); 497 SkipLLDBInitFiles(bool skip_lldbinit_files)498 void SkipLLDBInitFiles(bool skip_lldbinit_files) { 499 m_skip_lldbinit_files = skip_lldbinit_files; 500 } 501 SkipAppInitFiles(bool skip_app_init_files)502 void SkipAppInitFiles(bool skip_app_init_files) { 503 m_skip_app_init_files = skip_app_init_files; 504 } 505 506 bool GetSynchronous(); 507 508 void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found, 509 StringList &commands_help, 510 bool search_builtin_commands, 511 bool search_user_commands, 512 bool search_alias_commands, 513 bool search_user_mw_commands); 514 GetBatchCommandMode()515 bool GetBatchCommandMode() { return m_batch_command_mode; } 516 SetBatchCommandMode(bool value)517 bool SetBatchCommandMode(bool value) { 518 const bool old_value = m_batch_command_mode; 519 m_batch_command_mode = value; 520 return old_value; 521 } 522 ChildrenTruncated()523 void ChildrenTruncated() { 524 if (m_truncation_warning == eNoOmission) 525 m_truncation_warning = eUnwarnedOmission; 526 } 527 SetReachedMaximumDepth()528 void SetReachedMaximumDepth() { 529 if (m_max_depth_warning == eNoOmission) 530 m_max_depth_warning = eUnwarnedOmission; 531 } 532 PrintWarningsIfNecessary(Stream & s,const std::string & cmd_name)533 void PrintWarningsIfNecessary(Stream &s, const std::string &cmd_name) { 534 if (m_truncation_warning == eUnwarnedOmission) { 535 s.Printf("*** Some of the displayed variables have more members than the " 536 "debugger will show by default. To show all of them, you can " 537 "either use the --show-all-children option to %s or raise the " 538 "limit by changing the target.max-children-count setting.\n", 539 cmd_name.c_str()); 540 m_truncation_warning = eWarnedOmission; 541 } 542 543 if (m_max_depth_warning == eUnwarnedOmission) { 544 s.Printf("*** Some of the displayed variables have a greater depth of " 545 "members than the debugger will show by default. To increase " 546 "the limit, use the --depth option to %s, or raise the limit by " 547 "changing the target.max-children-depth setting.\n", 548 cmd_name.c_str()); 549 m_max_depth_warning = eWarnedOmission; 550 } 551 } 552 GetCommandHistory()553 CommandHistory &GetCommandHistory() { return m_command_history; } 554 555 bool IsActive(); 556 557 CommandInterpreterRunResult 558 RunCommandInterpreter(CommandInterpreterRunOptions &options); 559 560 void GetLLDBCommandsFromIOHandler(const char *prompt, 561 IOHandlerDelegate &delegate, 562 void *baton = nullptr); 563 564 void GetPythonCommandsFromIOHandler(const char *prompt, 565 IOHandlerDelegate &delegate, 566 void *baton = nullptr); 567 568 const char *GetCommandPrefix(); 569 570 // Properties 571 bool GetExpandRegexAliases() const; 572 573 bool GetPromptOnQuit() const; 574 void SetPromptOnQuit(bool enable); 575 576 bool GetSaveTranscript() const; 577 void SetSaveTranscript(bool enable); 578 579 bool GetSaveSessionOnQuit() const; 580 void SetSaveSessionOnQuit(bool enable); 581 582 bool GetOpenTranscriptInEditor() const; 583 void SetOpenTranscriptInEditor(bool enable); 584 585 FileSpec GetSaveSessionDirectory() const; 586 void SetSaveSessionDirectory(llvm::StringRef path); 587 588 bool GetEchoCommands() const; 589 void SetEchoCommands(bool enable); 590 591 bool GetEchoCommentCommands() const; 592 void SetEchoCommentCommands(bool enable); 593 594 bool GetRepeatPreviousCommand() const; 595 596 bool GetRequireCommandOverwrite() const; 597 GetUserCommands()598 const CommandObject::CommandMap &GetUserCommands() const { 599 return m_user_dict; 600 } 601 GetUserMultiwordCommands()602 const CommandObject::CommandMap &GetUserMultiwordCommands() const { 603 return m_user_mw_dict; 604 } 605 GetCommands()606 const CommandObject::CommandMap &GetCommands() const { 607 return m_command_dict; 608 } 609 GetAliases()610 const CommandObject::CommandMap &GetAliases() const { return m_alias_dict; } 611 612 /// Specify if the command interpreter should allow that the user can 613 /// specify a custom exit code when calling 'quit'. 614 void AllowExitCodeOnQuit(bool allow); 615 616 /// Sets the exit code for the quit command. 617 /// \param[in] exit_code 618 /// The exit code that the driver should return on exit. 619 /// \return True if the exit code was successfully set; false if the 620 /// interpreter doesn't allow custom exit codes. 621 /// \see AllowExitCodeOnQuit 622 [[nodiscard]] bool SetQuitExitCode(int exit_code); 623 624 /// Returns the exit code that the user has specified when running the 625 /// 'quit' command. 626 /// \param[out] exited 627 /// Set to true if the user has called quit with a custom exit code. 628 int GetQuitExitCode(bool &exited) const; 629 630 void ResolveCommand(const char *command_line, CommandReturnObject &result); 631 632 bool GetStopCmdSourceOnError() const; 633 634 lldb::IOHandlerSP 635 GetIOHandler(bool force_create = false, 636 CommandInterpreterRunOptions *options = nullptr); 637 638 bool GetSpaceReplPrompts() const; 639 640 /// Save the current debugger session transcript to a file on disk. 641 /// \param output_file 642 /// The file path to which the session transcript will be written. Since 643 /// the argument is optional, an arbitrary temporary file will be create 644 /// when no argument is passed. 645 /// \param result 646 /// This is used to pass function output and error messages. 647 /// \return \b true if the session transcript was successfully written to 648 /// disk, \b false otherwise. 649 bool SaveTranscript(CommandReturnObject &result, 650 std::optional<std::string> output_file = std::nullopt); 651 652 FileSpec GetCurrentSourceDir(); 653 654 bool IsInteractive(); 655 656 bool IOHandlerInterrupt(IOHandler &io_handler) override; 657 658 Status PreprocessCommand(std::string &command); 659 Status PreprocessToken(std::string &token); 660 IncreaseCommandUsage(const CommandObject & cmd_obj)661 void IncreaseCommandUsage(const CommandObject &cmd_obj) { 662 ++m_command_usages[cmd_obj.GetCommandName()]; 663 } 664 665 llvm::json::Value GetStatistics(); 666 const StructuredData::Array &GetTranscript() const; 667 668 protected: 669 friend class Debugger; 670 671 // This checks just the RunCommandInterpreter interruption state. It is only 672 // meant to be used in Debugger::InterruptRequested 673 bool WasInterrupted() const; 674 675 // IOHandlerDelegate functions 676 void IOHandlerInputComplete(IOHandler &io_handler, 677 std::string &line) override; 678 IOHandlerGetControlSequence(char ch)679 llvm::StringRef IOHandlerGetControlSequence(char ch) override { 680 static constexpr llvm::StringLiteral control_sequence("quit\n"); 681 if (ch == 'd') 682 return control_sequence; 683 return {}; 684 } 685 686 void GetProcessOutput(); 687 688 bool DidProcessStopAbnormally() const; 689 690 void SetSynchronous(bool value); 691 692 lldb::CommandObjectSP GetCommandSP(llvm::StringRef cmd, 693 bool include_aliases = true, 694 bool exact = true, 695 StringList *matches = nullptr, 696 StringList *descriptions = nullptr) const; 697 698 private: 699 void OverrideExecutionContext(const ExecutionContext &override_context); 700 701 void RestoreExecutionContext(); 702 703 void SourceInitFile(FileSpec file, CommandReturnObject &result); 704 705 // Completely resolves aliases and abbreviations, returning a pointer to the 706 // final command object and updating command_line to the fully substituted 707 // and translated command. 708 CommandObject *ResolveCommandImpl(std::string &command_line, 709 CommandReturnObject &result); 710 711 void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found, 712 StringList &commands_help, 713 const CommandObject::CommandMap &command_map); 714 715 // An interruptible wrapper around the stream output 716 void PrintCommandOutput(IOHandler &io_handler, llvm::StringRef str, 717 bool is_stdout); 718 719 bool EchoCommandNonInteractive(llvm::StringRef line, 720 const Flags &io_handler_flags) const; 721 722 // A very simple state machine which models the command handling transitions 723 enum class CommandHandlingState { 724 eIdle, 725 eInProgress, 726 eInterrupted, 727 }; 728 729 std::atomic<CommandHandlingState> m_command_state{ 730 CommandHandlingState::eIdle}; 731 732 int m_iohandler_nesting_level = 0; 733 734 void StartHandlingCommand(); 735 void FinishHandlingCommand(); 736 737 Debugger &m_debugger; // The debugger session that this interpreter is 738 // associated with 739 // Execution contexts that were temporarily set by some of HandleCommand* 740 // overloads. 741 std::stack<ExecutionContext> m_overriden_exe_contexts; 742 bool m_synchronous_execution; 743 bool m_skip_lldbinit_files; 744 bool m_skip_app_init_files; 745 CommandObject::CommandMap m_command_dict; // Stores basic built-in commands 746 // (they cannot be deleted, removed 747 // or overwritten). 748 CommandObject::CommandMap 749 m_alias_dict; // Stores user aliases/abbreviations for commands 750 CommandObject::CommandMap m_user_dict; // Stores user-defined commands 751 CommandObject::CommandMap 752 m_user_mw_dict; // Stores user-defined multiword commands 753 CommandHistory m_command_history; 754 std::string m_repeat_command; // Stores the command that will be executed for 755 // an empty command string. 756 lldb::IOHandlerSP m_command_io_handler_sp; 757 char m_comment_char; 758 bool m_batch_command_mode; 759 /// Whether we truncated a value's list of children and whether the user has 760 /// been told. 761 ChildrenOmissionWarningStatus m_truncation_warning; 762 /// Whether we reached the maximum child nesting depth and whether the user 763 /// has been told. 764 ChildrenOmissionWarningStatus m_max_depth_warning; 765 766 // FIXME: Stop using this to control adding to the history and then replace 767 // this with m_command_source_dirs.size(). 768 uint32_t m_command_source_depth; 769 /// A stack of directory paths. When not empty, the last one is the directory 770 /// of the file that's currently sourced. 771 std::vector<FileSpec> m_command_source_dirs; 772 std::vector<uint32_t> m_command_source_flags; 773 CommandInterpreterRunResult m_result; 774 775 // The exit code the user has requested when calling the 'quit' command. 776 // No value means the user hasn't set a custom exit code so far. 777 std::optional<int> m_quit_exit_code; 778 // If the driver is accepts custom exit codes for the 'quit' command. 779 bool m_allow_exit_code = false; 780 781 /// Command usage statistics. 782 typedef llvm::StringMap<uint64_t> CommandUsageMap; 783 CommandUsageMap m_command_usages; 784 785 /// Turn on settings `interpreter.save-transcript` for LLDB to populate 786 /// this stream. Otherwise this stream is empty. 787 StreamString m_transcript_stream; 788 789 /// Contains a list of handled commands and their details. Each element in 790 /// the list is a dictionary with the following keys/values: 791 /// - "command" (string): The command that was given by the user. 792 /// - "commandName" (string): The name of the executed command. 793 /// - "commandArguments" (string): The arguments of the executed command. 794 /// - "output" (string): The output of the command. Empty ("") if no output. 795 /// - "error" (string): The error of the command. Empty ("") if no error. 796 /// - "durationInSeconds" (float): The time it took to execute the command. 797 /// - "timestampInEpochSeconds" (int): The timestamp when the command is 798 /// executed. 799 /// 800 /// Turn on settings `interpreter.save-transcript` for LLDB to populate 801 /// this list. Otherwise this list is empty. 802 StructuredData::Array m_transcript; 803 }; 804 805 } // namespace lldb_private 806 807 #endif // LLDB_INTERPRETER_COMMANDINTERPRETER_H 808