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