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