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