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