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