xref: /freebsd-src/contrib/llvm-project/lldb/source/Core/IOHandler.cpp (revision 8cc087a1eee9ec1ca9f7ac1e63ad51bdb5a682eb)
1 //===-- IOHandler.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 "lldb/Core/IOHandler.h"
10 
11 #if defined(__APPLE__)
12 #include <deque>
13 #endif
14 #include <string>
15 
16 #include "lldb/Core/Debugger.h"
17 #include "lldb/Core/StreamFile.h"
18 #include "lldb/Host/Config.h"
19 #include "lldb/Host/File.h"
20 #include "lldb/Utility/Predicate.h"
21 #include "lldb/Utility/ReproducerProvider.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"
26 
27 #if LLDB_ENABLE_LIBEDIT
28 #include "lldb/Host/Editline.h"
29 #endif
30 #include "lldb/Interpreter/CommandCompletions.h"
31 #include "lldb/Interpreter/CommandInterpreter.h"
32 #include "llvm/ADT/StringRef.h"
33 
34 #ifdef _WIN32
35 #include "lldb/Host/windows/windows.h"
36 #endif
37 
38 #include <memory>
39 #include <mutex>
40 
41 #include <cassert>
42 #include <cctype>
43 #include <cerrno>
44 #include <clocale>
45 #include <cstdint>
46 #include <cstdio>
47 #include <cstring>
48 #include <type_traits>
49 
50 using namespace lldb;
51 using namespace lldb_private;
52 using llvm::None;
53 using llvm::Optional;
54 using llvm::StringRef;
55 
56 IOHandler::IOHandler(Debugger &debugger, IOHandler::Type type)
57     : IOHandler(debugger, type,
58                 FileSP(),       // Adopt STDIN from top input reader
59                 StreamFileSP(), // Adopt STDOUT from top input reader
60                 StreamFileSP(), // Adopt STDERR from top input reader
61                 0,              // Flags
62                 nullptr         // Shadow file recorder
63       ) {}
64 
65 IOHandler::IOHandler(Debugger &debugger, IOHandler::Type type,
66                      const lldb::FileSP &input_sp,
67                      const lldb::StreamFileSP &output_sp,
68                      const lldb::StreamFileSP &error_sp, uint32_t flags,
69                      repro::DataRecorder *data_recorder)
70     : m_debugger(debugger), m_input_sp(input_sp), m_output_sp(output_sp),
71       m_error_sp(error_sp), m_data_recorder(data_recorder), m_popped(false),
72       m_flags(flags), m_type(type), m_user_data(nullptr), m_done(false),
73       m_active(false) {
74   // If any files are not specified, then adopt them from the top input reader.
75   if (!m_input_sp || !m_output_sp || !m_error_sp)
76     debugger.AdoptTopIOHandlerFilesIfInvalid(m_input_sp, m_output_sp,
77                                              m_error_sp);
78 }
79 
80 IOHandler::~IOHandler() = default;
81 
82 int IOHandler::GetInputFD() {
83   return (m_input_sp ? m_input_sp->GetDescriptor() : -1);
84 }
85 
86 int IOHandler::GetOutputFD() {
87   return (m_output_sp ? m_output_sp->GetFile().GetDescriptor() : -1);
88 }
89 
90 int IOHandler::GetErrorFD() {
91   return (m_error_sp ? m_error_sp->GetFile().GetDescriptor() : -1);
92 }
93 
94 FILE *IOHandler::GetInputFILE() {
95   return (m_input_sp ? m_input_sp->GetStream() : nullptr);
96 }
97 
98 FILE *IOHandler::GetOutputFILE() {
99   return (m_output_sp ? m_output_sp->GetFile().GetStream() : nullptr);
100 }
101 
102 FILE *IOHandler::GetErrorFILE() {
103   return (m_error_sp ? m_error_sp->GetFile().GetStream() : nullptr);
104 }
105 
106 FileSP IOHandler::GetInputFileSP() { return m_input_sp; }
107 
108 StreamFileSP IOHandler::GetOutputStreamFileSP() { return m_output_sp; }
109 
110 StreamFileSP IOHandler::GetErrorStreamFileSP() { return m_error_sp; }
111 
112 bool IOHandler::GetIsInteractive() {
113   return GetInputFileSP() ? GetInputFileSP()->GetIsInteractive() : false;
114 }
115 
116 bool IOHandler::GetIsRealTerminal() {
117   return GetInputFileSP() ? GetInputFileSP()->GetIsRealTerminal() : false;
118 }
119 
120 void IOHandler::SetPopped(bool b) { m_popped.SetValue(b, eBroadcastOnChange); }
121 
122 void IOHandler::WaitForPop() { m_popped.WaitForValueEqualTo(true); }
123 
124 void IOHandlerStack::PrintAsync(Stream *stream, const char *s, size_t len) {
125   if (stream) {
126     std::lock_guard<std::recursive_mutex> guard(m_mutex);
127     if (m_top)
128       m_top->PrintAsync(stream, s, len);
129     else
130       stream->Write(s, len);
131   }
132 }
133 
134 IOHandlerConfirm::IOHandlerConfirm(Debugger &debugger, llvm::StringRef prompt,
135                                    bool default_response)
136     : IOHandlerEditline(
137           debugger, IOHandler::Type::Confirm,
138           nullptr, // nullptr editline_name means no history loaded/saved
139           llvm::StringRef(), // No prompt
140           llvm::StringRef(), // No continuation prompt
141           false,             // Multi-line
142           false, // Don't colorize the prompt (i.e. the confirm message.)
143           0, *this, nullptr),
144       m_default_response(default_response), m_user_response(default_response) {
145   StreamString prompt_stream;
146   prompt_stream.PutCString(prompt);
147   if (m_default_response)
148     prompt_stream.Printf(": [Y/n] ");
149   else
150     prompt_stream.Printf(": [y/N] ");
151 
152   SetPrompt(prompt_stream.GetString());
153 }
154 
155 IOHandlerConfirm::~IOHandlerConfirm() = default;
156 
157 void IOHandlerConfirm::IOHandlerComplete(IOHandler &io_handler,
158                                          CompletionRequest &request) {
159   if (request.GetRawCursorPos() != 0)
160     return;
161   request.AddCompletion(m_default_response ? "y" : "n");
162 }
163 
164 void IOHandlerConfirm::IOHandlerInputComplete(IOHandler &io_handler,
165                                               std::string &line) {
166   if (line.empty()) {
167     // User just hit enter, set the response to the default
168     m_user_response = m_default_response;
169     io_handler.SetIsDone(true);
170     return;
171   }
172 
173   if (line.size() == 1) {
174     switch (line[0]) {
175     case 'y':
176     case 'Y':
177       m_user_response = true;
178       io_handler.SetIsDone(true);
179       return;
180     case 'n':
181     case 'N':
182       m_user_response = false;
183       io_handler.SetIsDone(true);
184       return;
185     default:
186       break;
187     }
188   }
189 
190   if (line == "yes" || line == "YES" || line == "Yes") {
191     m_user_response = true;
192     io_handler.SetIsDone(true);
193   } else if (line == "no" || line == "NO" || line == "No") {
194     m_user_response = false;
195     io_handler.SetIsDone(true);
196   }
197 }
198 
199 llvm::Optional<std::string>
200 IOHandlerDelegate::IOHandlerSuggestion(IOHandler &io_handler,
201                                        llvm::StringRef line) {
202   return io_handler.GetDebugger()
203       .GetCommandInterpreter()
204       .GetAutoSuggestionForCommand(line);
205 }
206 
207 void IOHandlerDelegate::IOHandlerComplete(IOHandler &io_handler,
208                                           CompletionRequest &request) {
209   switch (m_completion) {
210   case Completion::None:
211     break;
212   case Completion::LLDBCommand:
213     io_handler.GetDebugger().GetCommandInterpreter().HandleCompletion(request);
214     break;
215   case Completion::Expression:
216     CommandCompletions::InvokeCommonCompletionCallbacks(
217         io_handler.GetDebugger().GetCommandInterpreter(),
218         CommandCompletions::eVariablePathCompletion, request, nullptr);
219     break;
220   }
221 }
222 
223 IOHandlerEditline::IOHandlerEditline(
224     Debugger &debugger, IOHandler::Type type,
225     const char *editline_name, // Used for saving history files
226     llvm::StringRef prompt, llvm::StringRef continuation_prompt,
227     bool multi_line, bool color_prompts, uint32_t line_number_start,
228     IOHandlerDelegate &delegate, repro::DataRecorder *data_recorder)
229     : IOHandlerEditline(debugger, type,
230                         FileSP(),       // Inherit input from top input reader
231                         StreamFileSP(), // Inherit output from top input reader
232                         StreamFileSP(), // Inherit error from top input reader
233                         0,              // Flags
234                         editline_name,  // Used for saving history files
235                         prompt, continuation_prompt, multi_line, color_prompts,
236                         line_number_start, delegate, data_recorder) {}
237 
238 IOHandlerEditline::IOHandlerEditline(
239     Debugger &debugger, IOHandler::Type type, const lldb::FileSP &input_sp,
240     const lldb::StreamFileSP &output_sp, const lldb::StreamFileSP &error_sp,
241     uint32_t flags,
242     const char *editline_name, // Used for saving history files
243     llvm::StringRef prompt, llvm::StringRef continuation_prompt,
244     bool multi_line, bool color_prompts, uint32_t line_number_start,
245     IOHandlerDelegate &delegate, repro::DataRecorder *data_recorder)
246     : IOHandler(debugger, type, input_sp, output_sp, error_sp, flags,
247                 data_recorder),
248 #if LLDB_ENABLE_LIBEDIT
249       m_editline_up(),
250 #endif
251       m_delegate(delegate), m_prompt(), m_continuation_prompt(),
252       m_current_lines_ptr(nullptr), m_base_line_number(line_number_start),
253       m_curr_line_idx(UINT32_MAX), m_multi_line(multi_line),
254       m_color_prompts(color_prompts), m_interrupt_exits(true) {
255   SetPrompt(prompt);
256 
257 #if LLDB_ENABLE_LIBEDIT
258   bool use_editline = false;
259 
260   use_editline = GetInputFILE() && GetOutputFILE() && GetErrorFILE() &&
261                  m_input_sp && m_input_sp->GetIsRealTerminal();
262 
263   if (use_editline) {
264     m_editline_up = std::make_unique<Editline>(editline_name, GetInputFILE(),
265                                                GetOutputFILE(), GetErrorFILE(),
266                                                m_color_prompts);
267     m_editline_up->SetIsInputCompleteCallback(
268         [this](Editline *editline, StringList &lines) {
269           return this->IsInputCompleteCallback(editline, lines);
270         });
271 
272     m_editline_up->SetAutoCompleteCallback([this](CompletionRequest &request) {
273       this->AutoCompleteCallback(request);
274     });
275 
276     if (debugger.GetUseAutosuggestion() && debugger.GetUseColor()) {
277       m_editline_up->SetSuggestionCallback([this](llvm::StringRef line) {
278         return this->SuggestionCallback(line);
279       });
280     }
281     // See if the delegate supports fixing indentation
282     const char *indent_chars = delegate.IOHandlerGetFixIndentationCharacters();
283     if (indent_chars) {
284       // The delegate does support indentation, hook it up so when any
285       // indentation character is typed, the delegate gets a chance to fix it
286       FixIndentationCallbackType f = [this](Editline *editline,
287                                             const StringList &lines,
288                                             int cursor_position) {
289         return this->FixIndentationCallback(editline, lines, cursor_position);
290       };
291       m_editline_up->SetFixIndentationCallback(std::move(f), indent_chars);
292     }
293   }
294 #endif
295   SetBaseLineNumber(m_base_line_number);
296   SetPrompt(prompt);
297   SetContinuationPrompt(continuation_prompt);
298 }
299 
300 IOHandlerEditline::~IOHandlerEditline() {
301 #if LLDB_ENABLE_LIBEDIT
302   m_editline_up.reset();
303 #endif
304 }
305 
306 void IOHandlerEditline::Activate() {
307   IOHandler::Activate();
308   m_delegate.IOHandlerActivated(*this, GetIsInteractive());
309 }
310 
311 void IOHandlerEditline::Deactivate() {
312   IOHandler::Deactivate();
313   m_delegate.IOHandlerDeactivated(*this);
314 }
315 
316 void IOHandlerEditline::TerminalSizeChanged() {
317 #if LLDB_ENABLE_LIBEDIT
318   if (m_editline_up)
319     m_editline_up->TerminalSizeChanged();
320 #endif
321 }
322 
323 // Split out a line from the buffer, if there is a full one to get.
324 static Optional<std::string> SplitLine(std::string &line_buffer) {
325   size_t pos = line_buffer.find('\n');
326   if (pos == std::string::npos)
327     return None;
328   std::string line =
329       std::string(StringRef(line_buffer.c_str(), pos).rtrim("\n\r"));
330   line_buffer = line_buffer.substr(pos + 1);
331   return line;
332 }
333 
334 // If the final line of the file ends without a end-of-line, return
335 // it as a line anyway.
336 static Optional<std::string> SplitLineEOF(std::string &line_buffer) {
337   if (llvm::all_of(line_buffer, llvm::isSpace))
338     return None;
339   std::string line = std::move(line_buffer);
340   line_buffer.clear();
341   return line;
342 }
343 
344 bool IOHandlerEditline::GetLine(std::string &line, bool &interrupted) {
345 #if LLDB_ENABLE_LIBEDIT
346   if (m_editline_up) {
347     bool b = m_editline_up->GetLine(line, interrupted);
348     if (b && m_data_recorder)
349       m_data_recorder->Record(line, true);
350     return b;
351   }
352 #endif
353 
354   line.clear();
355 
356   if (GetIsInteractive()) {
357     const char *prompt = nullptr;
358 
359     if (m_multi_line && m_curr_line_idx > 0)
360       prompt = GetContinuationPrompt();
361 
362     if (prompt == nullptr)
363       prompt = GetPrompt();
364 
365     if (prompt && prompt[0]) {
366       if (m_output_sp) {
367         m_output_sp->Printf("%s", prompt);
368         m_output_sp->Flush();
369       }
370     }
371   }
372 
373   Optional<std::string> got_line = SplitLine(m_line_buffer);
374 
375   if (!got_line && !m_input_sp) {
376     // No more input file, we are done...
377     SetIsDone(true);
378     return false;
379   }
380 
381   FILE *in = GetInputFILE();
382   char buffer[256];
383 
384   if (!got_line && !in && m_input_sp) {
385     // there is no FILE*, fall back on just reading bytes from the stream.
386     while (!got_line) {
387       size_t bytes_read = sizeof(buffer);
388       Status error = m_input_sp->Read((void *)buffer, bytes_read);
389       if (error.Success() && !bytes_read) {
390         got_line = SplitLineEOF(m_line_buffer);
391         break;
392       }
393       if (error.Fail())
394         break;
395       m_line_buffer += StringRef(buffer, bytes_read);
396       got_line = SplitLine(m_line_buffer);
397     }
398   }
399 
400   if (!got_line && in) {
401     while (!got_line) {
402       char *r = fgets(buffer, sizeof(buffer), in);
403 #ifdef _WIN32
404       // ReadFile on Windows is supposed to set ERROR_OPERATION_ABORTED
405       // according to the docs on MSDN. However, this has evidently been a
406       // known bug since Windows 8. Therefore, we can't detect if a signal
407       // interrupted in the fgets. So pressing ctrl-c causes the repl to end
408       // and the process to exit. A temporary workaround is just to attempt to
409       // fgets twice until this bug is fixed.
410       if (r == nullptr)
411         r = fgets(buffer, sizeof(buffer), in);
412       // this is the equivalent of EINTR for Windows
413       if (r == nullptr && GetLastError() == ERROR_OPERATION_ABORTED)
414         continue;
415 #endif
416       if (r == nullptr) {
417         if (ferror(in) && errno == EINTR)
418           continue;
419         if (feof(in))
420           got_line = SplitLineEOF(m_line_buffer);
421         break;
422       }
423       m_line_buffer += buffer;
424       got_line = SplitLine(m_line_buffer);
425     }
426   }
427 
428   if (got_line) {
429     line = got_line.getValue();
430     if (m_data_recorder)
431       m_data_recorder->Record(line, true);
432   }
433 
434   return (bool)got_line;
435 }
436 
437 #if LLDB_ENABLE_LIBEDIT
438 bool IOHandlerEditline::IsInputCompleteCallback(Editline *editline,
439                                                 StringList &lines) {
440   return m_delegate.IOHandlerIsInputComplete(*this, lines);
441 }
442 
443 int IOHandlerEditline::FixIndentationCallback(Editline *editline,
444                                               const StringList &lines,
445                                               int cursor_position) {
446   return m_delegate.IOHandlerFixIndentation(*this, lines, cursor_position);
447 }
448 
449 llvm::Optional<std::string>
450 IOHandlerEditline::SuggestionCallback(llvm::StringRef line) {
451   return m_delegate.IOHandlerSuggestion(*this, line);
452 }
453 
454 void IOHandlerEditline::AutoCompleteCallback(CompletionRequest &request) {
455   m_delegate.IOHandlerComplete(*this, request);
456 }
457 #endif
458 
459 const char *IOHandlerEditline::GetPrompt() {
460 #if LLDB_ENABLE_LIBEDIT
461   if (m_editline_up) {
462     return m_editline_up->GetPrompt();
463   } else {
464 #endif
465     if (m_prompt.empty())
466       return nullptr;
467 #if LLDB_ENABLE_LIBEDIT
468   }
469 #endif
470   return m_prompt.c_str();
471 }
472 
473 bool IOHandlerEditline::SetPrompt(llvm::StringRef prompt) {
474   m_prompt = std::string(prompt);
475 
476 #if LLDB_ENABLE_LIBEDIT
477   if (m_editline_up)
478     m_editline_up->SetPrompt(m_prompt.empty() ? nullptr : m_prompt.c_str());
479 #endif
480   return true;
481 }
482 
483 const char *IOHandlerEditline::GetContinuationPrompt() {
484   return (m_continuation_prompt.empty() ? nullptr
485                                         : m_continuation_prompt.c_str());
486 }
487 
488 void IOHandlerEditline::SetContinuationPrompt(llvm::StringRef prompt) {
489   m_continuation_prompt = std::string(prompt);
490 
491 #if LLDB_ENABLE_LIBEDIT
492   if (m_editline_up)
493     m_editline_up->SetContinuationPrompt(m_continuation_prompt.empty()
494                                              ? nullptr
495                                              : m_continuation_prompt.c_str());
496 #endif
497 }
498 
499 void IOHandlerEditline::SetBaseLineNumber(uint32_t line) {
500   m_base_line_number = line;
501 }
502 
503 uint32_t IOHandlerEditline::GetCurrentLineIndex() const {
504 #if LLDB_ENABLE_LIBEDIT
505   if (m_editline_up)
506     return m_editline_up->GetCurrentLine();
507 #endif
508   return m_curr_line_idx;
509 }
510 
511 bool IOHandlerEditline::GetLines(StringList &lines, bool &interrupted) {
512   m_current_lines_ptr = &lines;
513 
514   bool success = false;
515 #if LLDB_ENABLE_LIBEDIT
516   if (m_editline_up) {
517     return m_editline_up->GetLines(m_base_line_number, lines, interrupted);
518   } else {
519 #endif
520     bool done = false;
521     Status error;
522 
523     while (!done) {
524       // Show line numbers if we are asked to
525       std::string line;
526       if (m_base_line_number > 0 && GetIsInteractive()) {
527         if (m_output_sp) {
528           m_output_sp->Printf("%u%s",
529                               m_base_line_number + (uint32_t)lines.GetSize(),
530                               GetPrompt() == nullptr ? " " : "");
531         }
532       }
533 
534       m_curr_line_idx = lines.GetSize();
535 
536       bool interrupted = false;
537       if (GetLine(line, interrupted) && !interrupted) {
538         lines.AppendString(line);
539         done = m_delegate.IOHandlerIsInputComplete(*this, lines);
540       } else {
541         done = true;
542       }
543     }
544     success = lines.GetSize() > 0;
545 #if LLDB_ENABLE_LIBEDIT
546   }
547 #endif
548   return success;
549 }
550 
551 // Each IOHandler gets to run until it is done. It should read data from the
552 // "in" and place output into "out" and "err and return when done.
553 void IOHandlerEditline::Run() {
554   std::string line;
555   while (IsActive()) {
556     bool interrupted = false;
557     if (m_multi_line) {
558       StringList lines;
559       if (GetLines(lines, interrupted)) {
560         if (interrupted) {
561           m_done = m_interrupt_exits;
562           m_delegate.IOHandlerInputInterrupted(*this, line);
563 
564         } else {
565           line = lines.CopyList();
566           m_delegate.IOHandlerInputComplete(*this, line);
567         }
568       } else {
569         m_done = true;
570       }
571     } else {
572       if (GetLine(line, interrupted)) {
573         if (interrupted)
574           m_delegate.IOHandlerInputInterrupted(*this, line);
575         else
576           m_delegate.IOHandlerInputComplete(*this, line);
577       } else {
578         m_done = true;
579       }
580     }
581   }
582 }
583 
584 void IOHandlerEditline::Cancel() {
585 #if LLDB_ENABLE_LIBEDIT
586   if (m_editline_up)
587     m_editline_up->Cancel();
588 #endif
589 }
590 
591 bool IOHandlerEditline::Interrupt() {
592   // Let the delgate handle it first
593   if (m_delegate.IOHandlerInterrupt(*this))
594     return true;
595 
596 #if LLDB_ENABLE_LIBEDIT
597   if (m_editline_up)
598     return m_editline_up->Interrupt();
599 #endif
600   return false;
601 }
602 
603 void IOHandlerEditline::GotEOF() {
604 #if LLDB_ENABLE_LIBEDIT
605   if (m_editline_up)
606     m_editline_up->Interrupt();
607 #endif
608 }
609 
610 void IOHandlerEditline::PrintAsync(Stream *stream, const char *s, size_t len) {
611 #if LLDB_ENABLE_LIBEDIT
612   if (m_editline_up)
613     m_editline_up->PrintAsync(stream, s, len);
614   else
615 #endif
616   {
617 #ifdef _WIN32
618     const char *prompt = GetPrompt();
619     if (prompt) {
620       // Back up over previous prompt using Windows API
621       CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info;
622       HANDLE console_handle = GetStdHandle(STD_OUTPUT_HANDLE);
623       GetConsoleScreenBufferInfo(console_handle, &screen_buffer_info);
624       COORD coord = screen_buffer_info.dwCursorPosition;
625       coord.X -= strlen(prompt);
626       if (coord.X < 0)
627         coord.X = 0;
628       SetConsoleCursorPosition(console_handle, coord);
629     }
630 #endif
631     IOHandler::PrintAsync(stream, s, len);
632 #ifdef _WIN32
633     if (prompt)
634       IOHandler::PrintAsync(GetOutputStreamFileSP().get(), prompt,
635                             strlen(prompt));
636 #endif
637   }
638 }
639