1 //===-- IOHandler.cpp -----------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Core/IOHandler.h"
11 #if defined(__APPLE__)
16 #include "lldb/Core/Debugger.h"
17 #include "lldb/Host/Config.h"
18 #include "lldb/Host/File.h"
19 #include "lldb/Host/StreamFile.h"
20 #include "lldb/Utility/AnsiTerminal.h"
21 #include "lldb/Utility/Predicate.h"
22 #include "lldb/Utility/Status.h"
23 #include "lldb/Utility/StreamString.h"
24 #include "lldb/Utility/StringList.h"
25 #include "lldb/lldb-forward.h"
27 #if LLDB_ENABLE_LIBEDIT
28 #include "lldb/Host/Editline.h"
30 #include "lldb/Interpreter/CommandCompletions.h"
31 #include "lldb/Interpreter/CommandInterpreter.h"
32 #include "llvm/ADT/StringRef.h"
35 #include "lldb/Host/windows/windows.h"
49 #include <type_traits>
52 using namespace lldb_private
;
53 using llvm::StringRef
;
55 IOHandler::IOHandler(Debugger
&debugger
, IOHandler::Type type
)
56 : IOHandler(debugger
, type
,
57 FileSP(), // Adopt STDIN from top input reader
58 StreamFileSP(), // Adopt STDOUT from top input reader
59 StreamFileSP(), // Adopt STDERR from top input reader
64 IOHandler::IOHandler(Debugger
&debugger
, IOHandler::Type type
,
65 const lldb::FileSP
&input_sp
,
66 const lldb::StreamFileSP
&output_sp
,
67 const lldb::StreamFileSP
&error_sp
, uint32_t flags
)
68 : m_debugger(debugger
), m_input_sp(input_sp
), m_output_sp(output_sp
),
69 m_error_sp(error_sp
), m_popped(false), m_flags(flags
), m_type(type
),
70 m_user_data(nullptr), m_done(false), m_active(false) {
71 // If any files are not specified, then adopt them from the top input reader.
72 if (!m_input_sp
|| !m_output_sp
|| !m_error_sp
)
73 debugger
.AdoptTopIOHandlerFilesIfInvalid(m_input_sp
, m_output_sp
,
77 IOHandler::~IOHandler() = default;
79 int IOHandler::GetInputFD() {
80 return (m_input_sp
? m_input_sp
->GetDescriptor() : -1);
83 int IOHandler::GetOutputFD() {
84 return (m_output_sp
? m_output_sp
->GetFile().GetDescriptor() : -1);
87 int IOHandler::GetErrorFD() {
88 return (m_error_sp
? m_error_sp
->GetFile().GetDescriptor() : -1);
91 FILE *IOHandler::GetInputFILE() {
92 return (m_input_sp
? m_input_sp
->GetStream() : nullptr);
95 FILE *IOHandler::GetOutputFILE() {
96 return (m_output_sp
? m_output_sp
->GetFile().GetStream() : nullptr);
99 FILE *IOHandler::GetErrorFILE() {
100 return (m_error_sp
? m_error_sp
->GetFile().GetStream() : nullptr);
103 FileSP
IOHandler::GetInputFileSP() { return m_input_sp
; }
105 StreamFileSP
IOHandler::GetOutputStreamFileSP() { return m_output_sp
; }
107 StreamFileSP
IOHandler::GetErrorStreamFileSP() { return m_error_sp
; }
109 bool IOHandler::GetIsInteractive() {
110 return GetInputFileSP() ? GetInputFileSP()->GetIsInteractive() : false;
113 bool IOHandler::GetIsRealTerminal() {
114 return GetInputFileSP() ? GetInputFileSP()->GetIsRealTerminal() : false;
117 void IOHandler::SetPopped(bool b
) { m_popped
.SetValue(b
, eBroadcastOnChange
); }
119 void IOHandler::WaitForPop() { m_popped
.WaitForValueEqualTo(true); }
121 void IOHandler::PrintAsync(const char *s
, size_t len
, bool is_stdout
) {
122 std::lock_guard
<std::recursive_mutex
> guard(m_output_mutex
);
123 lldb::StreamFileSP stream
= is_stdout
? m_output_sp
: m_error_sp
;
124 stream
->Write(s
, len
);
128 bool IOHandlerStack::PrintAsync(const char *s
, size_t len
, bool is_stdout
) {
129 std::lock_guard
<std::recursive_mutex
> guard(m_mutex
);
132 m_top
->PrintAsync(s
, len
, is_stdout
);
136 IOHandlerConfirm::IOHandlerConfirm(Debugger
&debugger
, llvm::StringRef prompt
,
137 bool default_response
)
139 debugger
, IOHandler::Type::Confirm
,
140 nullptr, // nullptr editline_name means no history loaded/saved
141 llvm::StringRef(), // No prompt
142 llvm::StringRef(), // No continuation prompt
144 false, // Don't colorize the prompt (i.e. the confirm message.)
146 m_default_response(default_response
), m_user_response(default_response
) {
147 StreamString prompt_stream
;
148 prompt_stream
.PutCString(prompt
);
149 if (m_default_response
)
150 prompt_stream
.Printf(": [Y/n] ");
152 prompt_stream
.Printf(": [y/N] ");
154 SetPrompt(prompt_stream
.GetString());
157 IOHandlerConfirm::~IOHandlerConfirm() = default;
159 void IOHandlerConfirm::IOHandlerComplete(IOHandler
&io_handler
,
160 CompletionRequest
&request
) {
161 if (request
.GetRawCursorPos() != 0)
163 request
.AddCompletion(m_default_response
? "y" : "n");
166 void IOHandlerConfirm::IOHandlerInputComplete(IOHandler
&io_handler
,
169 // User just hit enter, set the response to the default
170 m_user_response
= m_default_response
;
171 io_handler
.SetIsDone(true);
175 if (line
.size() == 1) {
179 m_user_response
= true;
180 io_handler
.SetIsDone(true);
184 m_user_response
= false;
185 io_handler
.SetIsDone(true);
192 if (line
== "yes" || line
== "YES" || line
== "Yes") {
193 m_user_response
= true;
194 io_handler
.SetIsDone(true);
195 } else if (line
== "no" || line
== "NO" || line
== "No") {
196 m_user_response
= false;
197 io_handler
.SetIsDone(true);
201 std::optional
<std::string
>
202 IOHandlerDelegate::IOHandlerSuggestion(IOHandler
&io_handler
,
203 llvm::StringRef line
) {
204 return io_handler
.GetDebugger()
205 .GetCommandInterpreter()
206 .GetAutoSuggestionForCommand(line
);
209 void IOHandlerDelegate::IOHandlerComplete(IOHandler
&io_handler
,
210 CompletionRequest
&request
) {
211 switch (m_completion
) {
212 case Completion::None
:
214 case Completion::LLDBCommand
:
215 io_handler
.GetDebugger().GetCommandInterpreter().HandleCompletion(request
);
217 case Completion::Expression
:
218 lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
219 io_handler
.GetDebugger().GetCommandInterpreter(),
220 lldb::eVariablePathCompletion
, request
, nullptr);
225 IOHandlerEditline::IOHandlerEditline(
226 Debugger
&debugger
, IOHandler::Type type
,
227 const char *editline_name
, // Used for saving history files
228 llvm::StringRef prompt
, llvm::StringRef continuation_prompt
,
229 bool multi_line
, bool color
, uint32_t line_number_start
,
230 IOHandlerDelegate
&delegate
)
231 : IOHandlerEditline(debugger
, type
,
232 FileSP(), // Inherit input from top input reader
233 StreamFileSP(), // Inherit output from top input reader
234 StreamFileSP(), // Inherit error from top input reader
236 editline_name
, // Used for saving history files
237 prompt
, continuation_prompt
, multi_line
, color
,
238 line_number_start
, delegate
) {}
240 IOHandlerEditline::IOHandlerEditline(
241 Debugger
&debugger
, IOHandler::Type type
, const lldb::FileSP
&input_sp
,
242 const lldb::StreamFileSP
&output_sp
, const lldb::StreamFileSP
&error_sp
,
244 const char *editline_name
, // Used for saving history files
245 llvm::StringRef prompt
, llvm::StringRef continuation_prompt
,
246 bool multi_line
, bool color
, uint32_t line_number_start
,
247 IOHandlerDelegate
&delegate
)
248 : IOHandler(debugger
, type
, input_sp
, output_sp
, error_sp
, flags
),
249 #if LLDB_ENABLE_LIBEDIT
252 m_delegate(delegate
), m_prompt(), m_continuation_prompt(),
253 m_current_lines_ptr(nullptr), m_base_line_number(line_number_start
),
254 m_curr_line_idx(UINT32_MAX
), m_multi_line(multi_line
), m_color(color
),
255 m_interrupt_exits(true) {
258 #if LLDB_ENABLE_LIBEDIT
259 bool use_editline
= false;
261 use_editline
= GetInputFILE() && GetOutputFILE() && GetErrorFILE() &&
262 m_input_sp
&& m_input_sp
->GetIsRealTerminal();
265 m_editline_up
= std::make_unique
<Editline
>(editline_name
, GetInputFILE(),
266 GetOutputFILE(), GetErrorFILE(),
267 m_color
, GetOutputMutex());
268 m_editline_up
->SetIsInputCompleteCallback(
269 [this](Editline
*editline
, StringList
&lines
) {
270 return this->IsInputCompleteCallback(editline
, lines
);
273 m_editline_up
->SetAutoCompleteCallback([this](CompletionRequest
&request
) {
274 this->AutoCompleteCallback(request
);
277 if (debugger
.GetUseAutosuggestion()) {
278 m_editline_up
->SetSuggestionCallback([this](llvm::StringRef line
) {
279 return this->SuggestionCallback(line
);
281 m_editline_up
->SetSuggestionAnsiPrefix(ansi::FormatAnsiTerminalCodes(
282 debugger
.GetAutosuggestionAnsiPrefix()));
283 m_editline_up
->SetSuggestionAnsiSuffix(ansi::FormatAnsiTerminalCodes(
284 debugger
.GetAutosuggestionAnsiSuffix()));
286 // See if the delegate supports fixing indentation
287 const char *indent_chars
= delegate
.IOHandlerGetFixIndentationCharacters();
289 // The delegate does support indentation, hook it up so when any
290 // indentation character is typed, the delegate gets a chance to fix it
291 FixIndentationCallbackType f
= [this](Editline
*editline
,
292 const StringList
&lines
,
293 int cursor_position
) {
294 return this->FixIndentationCallback(editline
, lines
, cursor_position
);
296 m_editline_up
->SetFixIndentationCallback(std::move(f
), indent_chars
);
300 SetBaseLineNumber(m_base_line_number
);
302 SetContinuationPrompt(continuation_prompt
);
305 IOHandlerEditline::~IOHandlerEditline() {
306 #if LLDB_ENABLE_LIBEDIT
307 m_editline_up
.reset();
311 void IOHandlerEditline::Activate() {
312 IOHandler::Activate();
313 m_delegate
.IOHandlerActivated(*this, GetIsInteractive());
316 void IOHandlerEditline::Deactivate() {
317 IOHandler::Deactivate();
318 m_delegate
.IOHandlerDeactivated(*this);
321 void IOHandlerEditline::TerminalSizeChanged() {
322 #if LLDB_ENABLE_LIBEDIT
324 m_editline_up
->TerminalSizeChanged();
328 // Split out a line from the buffer, if there is a full one to get.
329 static std::optional
<std::string
> SplitLine(std::string
&line_buffer
) {
330 size_t pos
= line_buffer
.find('\n');
331 if (pos
== std::string::npos
)
334 std::string(StringRef(line_buffer
.c_str(), pos
).rtrim("\n\r"));
335 line_buffer
= line_buffer
.substr(pos
+ 1);
339 // If the final line of the file ends without a end-of-line, return
340 // it as a line anyway.
341 static std::optional
<std::string
> SplitLineEOF(std::string
&line_buffer
) {
342 if (llvm::all_of(line_buffer
, llvm::isSpace
))
344 std::string line
= std::move(line_buffer
);
349 bool IOHandlerEditline::GetLine(std::string
&line
, bool &interrupted
) {
350 #if LLDB_ENABLE_LIBEDIT
352 return m_editline_up
->GetLine(line
, interrupted
);
358 if (GetIsInteractive()) {
359 const char *prompt
= nullptr;
361 if (m_multi_line
&& m_curr_line_idx
> 0)
362 prompt
= GetContinuationPrompt();
364 if (prompt
== nullptr)
365 prompt
= GetPrompt();
367 if (prompt
&& prompt
[0]) {
369 m_output_sp
->Printf("%s", prompt
);
370 m_output_sp
->Flush();
375 std::optional
<std::string
> got_line
= SplitLine(m_line_buffer
);
377 if (!got_line
&& !m_input_sp
) {
378 // No more input file, we are done...
383 FILE *in
= GetInputFILE();
386 if (!got_line
&& !in
&& m_input_sp
) {
387 // there is no FILE*, fall back on just reading bytes from the stream.
389 size_t bytes_read
= sizeof(buffer
);
390 Status error
= m_input_sp
->Read((void *)buffer
, bytes_read
);
391 if (error
.Success() && !bytes_read
) {
392 got_line
= SplitLineEOF(m_line_buffer
);
397 m_line_buffer
+= StringRef(buffer
, bytes_read
);
398 got_line
= SplitLine(m_line_buffer
);
402 if (!got_line
&& in
) {
404 char *r
= fgets(buffer
, sizeof(buffer
), in
);
406 // ReadFile on Windows is supposed to set ERROR_OPERATION_ABORTED
407 // according to the docs on MSDN. However, this has evidently been a
408 // known bug since Windows 8. Therefore, we can't detect if a signal
409 // interrupted in the fgets. So pressing ctrl-c causes the repl to end
410 // and the process to exit. A temporary workaround is just to attempt to
411 // fgets twice until this bug is fixed.
413 r
= fgets(buffer
, sizeof(buffer
), in
);
414 // this is the equivalent of EINTR for Windows
415 if (r
== nullptr && GetLastError() == ERROR_OPERATION_ABORTED
)
419 if (ferror(in
) && errno
== EINTR
)
422 got_line
= SplitLineEOF(m_line_buffer
);
425 m_line_buffer
+= buffer
;
426 got_line
= SplitLine(m_line_buffer
);
434 return (bool)got_line
;
437 #if LLDB_ENABLE_LIBEDIT
438 bool IOHandlerEditline::IsInputCompleteCallback(Editline
*editline
,
440 return m_delegate
.IOHandlerIsInputComplete(*this, lines
);
443 int IOHandlerEditline::FixIndentationCallback(Editline
*editline
,
444 const StringList
&lines
,
445 int cursor_position
) {
446 return m_delegate
.IOHandlerFixIndentation(*this, lines
, cursor_position
);
449 std::optional
<std::string
>
450 IOHandlerEditline::SuggestionCallback(llvm::StringRef line
) {
451 return m_delegate
.IOHandlerSuggestion(*this, line
);
454 void IOHandlerEditline::AutoCompleteCallback(CompletionRequest
&request
) {
455 m_delegate
.IOHandlerComplete(*this, request
);
459 const char *IOHandlerEditline::GetPrompt() {
460 #if LLDB_ENABLE_LIBEDIT
462 return m_editline_up
->GetPrompt();
465 if (m_prompt
.empty())
467 #if LLDB_ENABLE_LIBEDIT
470 return m_prompt
.c_str();
473 bool IOHandlerEditline::SetPrompt(llvm::StringRef prompt
) {
474 m_prompt
= std::string(prompt
);
476 #if LLDB_ENABLE_LIBEDIT
478 m_editline_up
->SetPrompt(m_prompt
.empty() ? nullptr : m_prompt
.c_str());
479 m_editline_up
->SetPromptAnsiPrefix(
480 ansi::FormatAnsiTerminalCodes(m_debugger
.GetPromptAnsiPrefix()));
481 m_editline_up
->SetPromptAnsiSuffix(
482 ansi::FormatAnsiTerminalCodes(m_debugger
.GetPromptAnsiSuffix()));
488 const char *IOHandlerEditline::GetContinuationPrompt() {
489 return (m_continuation_prompt
.empty() ? nullptr
490 : m_continuation_prompt
.c_str());
493 void IOHandlerEditline::SetContinuationPrompt(llvm::StringRef prompt
) {
494 m_continuation_prompt
= std::string(prompt
);
496 #if LLDB_ENABLE_LIBEDIT
498 m_editline_up
->SetContinuationPrompt(m_continuation_prompt
.empty()
500 : m_continuation_prompt
.c_str());
504 void IOHandlerEditline::SetBaseLineNumber(uint32_t line
) {
505 m_base_line_number
= line
;
508 uint32_t IOHandlerEditline::GetCurrentLineIndex() const {
509 #if LLDB_ENABLE_LIBEDIT
511 return m_editline_up
->GetCurrentLine();
513 return m_curr_line_idx
;
516 StringList
IOHandlerEditline::GetCurrentLines() const {
517 #if LLDB_ENABLE_LIBEDIT
519 return m_editline_up
->GetInputAsStringList();
521 // When libedit is not used, the current lines can be gotten from
522 // `m_current_lines_ptr`, which is updated whenever a new line is processed.
523 // This doesn't happen when libedit is used, in which case
524 // `m_current_lines_ptr` is only updated when the full input is terminated.
526 if (m_current_lines_ptr
)
527 return *m_current_lines_ptr
;
531 bool IOHandlerEditline::GetLines(StringList
&lines
, bool &interrupted
) {
532 m_current_lines_ptr
= &lines
;
534 bool success
= false;
535 #if LLDB_ENABLE_LIBEDIT
537 return m_editline_up
->GetLines(m_base_line_number
, lines
, interrupted
);
544 // Show line numbers if we are asked to
546 if (m_base_line_number
> 0 && GetIsInteractive()) {
548 m_output_sp
->Printf("%u%s",
549 m_base_line_number
+ (uint32_t)lines
.GetSize(),
550 GetPrompt() == nullptr ? " " : "");
554 m_curr_line_idx
= lines
.GetSize();
556 bool interrupted
= false;
557 if (GetLine(line
, interrupted
) && !interrupted
) {
558 lines
.AppendString(line
);
559 done
= m_delegate
.IOHandlerIsInputComplete(*this, lines
);
564 success
= lines
.GetSize() > 0;
565 #if LLDB_ENABLE_LIBEDIT
571 // Each IOHandler gets to run until it is done. It should read data from the
572 // "in" and place output into "out" and "err and return when done.
573 void IOHandlerEditline::Run() {
576 bool interrupted
= false;
579 if (GetLines(lines
, interrupted
)) {
581 m_done
= m_interrupt_exits
;
582 m_delegate
.IOHandlerInputInterrupted(*this, line
);
585 line
= lines
.CopyList();
586 m_delegate
.IOHandlerInputComplete(*this, line
);
592 if (GetLine(line
, interrupted
)) {
594 m_delegate
.IOHandlerInputInterrupted(*this, line
);
596 m_delegate
.IOHandlerInputComplete(*this, line
);
604 void IOHandlerEditline::Cancel() {
605 #if LLDB_ENABLE_LIBEDIT
607 m_editline_up
->Cancel();
611 bool IOHandlerEditline::Interrupt() {
612 // Let the delgate handle it first
613 if (m_delegate
.IOHandlerInterrupt(*this))
616 #if LLDB_ENABLE_LIBEDIT
618 return m_editline_up
->Interrupt();
623 void IOHandlerEditline::GotEOF() {
624 #if LLDB_ENABLE_LIBEDIT
626 m_editline_up
->Interrupt();
630 void IOHandlerEditline::PrintAsync(const char *s
, size_t len
, bool is_stdout
) {
631 #if LLDB_ENABLE_LIBEDIT
633 std::lock_guard
<std::recursive_mutex
> guard(m_output_mutex
);
634 lldb::StreamFileSP stream
= is_stdout
? m_output_sp
: m_error_sp
;
635 m_editline_up
->PrintAsync(stream
.get(), s
, len
);
640 const char *prompt
= GetPrompt();
642 // Back up over previous prompt using Windows API
643 CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info
;
644 HANDLE console_handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
645 GetConsoleScreenBufferInfo(console_handle
, &screen_buffer_info
);
646 COORD coord
= screen_buffer_info
.dwCursorPosition
;
647 coord
.X
-= strlen(prompt
);
650 SetConsoleCursorPosition(console_handle
, coord
);
653 IOHandler::PrintAsync(s
, len
, is_stdout
);
656 IOHandler::PrintAsync(prompt
, strlen(prompt
), is_stdout
);