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 <assert.h>
42 #include <ctype.h>
43 #include <errno.h>
44 #include <locale.h>
45 #include <stdint.h>
46 #include <stdio.h>
47 #include <string.h>
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       m_editing(false) {
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(IsInputCompleteCallback, this);
269     m_editline_up->SetAutoCompleteCallback(AutoCompleteCallback, this);
270     if (debugger.GetUseAutosuggestion() && debugger.GetUseColor())
271       m_editline_up->SetSuggestionCallback(SuggestionCallback, this);
272     // See if the delegate supports fixing indentation
273     const char *indent_chars = delegate.IOHandlerGetFixIndentationCharacters();
274     if (indent_chars) {
275       // The delegate does support indentation, hook it up so when any
276       // indentation character is typed, the delegate gets a chance to fix it
277       m_editline_up->SetFixIndentationCallback(FixIndentationCallback, this,
278                                                indent_chars);
279     }
280   }
281 #endif
282   SetBaseLineNumber(m_base_line_number);
283   SetPrompt(prompt);
284   SetContinuationPrompt(continuation_prompt);
285 }
286 
287 IOHandlerEditline::~IOHandlerEditline() {
288 #if LLDB_ENABLE_LIBEDIT
289   m_editline_up.reset();
290 #endif
291 }
292 
293 void IOHandlerEditline::Activate() {
294   IOHandler::Activate();
295   m_delegate.IOHandlerActivated(*this, GetIsInteractive());
296 }
297 
298 void IOHandlerEditline::Deactivate() {
299   IOHandler::Deactivate();
300   m_delegate.IOHandlerDeactivated(*this);
301 }
302 
303 void IOHandlerEditline::TerminalSizeChanged() {
304 #if LLDB_ENABLE_LIBEDIT
305   if (m_editline_up)
306     m_editline_up->TerminalSizeChanged();
307 #endif
308 }
309 
310 // Split out a line from the buffer, if there is a full one to get.
311 static Optional<std::string> SplitLine(std::string &line_buffer) {
312   size_t pos = line_buffer.find('\n');
313   if (pos == std::string::npos)
314     return None;
315   std::string line =
316       std::string(StringRef(line_buffer.c_str(), pos).rtrim("\n\r"));
317   line_buffer = line_buffer.substr(pos + 1);
318   return line;
319 }
320 
321 // If the final line of the file ends without a end-of-line, return
322 // it as a line anyway.
323 static Optional<std::string> SplitLineEOF(std::string &line_buffer) {
324   if (llvm::all_of(line_buffer, llvm::isSpace))
325     return None;
326   std::string line = std::move(line_buffer);
327   line_buffer.clear();
328   return line;
329 }
330 
331 bool IOHandlerEditline::GetLine(std::string &line, bool &interrupted) {
332 #if LLDB_ENABLE_LIBEDIT
333   if (m_editline_up) {
334     bool b = m_editline_up->GetLine(line, interrupted);
335     if (b && m_data_recorder)
336       m_data_recorder->Record(line, true);
337     return b;
338   }
339 #endif
340 
341   line.clear();
342 
343   if (GetIsInteractive()) {
344     const char *prompt = nullptr;
345 
346     if (m_multi_line && m_curr_line_idx > 0)
347       prompt = GetContinuationPrompt();
348 
349     if (prompt == nullptr)
350       prompt = GetPrompt();
351 
352     if (prompt && prompt[0]) {
353       if (m_output_sp) {
354         m_output_sp->Printf("%s", prompt);
355         m_output_sp->Flush();
356       }
357     }
358   }
359 
360   Optional<std::string> got_line = SplitLine(m_line_buffer);
361 
362   if (!got_line && !m_input_sp) {
363     // No more input file, we are done...
364     SetIsDone(true);
365     return false;
366   }
367 
368   FILE *in = GetInputFILE();
369   char buffer[256];
370 
371   if (!got_line && !in && m_input_sp) {
372     // there is no FILE*, fall back on just reading bytes from the stream.
373     while (!got_line) {
374       size_t bytes_read = sizeof(buffer);
375       Status error = m_input_sp->Read((void *)buffer, bytes_read);
376       if (error.Success() && !bytes_read) {
377         got_line = SplitLineEOF(m_line_buffer);
378         break;
379       }
380       if (error.Fail())
381         break;
382       m_line_buffer += StringRef(buffer, bytes_read);
383       got_line = SplitLine(m_line_buffer);
384     }
385   }
386 
387   if (!got_line && in) {
388     m_editing = true;
389     while (!got_line) {
390       char *r = fgets(buffer, sizeof(buffer), in);
391 #ifdef _WIN32
392       // ReadFile on Windows is supposed to set ERROR_OPERATION_ABORTED
393       // according to the docs on MSDN. However, this has evidently been a
394       // known bug since Windows 8. Therefore, we can't detect if a signal
395       // interrupted in the fgets. So pressing ctrl-c causes the repl to end
396       // and the process to exit. A temporary workaround is just to attempt to
397       // fgets twice until this bug is fixed.
398       if (r == nullptr)
399         r = fgets(buffer, sizeof(buffer), in);
400       // this is the equivalent of EINTR for Windows
401       if (r == nullptr && GetLastError() == ERROR_OPERATION_ABORTED)
402         continue;
403 #endif
404       if (r == nullptr) {
405         if (ferror(in) && errno == EINTR)
406           continue;
407         if (feof(in))
408           got_line = SplitLineEOF(m_line_buffer);
409         break;
410       }
411       m_line_buffer += buffer;
412       got_line = SplitLine(m_line_buffer);
413     }
414     m_editing = false;
415   }
416 
417   if (got_line) {
418     line = got_line.getValue();
419     if (m_data_recorder)
420       m_data_recorder->Record(line, true);
421   }
422 
423   return (bool)got_line;
424 }
425 
426 #if LLDB_ENABLE_LIBEDIT
427 bool IOHandlerEditline::IsInputCompleteCallback(Editline *editline,
428                                                 StringList &lines,
429                                                 void *baton) {
430   IOHandlerEditline *editline_reader = (IOHandlerEditline *)baton;
431   return editline_reader->m_delegate.IOHandlerIsInputComplete(*editline_reader,
432                                                               lines);
433 }
434 
435 int IOHandlerEditline::FixIndentationCallback(Editline *editline,
436                                               const StringList &lines,
437                                               int cursor_position,
438                                               void *baton) {
439   IOHandlerEditline *editline_reader = (IOHandlerEditline *)baton;
440   return editline_reader->m_delegate.IOHandlerFixIndentation(
441       *editline_reader, lines, cursor_position);
442 }
443 
444 llvm::Optional<std::string>
445 IOHandlerEditline::SuggestionCallback(llvm::StringRef line, void *baton) {
446   IOHandlerEditline *editline_reader = static_cast<IOHandlerEditline *>(baton);
447   if (editline_reader)
448     return editline_reader->m_delegate.IOHandlerSuggestion(*editline_reader,
449                                                            line);
450 
451   return llvm::None;
452 }
453 
454 void IOHandlerEditline::AutoCompleteCallback(CompletionRequest &request,
455                                              void *baton) {
456   IOHandlerEditline *editline_reader = (IOHandlerEditline *)baton;
457   if (editline_reader)
458     editline_reader->m_delegate.IOHandlerComplete(*editline_reader, request);
459 }
460 #endif
461 
462 const char *IOHandlerEditline::GetPrompt() {
463 #if LLDB_ENABLE_LIBEDIT
464   if (m_editline_up) {
465     return m_editline_up->GetPrompt();
466   } else {
467 #endif
468     if (m_prompt.empty())
469       return nullptr;
470 #if LLDB_ENABLE_LIBEDIT
471   }
472 #endif
473   return m_prompt.c_str();
474 }
475 
476 bool IOHandlerEditline::SetPrompt(llvm::StringRef prompt) {
477   m_prompt = std::string(prompt);
478 
479 #if LLDB_ENABLE_LIBEDIT
480   if (m_editline_up)
481     m_editline_up->SetPrompt(m_prompt.empty() ? nullptr : m_prompt.c_str());
482 #endif
483   return true;
484 }
485 
486 const char *IOHandlerEditline::GetContinuationPrompt() {
487   return (m_continuation_prompt.empty() ? nullptr
488                                         : m_continuation_prompt.c_str());
489 }
490 
491 void IOHandlerEditline::SetContinuationPrompt(llvm::StringRef prompt) {
492   m_continuation_prompt = std::string(prompt);
493 
494 #if LLDB_ENABLE_LIBEDIT
495   if (m_editline_up)
496     m_editline_up->SetContinuationPrompt(m_continuation_prompt.empty()
497                                              ? nullptr
498                                              : m_continuation_prompt.c_str());
499 #endif
500 }
501 
502 void IOHandlerEditline::SetBaseLineNumber(uint32_t line) {
503   m_base_line_number = line;
504 }
505 
506 uint32_t IOHandlerEditline::GetCurrentLineIndex() const {
507 #if LLDB_ENABLE_LIBEDIT
508   if (m_editline_up)
509     return m_editline_up->GetCurrentLine();
510 #endif
511   return m_curr_line_idx;
512 }
513 
514 bool IOHandlerEditline::GetLines(StringList &lines, bool &interrupted) {
515   m_current_lines_ptr = &lines;
516 
517   bool success = false;
518 #if LLDB_ENABLE_LIBEDIT
519   if (m_editline_up) {
520     return m_editline_up->GetLines(m_base_line_number, lines, interrupted);
521   } else {
522 #endif
523     bool done = false;
524     Status error;
525 
526     while (!done) {
527       // Show line numbers if we are asked to
528       std::string line;
529       if (m_base_line_number > 0 && GetIsInteractive()) {
530         if (m_output_sp) {
531           m_output_sp->Printf("%u%s",
532                               m_base_line_number + (uint32_t)lines.GetSize(),
533                               GetPrompt() == nullptr ? " " : "");
534         }
535       }
536 
537       m_curr_line_idx = lines.GetSize();
538 
539       bool interrupted = false;
540       if (GetLine(line, interrupted) && !interrupted) {
541         lines.AppendString(line);
542         done = m_delegate.IOHandlerIsInputComplete(*this, lines);
543       } else {
544         done = true;
545       }
546     }
547     success = lines.GetSize() > 0;
548 #if LLDB_ENABLE_LIBEDIT
549   }
550 #endif
551   return success;
552 }
553 
554 // Each IOHandler gets to run until it is done. It should read data from the
555 // "in" and place output into "out" and "err and return when done.
556 void IOHandlerEditline::Run() {
557   std::string line;
558   while (IsActive()) {
559     bool interrupted = false;
560     if (m_multi_line) {
561       StringList lines;
562       if (GetLines(lines, interrupted)) {
563         if (interrupted) {
564           m_done = m_interrupt_exits;
565           m_delegate.IOHandlerInputInterrupted(*this, line);
566 
567         } else {
568           line = lines.CopyList();
569           m_delegate.IOHandlerInputComplete(*this, line);
570         }
571       } else {
572         m_done = true;
573       }
574     } else {
575       if (GetLine(line, interrupted)) {
576         if (interrupted)
577           m_delegate.IOHandlerInputInterrupted(*this, line);
578         else
579           m_delegate.IOHandlerInputComplete(*this, line);
580       } else {
581         m_done = true;
582       }
583     }
584   }
585 }
586 
587 void IOHandlerEditline::Cancel() {
588 #if LLDB_ENABLE_LIBEDIT
589   if (m_editline_up)
590     m_editline_up->Cancel();
591 #endif
592 }
593 
594 bool IOHandlerEditline::Interrupt() {
595   // Let the delgate handle it first
596   if (m_delegate.IOHandlerInterrupt(*this))
597     return true;
598 
599 #if LLDB_ENABLE_LIBEDIT
600   if (m_editline_up)
601     return m_editline_up->Interrupt();
602 #endif
603   return false;
604 }
605 
606 void IOHandlerEditline::GotEOF() {
607 #if LLDB_ENABLE_LIBEDIT
608   if (m_editline_up)
609     m_editline_up->Interrupt();
610 #endif
611 }
612 
613 void IOHandlerEditline::PrintAsync(Stream *stream, const char *s, size_t len) {
614 #if LLDB_ENABLE_LIBEDIT
615   if (m_editline_up)
616     m_editline_up->PrintAsync(stream, s, len);
617   else
618 #endif
619   {
620 #ifdef _WIN32
621     const char *prompt = GetPrompt();
622     if (prompt) {
623       // Back up over previous prompt using Windows API
624       CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info;
625       HANDLE console_handle = GetStdHandle(STD_OUTPUT_HANDLE);
626       GetConsoleScreenBufferInfo(console_handle, &screen_buffer_info);
627       COORD coord = screen_buffer_info.dwCursorPosition;
628       coord.X -= strlen(prompt);
629       if (coord.X < 0)
630         coord.X = 0;
631       SetConsoleCursorPosition(console_handle, coord);
632     }
633 #endif
634     IOHandler::PrintAsync(stream, s, len);
635 #ifdef _WIN32
636     if (prompt)
637       IOHandler::PrintAsync(GetOutputStreamFileSP().get(), prompt,
638                             strlen(prompt));
639 #endif
640   }
641 }
642