1 //===-- REPL.cpp ------------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // C Includes
11 // C++ Includes
12 // Other libraries and framework includes
13 // Project includes
14 #include "lldb/Expression/REPL.h"
15 #include "lldb/Core/Debugger.h"
16 #include "lldb/Core/PluginManager.h"
17 #include "lldb/Core/StreamFile.h"
18 #include "lldb/Expression/ExpressionVariable.h"
19 #include "lldb/Expression/UserExpression.h"
20 #include "lldb/Host/HostInfo.h"
21 #include "lldb/Interpreter/CommandInterpreter.h"
22 #include "lldb/Interpreter/CommandReturnObject.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Target/Thread.h"
25 #include "lldb/Utility/AnsiTerminal.h"
26 
27 using namespace lldb_private;
28 
29 REPL::REPL(LLVMCastKind kind, Target &target) : m_target(target), m_kind(kind) {
30   // Make sure all option values have sane defaults
31   Debugger &debugger = m_target.GetDebugger();
32   auto exe_ctx = debugger.GetCommandInterpreter().GetExecutionContext();
33   m_format_options.OptionParsingStarting(&exe_ctx);
34   m_varobj_options.OptionParsingStarting(&exe_ctx);
35   m_command_options.OptionParsingStarting(&exe_ctx);
36 
37   // Default certain settings for REPL regardless of the global settings.
38   m_command_options.unwind_on_error = false;
39   m_command_options.ignore_breakpoints = false;
40   m_command_options.debug = false;
41 }
42 
43 REPL::~REPL() = default;
44 
45 lldb::REPLSP REPL::Create(Status &err, lldb::LanguageType language,
46                           Debugger *debugger, Target *target,
47                           const char *repl_options) {
48   uint32_t idx = 0;
49   lldb::REPLSP ret;
50 
51   while (REPLCreateInstance create_instance =
52              PluginManager::GetREPLCreateCallbackAtIndex(idx++)) {
53     ret = (*create_instance)(err, language, debugger, target, repl_options);
54     if (ret) {
55       break;
56     }
57   }
58 
59   return ret;
60 }
61 
62 std::string REPL::GetSourcePath() {
63   ConstString file_basename = GetSourceFileBasename();
64 
65   FileSpec tmpdir_file_spec;
66   if (HostInfo::GetLLDBPath(lldb::ePathTypeLLDBTempSystemDir,
67                             tmpdir_file_spec)) {
68     tmpdir_file_spec.GetFilename().SetCString(file_basename.AsCString());
69     m_repl_source_path = tmpdir_file_spec.GetPath();
70   } else {
71     tmpdir_file_spec = FileSpec("/tmp", false);
72     tmpdir_file_spec.AppendPathComponent(file_basename.AsCString());
73   }
74 
75   return tmpdir_file_spec.GetPath();
76 }
77 
78 lldb::IOHandlerSP REPL::GetIOHandler() {
79   if (!m_io_handler_sp) {
80     Debugger &debugger = m_target.GetDebugger();
81     m_io_handler_sp.reset(
82         new IOHandlerEditline(debugger, IOHandler::Type::REPL,
83                               "lldb-repl", // Name of input reader for history
84                               llvm::StringRef("> "), // prompt
85                               llvm::StringRef(". "), // Continuation prompt
86                               true,                  // Multi-line
87                               true, // The REPL prompt is always colored
88                               1,    // Line number
89                               *this));
90 
91     // Don't exit if CTRL+C is pressed
92     static_cast<IOHandlerEditline *>(m_io_handler_sp.get())
93         ->SetInterruptExits(false);
94 
95     if (m_io_handler_sp->GetIsInteractive() &&
96         m_io_handler_sp->GetIsRealTerminal()) {
97       m_indent_str.assign(debugger.GetTabSize(), ' ');
98       m_enable_auto_indent = debugger.GetAutoIndent();
99     } else {
100       m_indent_str.clear();
101       m_enable_auto_indent = false;
102     }
103   }
104   return m_io_handler_sp;
105 }
106 
107 void REPL::IOHandlerActivated(IOHandler &io_handler) {
108   lldb::ProcessSP process_sp = m_target.GetProcessSP();
109   if (process_sp && process_sp->IsAlive())
110     return;
111   lldb::StreamFileSP error_sp(io_handler.GetErrorStreamFile());
112   error_sp->Printf("REPL requires a running target process.\n");
113   io_handler.SetIsDone(true);
114 }
115 
116 bool REPL::IOHandlerInterrupt(IOHandler &io_handler) { return false; }
117 
118 void REPL::IOHandlerInputInterrupted(IOHandler &io_handler, std::string &line) {
119 }
120 
121 const char *REPL::IOHandlerGetFixIndentationCharacters() {
122   return (m_enable_auto_indent ? GetAutoIndentCharacters() : nullptr);
123 }
124 
125 ConstString REPL::IOHandlerGetControlSequence(char ch) {
126   if (ch == 'd')
127     return ConstString(":quit\n");
128   return ConstString();
129 }
130 
131 const char *REPL::IOHandlerGetCommandPrefix() { return ":"; }
132 
133 const char *REPL::IOHandlerGetHelpPrologue() {
134   return "\nThe REPL (Read-Eval-Print-Loop) acts like an interpreter.  "
135          "Valid statements, expressions, and declarations are immediately "
136          "compiled and executed.\n\n"
137          "The complete set of LLDB debugging commands are also available as "
138          "described below.  Commands "
139          "must be prefixed with a colon at the REPL prompt (:quit for "
140          "example.)  Typing just a colon "
141          "followed by return will switch to the LLDB prompt.\n\n";
142 }
143 
144 bool REPL::IOHandlerIsInputComplete(IOHandler &io_handler, StringList &lines) {
145   // Check for meta command
146   const size_t num_lines = lines.GetSize();
147   if (num_lines == 1) {
148     const char *first_line = lines.GetStringAtIndex(0);
149     if (first_line[0] == ':')
150       return true; // Meta command is a single line where that starts with ':'
151   }
152 
153   // Check if REPL input is done
154   std::string source_string(lines.CopyList());
155   return SourceIsComplete(source_string);
156 }
157 
158 int REPL::CalculateActualIndentation(const StringList &lines) {
159   std::string last_line = lines[lines.GetSize() - 1];
160 
161   int actual_indent = 0;
162   for (char &ch : last_line) {
163     if (ch != ' ')
164       break;
165     ++actual_indent;
166   }
167 
168   return actual_indent;
169 }
170 
171 int REPL::IOHandlerFixIndentation(IOHandler &io_handler,
172                                   const StringList &lines,
173                                   int cursor_position) {
174   if (!m_enable_auto_indent)
175     return 0;
176 
177   if (!lines.GetSize()) {
178     return 0;
179   }
180 
181   int tab_size = io_handler.GetDebugger().GetTabSize();
182 
183   lldb::offset_t desired_indent =
184       GetDesiredIndentation(lines, cursor_position, tab_size);
185 
186   int actual_indent = REPL::CalculateActualIndentation(lines);
187 
188   if (desired_indent == LLDB_INVALID_OFFSET)
189     return 0;
190 
191   return (int)desired_indent - actual_indent;
192 }
193 
194 void REPL::IOHandlerInputComplete(IOHandler &io_handler, std::string &code) {
195   lldb::StreamFileSP output_sp(io_handler.GetOutputStreamFile());
196   lldb::StreamFileSP error_sp(io_handler.GetErrorStreamFile());
197   bool extra_line = false;
198   bool did_quit = false;
199 
200   if (code.empty()) {
201     m_code.AppendString("");
202     static_cast<IOHandlerEditline &>(io_handler)
203         .SetBaseLineNumber(m_code.GetSize() + 1);
204   } else {
205     Debugger &debugger = m_target.GetDebugger();
206     CommandInterpreter &ci = debugger.GetCommandInterpreter();
207     extra_line = ci.GetSpaceReplPrompts();
208 
209     ExecutionContext exe_ctx(m_target.GetProcessSP()
210                                  ->GetThreadList()
211                                  .GetSelectedThread()
212                                  ->GetSelectedFrame()
213                                  .get());
214 
215     lldb::ProcessSP process_sp(exe_ctx.GetProcessSP());
216 
217     if (code[0] == ':') {
218       // Meta command
219       // Strip the ':'
220       code.erase(0, 1);
221       if (Args::StripSpaces(code)) {
222         // "lldb" was followed by arguments, so just execute the command dump
223         // the results
224 
225         // Turn off prompt on quit in case the user types ":quit"
226         const bool saved_prompt_on_quit = ci.GetPromptOnQuit();
227         if (saved_prompt_on_quit)
228           ci.SetPromptOnQuit(false);
229 
230         // Execute the command
231         CommandReturnObject result;
232         result.SetImmediateOutputStream(output_sp);
233         result.SetImmediateErrorStream(error_sp);
234         ci.HandleCommand(code.c_str(), eLazyBoolNo, result);
235 
236         if (saved_prompt_on_quit)
237           ci.SetPromptOnQuit(true);
238 
239         if (result.GetStatus() == lldb::eReturnStatusQuit) {
240           did_quit = true;
241           io_handler.SetIsDone(true);
242           if (debugger.CheckTopIOHandlerTypes(
243                   IOHandler::Type::REPL, IOHandler::Type::CommandInterpreter)) {
244             // We typed "quit" or an alias to quit so we need to check if the
245             // command interpreter is above us and tell it that it is done as
246             // well so we don't drop back into the command interpreter if we
247             // have already quit
248             lldb::IOHandlerSP io_handler_sp(ci.GetIOHandler());
249             if (io_handler_sp)
250               io_handler_sp->SetIsDone(true);
251           }
252         }
253       } else {
254         // ":" was followed by no arguments, so push the LLDB command prompt
255         if (debugger.CheckTopIOHandlerTypes(
256                 IOHandler::Type::REPL, IOHandler::Type::CommandInterpreter)) {
257           // If the user wants to get back to the command interpreter and the
258           // command interpreter is what launched the REPL, then just let the
259           // REPL exit and fall back to the command interpreter.
260           io_handler.SetIsDone(true);
261         } else {
262           // The REPL wasn't launched the by the command interpreter, it is the
263           // base IOHandler, so we need to get the command interpreter and
264           lldb::IOHandlerSP io_handler_sp(ci.GetIOHandler());
265           if (io_handler_sp) {
266             io_handler_sp->SetIsDone(false);
267             debugger.PushIOHandler(ci.GetIOHandler());
268           }
269         }
270       }
271     } else {
272       // Unwind any expression we might have been running in case our REPL
273       // expression crashed and the user was looking around
274       if (m_dedicated_repl_mode) {
275         Thread *thread = exe_ctx.GetThreadPtr();
276         if (thread && thread->UnwindInnermostExpression().Success()) {
277           thread->SetSelectedFrameByIndex(0, false);
278           exe_ctx.SetFrameSP(thread->GetSelectedFrame());
279         }
280       }
281 
282       const bool colorize_err = error_sp->GetFile().GetIsTerminalWithColors();
283 
284       EvaluateExpressionOptions expr_options;
285       expr_options.SetCoerceToId(m_varobj_options.use_objc);
286       expr_options.SetUnwindOnError(m_command_options.unwind_on_error);
287       expr_options.SetIgnoreBreakpoints(m_command_options.ignore_breakpoints);
288       expr_options.SetKeepInMemory(true);
289       expr_options.SetUseDynamic(m_varobj_options.use_dynamic);
290       expr_options.SetTryAllThreads(m_command_options.try_all_threads);
291       expr_options.SetGenerateDebugInfo(true);
292       expr_options.SetREPLEnabled(true);
293       expr_options.SetColorizeErrors(colorize_err);
294       expr_options.SetPoundLine(m_repl_source_path.c_str(),
295                                 m_code.GetSize() + 1);
296       if (m_command_options.timeout > 0)
297         expr_options.SetTimeout(std::chrono::microseconds(m_command_options.timeout));
298       else
299         expr_options.SetTimeout(llvm::None);
300 
301       expr_options.SetLanguage(GetLanguage());
302 
303       PersistentExpressionState *persistent_state =
304           m_target.GetPersistentExpressionStateForLanguage(GetLanguage());
305 
306       const size_t var_count_before = persistent_state->GetSize();
307 
308       const char *expr_prefix = nullptr;
309       lldb::ValueObjectSP result_valobj_sp;
310       Status error;
311       lldb::ModuleSP jit_module_sp;
312       lldb::ExpressionResults execution_results =
313           UserExpression::Evaluate(exe_ctx, expr_options, code.c_str(),
314                                    expr_prefix, result_valobj_sp, error,
315                                    0,       // Line offset
316                                    nullptr, // Fixed Expression
317                                    &jit_module_sp);
318 
319       // CommandInterpreter &ci = debugger.GetCommandInterpreter();
320 
321       if (process_sp && process_sp->IsAlive()) {
322         bool add_to_code = true;
323         bool handled = false;
324         if (result_valobj_sp) {
325           lldb::Format format = m_format_options.GetFormat();
326 
327           if (result_valobj_sp->GetError().Success()) {
328             handled |= PrintOneVariable(debugger, output_sp, result_valobj_sp);
329           } else if (result_valobj_sp->GetError().GetError() ==
330                      UserExpression::kNoResult) {
331             if (format != lldb::eFormatVoid && debugger.GetNotifyVoid()) {
332               error_sp->PutCString("(void)\n");
333               handled = true;
334             }
335           }
336         }
337 
338         if (debugger.GetPrintDecls()) {
339           for (size_t vi = var_count_before, ve = persistent_state->GetSize();
340                vi != ve; ++vi) {
341             lldb::ExpressionVariableSP persistent_var_sp =
342                 persistent_state->GetVariableAtIndex(vi);
343             lldb::ValueObjectSP valobj_sp = persistent_var_sp->GetValueObject();
344 
345             PrintOneVariable(debugger, output_sp, valobj_sp,
346                              persistent_var_sp.get());
347           }
348         }
349 
350         if (!handled) {
351           bool useColors = error_sp->GetFile().GetIsTerminalWithColors();
352           switch (execution_results) {
353           case lldb::eExpressionSetupError:
354           case lldb::eExpressionParseError:
355             add_to_code = false;
356             LLVM_FALLTHROUGH;
357           case lldb::eExpressionDiscarded:
358             error_sp->Printf("%s\n", error.AsCString());
359             break;
360 
361           case lldb::eExpressionCompleted:
362             break;
363           case lldb::eExpressionInterrupted:
364             if (useColors) {
365               error_sp->Printf(ANSI_ESCAPE1(ANSI_FG_COLOR_RED));
366               error_sp->Printf(ANSI_ESCAPE1(ANSI_CTRL_BOLD));
367             }
368             error_sp->Printf("Execution interrupted. ");
369             if (useColors)
370               error_sp->Printf(ANSI_ESCAPE1(ANSI_CTRL_NORMAL));
371             error_sp->Printf("Enter code to recover and continue.\nEnter LLDB "
372                              "commands to investigate (type :help for "
373                              "assistance.)\n");
374             break;
375 
376           case lldb::eExpressionHitBreakpoint:
377             // Breakpoint was hit, drop into LLDB command interpreter
378             if (useColors) {
379               error_sp->Printf(ANSI_ESCAPE1(ANSI_FG_COLOR_RED));
380               error_sp->Printf(ANSI_ESCAPE1(ANSI_CTRL_BOLD));
381             }
382             output_sp->Printf("Execution stopped at breakpoint.  ");
383             if (useColors)
384               error_sp->Printf(ANSI_ESCAPE1(ANSI_CTRL_NORMAL));
385             output_sp->Printf("Enter LLDB commands to investigate (type help "
386                               "for assistance.)\n");
387             {
388               lldb::IOHandlerSP io_handler_sp(ci.GetIOHandler());
389               if (io_handler_sp) {
390                 io_handler_sp->SetIsDone(false);
391                 debugger.PushIOHandler(ci.GetIOHandler());
392               }
393             }
394             break;
395 
396           case lldb::eExpressionTimedOut:
397             error_sp->Printf("error: timeout\n");
398             if (error.AsCString())
399               error_sp->Printf("error: %s\n", error.AsCString());
400             break;
401           case lldb::eExpressionResultUnavailable:
402             // Shoulnd't happen???
403             error_sp->Printf("error: could not fetch result -- %s\n",
404                              error.AsCString());
405             break;
406           case lldb::eExpressionStoppedForDebug:
407             // Shoulnd't happen???
408             error_sp->Printf("error: stopped for debug -- %s\n",
409                              error.AsCString());
410             break;
411           }
412         }
413 
414         if (add_to_code) {
415           const uint32_t new_default_line = m_code.GetSize() + 1;
416 
417           m_code.SplitIntoLines(code);
418 
419           // Update our code on disk
420           if (!m_repl_source_path.empty()) {
421             lldb_private::File file(m_repl_source_path.c_str(),
422                                     File::eOpenOptionWrite |
423                                         File::eOpenOptionTruncate |
424                                         File::eOpenOptionCanCreate,
425                                     lldb::eFilePermissionsFileDefault);
426             std::string code(m_code.CopyList());
427             code.append(1, '\n');
428             size_t bytes_written = code.size();
429             file.Write(code.c_str(), bytes_written);
430             file.Close();
431 
432             // Now set the default file and line to the REPL source file
433             m_target.GetSourceManager().SetDefaultFileAndLine(
434                 FileSpec(m_repl_source_path, false), new_default_line);
435           }
436           static_cast<IOHandlerEditline &>(io_handler)
437               .SetBaseLineNumber(m_code.GetSize() + 1);
438         }
439         if (extra_line) {
440           fprintf(output_sp->GetFile().GetStream(), "\n");
441         }
442       }
443     }
444 
445     // Don't complain about the REPL process going away if we are in the
446     // process of quitting.
447     if (!did_quit && (!process_sp || !process_sp->IsAlive())) {
448       error_sp->Printf(
449           "error: REPL process is no longer alive, exiting REPL\n");
450       io_handler.SetIsDone(true);
451     }
452   }
453 }
454 
455 int REPL::IOHandlerComplete(IOHandler &io_handler, const char *current_line,
456                             const char *cursor, const char *last_char,
457                             int skip_first_n_matches, int max_matches,
458                             StringList &matches) {
459   matches.Clear();
460 
461   llvm::StringRef line(current_line, cursor - current_line);
462 
463   // Complete an LLDB command if the first character is a colon...
464   if (!line.empty() && line[0] == ':') {
465     Debugger &debugger = m_target.GetDebugger();
466 
467     // auto complete LLDB commands
468     const char *lldb_current_line = line.substr(1).data();
469     return debugger.GetCommandInterpreter().HandleCompletion(
470         lldb_current_line, cursor, last_char, skip_first_n_matches, max_matches,
471         matches);
472   }
473 
474   // Strip spaces from the line and see if we had only spaces
475   line = line.ltrim();
476   if (line.empty()) {
477     // Only spaces on this line, so just indent
478     matches.AppendString(m_indent_str);
479     return 1;
480   }
481 
482   std::string current_code;
483   current_code.append(m_code.CopyList());
484 
485   IOHandlerEditline &editline = static_cast<IOHandlerEditline &>(io_handler);
486   const StringList *current_lines = editline.GetCurrentLines();
487   if (current_lines) {
488     const uint32_t current_line_idx = editline.GetCurrentLineIndex();
489 
490     if (current_line_idx < current_lines->GetSize()) {
491       for (uint32_t i = 0; i < current_line_idx; ++i) {
492         const char *line_cstr = current_lines->GetStringAtIndex(i);
493         if (line_cstr) {
494           current_code.append("\n");
495           current_code.append(line_cstr);
496         }
497       }
498     }
499   }
500 
501   if (cursor > current_line) {
502     current_code.append("\n");
503     current_code.append(current_line, cursor - current_line);
504   }
505 
506   return CompleteCode(current_code, matches);
507 }
508 
509 bool QuitCommandOverrideCallback(void *baton, const char **argv) {
510   Target *target = (Target *)baton;
511   lldb::ProcessSP process_sp(target->GetProcessSP());
512   if (process_sp) {
513     process_sp->Destroy(false);
514     process_sp->GetTarget().GetDebugger().ClearIOHandlers();
515   }
516   return false;
517 }
518 
519 Status REPL::RunLoop() {
520   Status error;
521 
522   error = DoInitialization();
523   m_repl_source_path = GetSourcePath();
524 
525   if (!error.Success())
526     return error;
527 
528   Debugger &debugger = m_target.GetDebugger();
529 
530   lldb::IOHandlerSP io_handler_sp(GetIOHandler());
531 
532   FileSpec save_default_file;
533   uint32_t save_default_line = 0;
534 
535   if (!m_repl_source_path.empty()) {
536     // Save the current default file and line
537     m_target.GetSourceManager().GetDefaultFileAndLine(save_default_file,
538                                                       save_default_line);
539   }
540 
541   debugger.PushIOHandler(io_handler_sp);
542 
543   // Check if we are in dedicated REPL mode where LLDB was start with the "--
544   // repl" option from the command line. Currently we know this by checking if
545   // the debugger already has a IOHandler thread.
546   if (!debugger.HasIOHandlerThread()) {
547     // The debugger doesn't have an existing IOHandler thread, so this must be
548     // dedicated REPL mode...
549     m_dedicated_repl_mode = true;
550     debugger.StartIOHandlerThread();
551     llvm::StringRef command_name_str("quit");
552     CommandObject *cmd_obj =
553         debugger.GetCommandInterpreter().GetCommandObjectForCommand(
554             command_name_str);
555     if (cmd_obj) {
556       assert(command_name_str.empty());
557       cmd_obj->SetOverrideCallback(QuitCommandOverrideCallback, &m_target);
558     }
559   }
560 
561   // Wait for the REPL command interpreter to get popped
562   io_handler_sp->WaitForPop();
563 
564   if (m_dedicated_repl_mode) {
565     // If we were in dedicated REPL mode we would have started the IOHandler
566     // thread, and we should kill our process
567     lldb::ProcessSP process_sp = m_target.GetProcessSP();
568     if (process_sp && process_sp->IsAlive())
569       process_sp->Destroy(false);
570 
571     // Wait for the IO handler thread to exit (TODO: don't do this if the IO
572     // handler thread already exists...)
573     debugger.JoinIOHandlerThread();
574   }
575 
576   // Restore the default file and line
577   if (save_default_file && save_default_line != 0)
578     m_target.GetSourceManager().SetDefaultFileAndLine(save_default_file,
579                                                       save_default_line);
580   return error;
581 }
582