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