1 //===-- IOHandler.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 liblldb_IOHandler_h_ 10 #define liblldb_IOHandler_h_ 11 12 #include "lldb/Core/ValueObjectList.h" 13 #include "lldb/Utility/ConstString.h" 14 #include "lldb/Utility/Flags.h" 15 #include "lldb/Utility/Predicate.h" 16 #include "lldb/Utility/Reproducer.h" 17 #include "lldb/Utility/Stream.h" 18 #include "lldb/Utility/StringList.h" 19 #include "lldb/lldb-defines.h" 20 #include "lldb/lldb-forward.h" 21 #include "llvm/ADT/StringRef.h" 22 23 #include <memory> 24 #include <mutex> 25 #include <string> 26 #include <vector> 27 28 #include <stdint.h> 29 #include <stdio.h> 30 31 namespace lldb_private { 32 class Debugger; 33 } 34 35 namespace curses { 36 class Application; 37 typedef std::unique_ptr<Application> ApplicationAP; 38 } // namespace curses 39 40 namespace lldb_private { 41 42 class IOHandler { 43 public: 44 enum class Type { 45 CommandInterpreter, 46 CommandList, 47 Confirm, 48 Curses, 49 Expression, 50 REPL, 51 ProcessIO, 52 PythonInterpreter, 53 PythonCode, 54 Other 55 }; 56 57 IOHandler(Debugger &debugger, IOHandler::Type type); 58 59 IOHandler(Debugger &debugger, IOHandler::Type type, 60 const lldb::StreamFileSP &input_sp, 61 const lldb::StreamFileSP &output_sp, 62 const lldb::StreamFileSP &error_sp, uint32_t flags, 63 repro::DataRecorder *data_recorder); 64 65 virtual ~IOHandler(); 66 67 // Each IOHandler gets to run until it is done. It should read data from the 68 // "in" and place output into "out" and "err and return when done. 69 virtual void Run() = 0; 70 71 // Called when an input reader should relinquish its control so another can 72 // be pushed onto the IO handler stack, or so the current IO handler can pop 73 // itself off the stack 74 75 virtual void Cancel() = 0; 76 77 // Called when CTRL+C is pressed which usually causes 78 // Debugger::DispatchInputInterrupt to be called. 79 80 virtual bool Interrupt() = 0; 81 82 virtual void GotEOF() = 0; 83 84 virtual bool IsActive() { return m_active && !m_done; } 85 86 virtual void SetIsDone(bool b) { m_done = b; } 87 88 virtual bool GetIsDone() { return m_done; } 89 90 Type GetType() const { return m_type; } 91 92 virtual void Activate() { m_active = true; } 93 94 virtual void Deactivate() { m_active = false; } 95 96 virtual const char *GetPrompt() { 97 // Prompt support isn't mandatory 98 return nullptr; 99 } 100 101 virtual bool SetPrompt(llvm::StringRef prompt) { 102 // Prompt support isn't mandatory 103 return false; 104 } 105 bool SetPrompt(const char *) = delete; 106 107 virtual ConstString GetControlSequence(char ch) { return ConstString(); } 108 109 virtual const char *GetCommandPrefix() { return nullptr; } 110 111 virtual const char *GetHelpPrologue() { return nullptr; } 112 113 int GetInputFD(); 114 115 int GetOutputFD(); 116 117 int GetErrorFD(); 118 119 FILE *GetInputFILE(); 120 121 FILE *GetOutputFILE(); 122 123 FILE *GetErrorFILE(); 124 125 lldb::StreamFileSP &GetInputStreamFile(); 126 127 lldb::StreamFileSP &GetOutputStreamFile(); 128 129 lldb::StreamFileSP &GetErrorStreamFile(); 130 131 Debugger &GetDebugger() { return m_debugger; } 132 133 void *GetUserData() { return m_user_data; } 134 135 void SetUserData(void *user_data) { m_user_data = user_data; } 136 137 Flags &GetFlags() { return m_flags; } 138 139 const Flags &GetFlags() const { return m_flags; } 140 141 //------------------------------------------------------------------ 142 /// Check if the input is being supplied interactively by a user 143 /// 144 /// This will return true if the input stream is a terminal (tty or 145 /// pty) and can cause IO handlers to do different things (like 146 /// for a confirmation when deleting all breakpoints). 147 //------------------------------------------------------------------ 148 bool GetIsInteractive(); 149 150 //------------------------------------------------------------------ 151 /// Check if the input is coming from a real terminal. 152 /// 153 /// A real terminal has a valid size with a certain number of rows 154 /// and columns. If this function returns true, then terminal escape 155 /// sequences are expected to work (cursor movement escape sequences, 156 /// clearing lines, etc). 157 //------------------------------------------------------------------ 158 bool GetIsRealTerminal(); 159 160 void SetPopped(bool b); 161 162 void WaitForPop(); 163 164 virtual void PrintAsync(Stream *stream, const char *s, size_t len) { 165 stream->Write(s, len); 166 stream->Flush(); 167 } 168 169 protected: 170 Debugger &m_debugger; 171 lldb::StreamFileSP m_input_sp; 172 lldb::StreamFileSP m_output_sp; 173 lldb::StreamFileSP m_error_sp; 174 repro::DataRecorder *m_data_recorder; 175 Predicate<bool> m_popped; 176 Flags m_flags; 177 Type m_type; 178 void *m_user_data; 179 bool m_done; 180 bool m_active; 181 182 private: 183 DISALLOW_COPY_AND_ASSIGN(IOHandler); 184 }; 185 186 //------------------------------------------------------------------ 187 /// A delegate class for use with IOHandler subclasses. 188 /// 189 /// The IOHandler delegate is designed to be mixed into classes so 190 /// they can use an IOHandler subclass to fetch input and notify the 191 /// object that inherits from this delegate class when a token is 192 /// received. 193 //------------------------------------------------------------------ 194 class IOHandlerDelegate { 195 public: 196 enum class Completion { None, LLDBCommand, Expression }; 197 198 IOHandlerDelegate(Completion completion = Completion::None) 199 : m_completion(completion) {} 200 201 virtual ~IOHandlerDelegate() = default; 202 203 virtual void IOHandlerActivated(IOHandler &io_handler, bool interactive) {} 204 205 virtual void IOHandlerDeactivated(IOHandler &io_handler) {} 206 207 virtual int IOHandlerComplete(IOHandler &io_handler, const char *current_line, 208 const char *cursor, const char *last_char, 209 int skip_first_n_matches, int max_matches, 210 StringList &matches, StringList &descriptions); 211 212 virtual const char *IOHandlerGetFixIndentationCharacters() { return nullptr; } 213 214 //------------------------------------------------------------------ 215 /// Called when a new line is created or one of an identified set of 216 /// indentation characters is typed. 217 /// 218 /// This function determines how much indentation should be added 219 /// or removed to match the recommended amount for the final line. 220 /// 221 /// \param[in] io_handler 222 /// The IOHandler that responsible for input. 223 /// 224 /// \param[in] lines 225 /// The current input up to the line to be corrected. Lines 226 /// following the line containing the cursor are not included. 227 /// 228 /// \param[in] cursor_position 229 /// The number of characters preceding the cursor on the final 230 /// line at the time. 231 /// 232 /// \return 233 /// Returns an integer describing the number of spaces needed 234 /// to correct the indentation level. Positive values indicate 235 /// that spaces should be added, while negative values represent 236 /// spaces that should be removed. 237 //------------------------------------------------------------------ 238 virtual int IOHandlerFixIndentation(IOHandler &io_handler, 239 const StringList &lines, 240 int cursor_position) { 241 return 0; 242 } 243 244 //------------------------------------------------------------------ 245 /// Called when a line or lines have been retrieved. 246 /// 247 /// This function can handle the current line and possibly call 248 /// IOHandler::SetIsDone(true) when the IO handler is done like when 249 /// "quit" is entered as a command, of when an empty line is 250 /// received. It is up to the delegate to determine when a line 251 /// should cause a IOHandler to exit. 252 //------------------------------------------------------------------ 253 virtual void IOHandlerInputComplete(IOHandler &io_handler, 254 std::string &data) = 0; 255 256 virtual void IOHandlerInputInterrupted(IOHandler &io_handler, 257 std::string &data) {} 258 259 //------------------------------------------------------------------ 260 /// Called to determine whether typing enter after the last line in 261 /// \a lines should end input. This function will not be called on 262 /// IOHandler objects that are getting single lines. 263 /// \param[in] io_handler 264 /// The IOHandler that responsible for updating the lines. 265 /// 266 /// \param[in] lines 267 /// The current multi-line content. May be altered to provide 268 /// alternative input when complete. 269 /// 270 /// \return 271 /// Return an boolean to indicate whether input is complete, 272 /// true indicates that no additional input is necessary, while 273 /// false indicates that more input is required. 274 //------------------------------------------------------------------ 275 virtual bool IOHandlerIsInputComplete(IOHandler &io_handler, 276 StringList &lines) { 277 // Impose no requirements for input to be considered complete. subclasses 278 // should do something more intelligent. 279 return true; 280 } 281 282 virtual ConstString IOHandlerGetControlSequence(char ch) { 283 return ConstString(); 284 } 285 286 virtual const char *IOHandlerGetCommandPrefix() { return nullptr; } 287 288 virtual const char *IOHandlerGetHelpPrologue() { return nullptr; } 289 290 //------------------------------------------------------------------ 291 // Intercept the IOHandler::Interrupt() calls and do something. 292 // 293 // Return true if the interrupt was handled, false if the IOHandler should 294 // continue to try handle the interrupt itself. 295 //------------------------------------------------------------------ 296 virtual bool IOHandlerInterrupt(IOHandler &io_handler) { return false; } 297 298 protected: 299 Completion m_completion; // Support for common builtin completions 300 }; 301 302 //---------------------------------------------------------------------- 303 // IOHandlerDelegateMultiline 304 // 305 // A IOHandlerDelegate that handles terminating multi-line input when 306 // the last line is equal to "end_line" which is specified in the constructor. 307 //---------------------------------------------------------------------- 308 class IOHandlerDelegateMultiline : public IOHandlerDelegate { 309 public: 310 IOHandlerDelegateMultiline(const char *end_line, 311 Completion completion = Completion::None) 312 : IOHandlerDelegate(completion), 313 m_end_line((end_line && end_line[0]) ? end_line : "") {} 314 315 ~IOHandlerDelegateMultiline() override = default; 316 317 ConstString IOHandlerGetControlSequence(char ch) override { 318 if (ch == 'd') 319 return ConstString(m_end_line + "\n"); 320 return ConstString(); 321 } 322 323 bool IOHandlerIsInputComplete(IOHandler &io_handler, 324 StringList &lines) override { 325 // Determine whether the end of input signal has been entered 326 const size_t num_lines = lines.GetSize(); 327 if (num_lines > 0 && lines[num_lines - 1] == m_end_line) { 328 // Remove the terminal line from "lines" so it doesn't appear in the 329 // resulting input and return true to indicate we are done getting lines 330 lines.PopBack(); 331 return true; 332 } 333 return false; 334 } 335 336 protected: 337 const std::string m_end_line; 338 }; 339 340 class IOHandlerEditline : public IOHandler { 341 public: 342 IOHandlerEditline(Debugger &debugger, IOHandler::Type type, 343 const char *editline_name, // Used for saving history files 344 llvm::StringRef prompt, llvm::StringRef continuation_prompt, 345 bool multi_line, bool color_prompts, 346 uint32_t line_number_start, // If non-zero show line numbers 347 // starting at 348 // 'line_number_start' 349 IOHandlerDelegate &delegate, 350 repro::DataRecorder *data_recorder); 351 352 IOHandlerEditline(Debugger &debugger, IOHandler::Type type, 353 const lldb::StreamFileSP &input_sp, 354 const lldb::StreamFileSP &output_sp, 355 const lldb::StreamFileSP &error_sp, uint32_t flags, 356 const char *editline_name, // Used for saving history files 357 llvm::StringRef prompt, llvm::StringRef continuation_prompt, 358 bool multi_line, bool color_prompts, 359 uint32_t line_number_start, // If non-zero show line numbers 360 // starting at 361 // 'line_number_start' 362 IOHandlerDelegate &delegate, 363 repro::DataRecorder *data_recorder); 364 365 IOHandlerEditline(Debugger &, IOHandler::Type, const char *, const char *, 366 const char *, bool, bool, uint32_t, 367 IOHandlerDelegate &) = delete; 368 369 IOHandlerEditline(Debugger &, IOHandler::Type, const lldb::StreamFileSP &, 370 const lldb::StreamFileSP &, const lldb::StreamFileSP &, 371 uint32_t, const char *, const char *, const char *, bool, 372 bool, uint32_t, IOHandlerDelegate &) = delete; 373 374 ~IOHandlerEditline() override; 375 376 void Run() override; 377 378 void Cancel() override; 379 380 bool Interrupt() override; 381 382 void GotEOF() override; 383 384 void Activate() override; 385 386 void Deactivate() override; 387 388 ConstString GetControlSequence(char ch) override { 389 return m_delegate.IOHandlerGetControlSequence(ch); 390 } 391 392 const char *GetCommandPrefix() override { 393 return m_delegate.IOHandlerGetCommandPrefix(); 394 } 395 396 const char *GetHelpPrologue() override { 397 return m_delegate.IOHandlerGetHelpPrologue(); 398 } 399 400 const char *GetPrompt() override; 401 402 bool SetPrompt(llvm::StringRef prompt) override; 403 bool SetPrompt(const char *prompt) = delete; 404 405 const char *GetContinuationPrompt(); 406 407 void SetContinuationPrompt(llvm::StringRef prompt); 408 void SetContinuationPrompt(const char *) = delete; 409 410 bool GetLine(std::string &line, bool &interrupted); 411 412 bool GetLines(StringList &lines, bool &interrupted); 413 414 void SetBaseLineNumber(uint32_t line); 415 416 bool GetInterruptExits() { return m_interrupt_exits; } 417 418 void SetInterruptExits(bool b) { m_interrupt_exits = b; } 419 420 const StringList *GetCurrentLines() const { return m_current_lines_ptr; } 421 422 uint32_t GetCurrentLineIndex() const; 423 424 void PrintAsync(Stream *stream, const char *s, size_t len) override; 425 426 private: 427 #ifndef LLDB_DISABLE_LIBEDIT 428 static bool IsInputCompleteCallback(Editline *editline, StringList &lines, 429 void *baton); 430 431 static int FixIndentationCallback(Editline *editline, const StringList &lines, 432 int cursor_position, void *baton); 433 434 static int AutoCompleteCallback(const char *current_line, const char *cursor, 435 const char *last_char, 436 int skip_first_n_matches, int max_matches, 437 StringList &matches, StringList &descriptions, 438 void *baton); 439 #endif 440 441 protected: 442 #ifndef LLDB_DISABLE_LIBEDIT 443 std::unique_ptr<Editline> m_editline_up; 444 #endif 445 IOHandlerDelegate &m_delegate; 446 std::string m_prompt; 447 std::string m_continuation_prompt; 448 StringList *m_current_lines_ptr; 449 uint32_t m_base_line_number; // If non-zero, then show line numbers in prompt 450 uint32_t m_curr_line_idx; 451 bool m_multi_line; 452 bool m_color_prompts; 453 bool m_interrupt_exits; 454 bool m_editing; // Set to true when fetching a line manually (not using 455 // libedit) 456 }; 457 458 // The order of base classes is important. Look at the constructor of 459 // IOHandlerConfirm to see how. 460 class IOHandlerConfirm : public IOHandlerDelegate, public IOHandlerEditline { 461 public: 462 IOHandlerConfirm(Debugger &debugger, llvm::StringRef prompt, 463 bool default_response); 464 465 ~IOHandlerConfirm() override; 466 467 bool GetResponse() const { return m_user_response; } 468 469 int IOHandlerComplete(IOHandler &io_handler, const char *current_line, 470 const char *cursor, const char *last_char, 471 int skip_first_n_matches, int max_matches, 472 StringList &matches, StringList &descriptions) override; 473 474 void IOHandlerInputComplete(IOHandler &io_handler, 475 std::string &data) override; 476 477 protected: 478 const bool m_default_response; 479 bool m_user_response; 480 }; 481 482 class IOHandlerCursesGUI : public IOHandler { 483 public: 484 IOHandlerCursesGUI(Debugger &debugger); 485 486 ~IOHandlerCursesGUI() override; 487 488 void Run() override; 489 490 void Cancel() override; 491 492 bool Interrupt() override; 493 494 void GotEOF() override; 495 496 void Activate() override; 497 498 void Deactivate() override; 499 500 protected: 501 curses::ApplicationAP m_app_ap; 502 }; 503 504 class IOHandlerCursesValueObjectList : public IOHandler { 505 public: 506 IOHandlerCursesValueObjectList(Debugger &debugger, 507 ValueObjectList &valobj_list); 508 509 ~IOHandlerCursesValueObjectList() override; 510 511 void Run() override; 512 513 void GotEOF() override; 514 515 protected: 516 ValueObjectList m_valobj_list; 517 }; 518 519 class IOHandlerStack { 520 public: 521 IOHandlerStack() : m_stack(), m_mutex(), m_top(nullptr) {} 522 523 ~IOHandlerStack() = default; 524 525 size_t GetSize() const { 526 std::lock_guard<std::recursive_mutex> guard(m_mutex); 527 return m_stack.size(); 528 } 529 530 void Push(const lldb::IOHandlerSP &sp) { 531 if (sp) { 532 std::lock_guard<std::recursive_mutex> guard(m_mutex); 533 sp->SetPopped(false); 534 m_stack.push_back(sp); 535 // Set m_top the non-locking IsTop() call 536 m_top = sp.get(); 537 } 538 } 539 540 bool IsEmpty() const { 541 std::lock_guard<std::recursive_mutex> guard(m_mutex); 542 return m_stack.empty(); 543 } 544 545 lldb::IOHandlerSP Top() { 546 lldb::IOHandlerSP sp; 547 { 548 std::lock_guard<std::recursive_mutex> guard(m_mutex); 549 if (!m_stack.empty()) 550 sp = m_stack.back(); 551 } 552 return sp; 553 } 554 555 void Pop() { 556 std::lock_guard<std::recursive_mutex> guard(m_mutex); 557 if (!m_stack.empty()) { 558 lldb::IOHandlerSP sp(m_stack.back()); 559 m_stack.pop_back(); 560 sp->SetPopped(true); 561 } 562 // Set m_top the non-locking IsTop() call 563 564 m_top = (m_stack.empty() ? nullptr : m_stack.back().get()); 565 } 566 567 std::recursive_mutex &GetMutex() { return m_mutex; } 568 569 bool IsTop(const lldb::IOHandlerSP &io_handler_sp) const { 570 return m_top == io_handler_sp.get(); 571 } 572 573 bool CheckTopIOHandlerTypes(IOHandler::Type top_type, 574 IOHandler::Type second_top_type) { 575 std::lock_guard<std::recursive_mutex> guard(m_mutex); 576 const size_t num_io_handlers = m_stack.size(); 577 return (num_io_handlers >= 2 && 578 m_stack[num_io_handlers - 1]->GetType() == top_type && 579 m_stack[num_io_handlers - 2]->GetType() == second_top_type); 580 } 581 582 ConstString GetTopIOHandlerControlSequence(char ch) { 583 return ((m_top != nullptr) ? m_top->GetControlSequence(ch) : ConstString()); 584 } 585 586 const char *GetTopIOHandlerCommandPrefix() { 587 return ((m_top != nullptr) ? m_top->GetCommandPrefix() : nullptr); 588 } 589 590 const char *GetTopIOHandlerHelpPrologue() { 591 return ((m_top != nullptr) ? m_top->GetHelpPrologue() : nullptr); 592 } 593 594 void PrintAsync(Stream *stream, const char *s, size_t len); 595 596 protected: 597 typedef std::vector<lldb::IOHandlerSP> collection; 598 collection m_stack; 599 mutable std::recursive_mutex m_mutex; 600 IOHandler *m_top; 601 602 private: 603 DISALLOW_COPY_AND_ASSIGN(IOHandlerStack); 604 }; 605 606 } // namespace lldb_private 607 608 #endif // liblldb_IOHandler_h_ 609