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