1 //===-- Driver.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 #include "Driver.h"
11 
12 #include <algorithm>
13 #include <atomic>
14 #include <bitset>
15 #include <csignal>
16 #include <fcntl.h>
17 #include <limits.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 
22 // Includes for pipe()
23 #if defined(_WIN32)
24 #include <fcntl.h>
25 #include <io.h>
26 #else
27 #include <unistd.h>
28 #endif
29 
30 #include <string>
31 
32 #include "lldb/API/SBBreakpoint.h"
33 #include "lldb/API/SBCommandInterpreter.h"
34 #include "lldb/API/SBCommandReturnObject.h"
35 #include "lldb/API/SBCommunication.h"
36 #include "lldb/API/SBDebugger.h"
37 #include "lldb/API/SBEvent.h"
38 #include "lldb/API/SBHostOS.h"
39 #include "lldb/API/SBLanguageRuntime.h"
40 #include "lldb/API/SBListener.h"
41 #include "lldb/API/SBProcess.h"
42 #include "lldb/API/SBStream.h"
43 #include "lldb/API/SBStringList.h"
44 #include "lldb/API/SBTarget.h"
45 #include "lldb/API/SBThread.h"
46 #include "llvm/ADT/StringRef.h"
47 #include "llvm/Support/ConvertUTF.h"
48 #include "llvm/Support/PrettyStackTrace.h"
49 #include "llvm/Support/Signals.h"
50 #include <thread>
51 #include <utility>
52 
53 #if !defined(__APPLE__)
54 #include "llvm/Support/DataTypes.h"
55 #endif
56 
57 using namespace lldb;
58 
59 static void reset_stdin_termios();
60 static bool g_old_stdin_termios_is_valid = false;
61 static struct termios g_old_stdin_termios;
62 
63 static Driver *g_driver = NULL;
64 
65 // In the Driver::MainLoop, we change the terminal settings.  This function is
66 // added as an atexit handler to make sure we clean them up.
67 static void reset_stdin_termios() {
68   if (g_old_stdin_termios_is_valid) {
69     g_old_stdin_termios_is_valid = false;
70     ::tcsetattr(STDIN_FILENO, TCSANOW, &g_old_stdin_termios);
71   }
72 }
73 
74 typedef struct {
75   uint32_t usage_mask; // Used to mark options that can be used together.  If (1
76                        // << n & usage_mask) != 0
77                        // then this option belongs to option set n.
78   bool required;       // This option is required (in the current usage level)
79   const char *long_option; // Full name for this option.
80   int short_option;        // Single character for this option.
81   int option_has_arg; // no_argument, required_argument or optional_argument
82   uint32_t completion_type; // Cookie the option class can use to do define the
83                             // argument completion.
84   lldb::CommandArgumentType argument_type; // Type of argument this option takes
85   const char *usage_text; // Full text explaining what this options does and
86                           // what (if any) argument to
87                           // pass it.
88 } OptionDefinition;
89 
90 #define LLDB_3_TO_5 LLDB_OPT_SET_3 | LLDB_OPT_SET_4 | LLDB_OPT_SET_5
91 #define LLDB_4_TO_5 LLDB_OPT_SET_4 | LLDB_OPT_SET_5
92 
93 static constexpr OptionDefinition g_options[] = {
94     {LLDB_OPT_SET_1, true, "help", 'h', no_argument, 0, eArgTypeNone,
95      "Prints out the usage information for the LLDB debugger."},
96     {LLDB_OPT_SET_2, true, "version", 'v', no_argument, 0, eArgTypeNone,
97      "Prints out the current version number of the LLDB debugger."},
98     {LLDB_OPT_SET_3, true, "arch", 'a', required_argument, 0,
99      eArgTypeArchitecture,
100      "Tells the debugger to use the specified architecture when starting and "
101      "running the program.  <architecture> must "
102      "be one of the architectures for which the program was compiled."},
103     {LLDB_OPT_SET_3, true, "file", 'f', required_argument, 0, eArgTypeFilename,
104      "Tells the debugger to use the file <filename> as the program to be "
105      "debugged."},
106     {LLDB_OPT_SET_3, false, "core", 'c', required_argument, 0, eArgTypeFilename,
107      "Tells the debugger to use the fullpath to <path> as the core file."},
108     {LLDB_OPT_SET_5, true, "attach-pid", 'p', required_argument, 0, eArgTypePid,
109      "Tells the debugger to attach to a process with the given pid."},
110     {LLDB_OPT_SET_4, true, "attach-name", 'n', required_argument, 0,
111      eArgTypeProcessName,
112      "Tells the debugger to attach to a process with the given name."},
113     {LLDB_OPT_SET_4, true, "wait-for", 'w', no_argument, 0, eArgTypeNone,
114      "Tells the debugger to wait for a process with the given pid or name to "
115      "launch before attaching."},
116     {LLDB_3_TO_5, false, "source", 's', required_argument, 0, eArgTypeFilename,
117      "Tells the debugger to read in and execute the lldb commands in the given "
118      "file, after any file provided on the command line has been loaded."},
119     {LLDB_3_TO_5, false, "one-line", 'o', required_argument, 0, eArgTypeNone,
120      "Tells the debugger to execute this one-line lldb command after any file "
121      "provided on the command line has been loaded."},
122     {LLDB_3_TO_5, false, "source-before-file", 'S', required_argument, 0,
123      eArgTypeFilename, "Tells the debugger to read in and execute the lldb "
124                        "commands in the given file, before any file provided "
125                        "on the command line has been loaded."},
126     {LLDB_3_TO_5, false, "one-line-before-file", 'O', required_argument, 0,
127      eArgTypeNone, "Tells the debugger to execute this one-line lldb command "
128                    "before any file provided on the command line has been "
129                    "loaded."},
130     {LLDB_3_TO_5, false, "one-line-on-crash", 'k', required_argument, 0,
131      eArgTypeNone, "When in batch mode, tells the debugger to execute this "
132                    "one-line lldb command if the target crashes."},
133     {LLDB_3_TO_5, false, "source-on-crash", 'K', required_argument, 0,
134      eArgTypeFilename, "When in batch mode, tells the debugger to source this "
135                        "file of lldb commands if the target crashes."},
136     {LLDB_3_TO_5, false, "source-quietly", 'Q', no_argument, 0, eArgTypeNone,
137      "Tells the debugger to execute this one-line lldb command before any file "
138      "provided on the command line has been loaded."},
139     {LLDB_3_TO_5, false, "batch", 'b', no_argument, 0, eArgTypeNone,
140      "Tells the debugger to run the commands from -s, -S, -o & -O, and "
141      "then quit.  However if any run command stopped due to a signal or crash, "
142      "the debugger will return to the interactive prompt at the place of the "
143      "crash."},
144     {LLDB_3_TO_5, false, "editor", 'e', no_argument, 0, eArgTypeNone,
145      "Tells the debugger to open source files using the host's \"external "
146      "editor\" mechanism."},
147     {LLDB_3_TO_5, false, "no-lldbinit", 'x', no_argument, 0, eArgTypeNone,
148      "Do not automatically parse any '.lldbinit' files."},
149     {LLDB_3_TO_5, false, "no-use-colors", 'X', no_argument, 0, eArgTypeNone,
150      "Do not use colors."},
151     {LLDB_OPT_SET_6, true, "python-path", 'P', no_argument, 0, eArgTypeNone,
152      "Prints out the path to the lldb.py file for this version of lldb."},
153     {LLDB_3_TO_5, false, "script-language", 'l', required_argument, 0,
154      eArgTypeScriptLang,
155      "Tells the debugger to use the specified scripting language for "
156      "user-defined scripts, rather than the default.  "
157      "Valid scripting languages that can be specified include Python, Perl, "
158      "Ruby and Tcl.  Currently only the Python "
159      "extensions have been implemented."},
160     {LLDB_3_TO_5, false, "debug", 'd', no_argument, 0, eArgTypeNone,
161      "Tells the debugger to print out extra information for debugging itself."},
162     {LLDB_OPT_SET_7, true, "repl", 'r', optional_argument, 0, eArgTypeNone,
163      "Runs lldb in REPL mode with a stub process."},
164     {LLDB_OPT_SET_7, true, "repl-language", 'R', required_argument, 0,
165      eArgTypeNone, "Chooses the language for the REPL."}};
166 
167 static constexpr auto g_num_options = sizeof(g_options)/sizeof(OptionDefinition);
168 
169 static const uint32_t last_option_set_with_args = 2;
170 
171 Driver::Driver()
172     : SBBroadcaster("Driver"), m_debugger(SBDebugger::Create(false)),
173       m_option_data() {
174   // We want to be able to handle CTRL+D in the terminal to have it terminate
175   // certain input
176   m_debugger.SetCloseInputOnEOF(false);
177   g_driver = this;
178 }
179 
180 Driver::~Driver() { g_driver = NULL; }
181 
182 // This function takes INDENT, which tells how many spaces to output at the
183 // front
184 // of each line; TEXT, which is the text that is to be output. It outputs the
185 // text, on multiple lines if necessary, to RESULT, with INDENT spaces at the
186 // front of each line.  It breaks lines on spaces, tabs or newlines, shortening
187 // the line if necessary to not break in the middle of a word. It assumes that
188 // each output line should contain a maximum of OUTPUT_MAX_COLUMNS characters.
189 
190 void OutputFormattedUsageText(FILE *out, int indent, const char *text,
191                               int output_max_columns) {
192   int len = strlen(text);
193   std::string text_string(text);
194 
195   // Force indentation to be reasonable.
196   if (indent >= output_max_columns)
197     indent = 0;
198 
199   // Will it all fit on one line?
200 
201   if (len + indent < output_max_columns)
202     // Output as a single line
203     fprintf(out, "%*s%s\n", indent, "", text);
204   else {
205     // We need to break it up into multiple lines.
206     int text_width = output_max_columns - indent - 1;
207     int start = 0;
208     int end = start;
209     int final_end = len;
210     int sub_len;
211 
212     while (end < final_end) {
213       // Dont start the 'text' on a space, since we're already outputting the
214       // indentation.
215       while ((start < final_end) && (text[start] == ' '))
216         start++;
217 
218       end = start + text_width;
219       if (end > final_end)
220         end = final_end;
221       else {
222         // If we're not at the end of the text, make sure we break the line on
223         // white space.
224         while (end > start && text[end] != ' ' && text[end] != '\t' &&
225                text[end] != '\n')
226           end--;
227       }
228       sub_len = end - start;
229       std::string substring = text_string.substr(start, sub_len);
230       fprintf(out, "%*s%s\n", indent, "", substring.c_str());
231       start = end + 1;
232     }
233   }
234 }
235 
236 static void ShowUsage(FILE *out, Driver::OptionData data) {
237   uint32_t screen_width = 80;
238   uint32_t indent_level = 0;
239   const char *name = "lldb";
240 
241   fprintf(out, "\nUsage:\n\n");
242 
243   indent_level += 2;
244 
245   // First, show each usage level set of options, e.g. <cmd>
246   // [options-for-level-0]
247   //                                                   <cmd>
248   //                                                   [options-for-level-1]
249   //                                                   etc.
250 
251   uint32_t num_option_sets = 0;
252 
253   for (const auto &opt : g_options) {
254     uint32_t this_usage_mask = opt.usage_mask;
255     if (this_usage_mask == LLDB_OPT_SET_ALL) {
256       if (num_option_sets == 0)
257         num_option_sets = 1;
258     } else {
259       for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++) {
260         if (this_usage_mask & 1 << j) {
261           if (num_option_sets <= j)
262             num_option_sets = j + 1;
263         }
264       }
265     }
266   }
267 
268   for (uint32_t opt_set = 0; opt_set < num_option_sets; opt_set++) {
269     uint32_t opt_set_mask;
270 
271     opt_set_mask = 1 << opt_set;
272 
273     if (opt_set > 0)
274       fprintf(out, "\n");
275     fprintf(out, "%*s%s", indent_level, "", name);
276     bool is_help_line = false;
277 
278     for (const auto &opt : g_options) {
279       if (opt.usage_mask & opt_set_mask) {
280         CommandArgumentType arg_type = opt.argument_type;
281         const char *arg_name =
282             SBCommandInterpreter::GetArgumentTypeAsCString(arg_type);
283         // This is a bit of a hack, but there's no way to say certain options
284         // don't have arguments yet...
285         // so we do it by hand here.
286         if (opt.short_option == 'h')
287           is_help_line = true;
288 
289         if (opt.required) {
290           if (opt.option_has_arg == required_argument)
291             fprintf(out, " -%c <%s>", opt.short_option, arg_name);
292           else if (opt.option_has_arg == optional_argument)
293             fprintf(out, " -%c [<%s>]", opt.short_option, arg_name);
294           else
295             fprintf(out, " -%c", opt.short_option);
296         } else {
297           if (opt.option_has_arg == required_argument)
298             fprintf(out, " [-%c <%s>]", opt.short_option, arg_name);
299           else if (opt.option_has_arg == optional_argument)
300             fprintf(out, " [-%c [<%s>]]", opt.short_option,
301                     arg_name);
302           else
303             fprintf(out, " [-%c]", opt.short_option);
304         }
305       }
306     }
307     if (!is_help_line && (opt_set <= last_option_set_with_args))
308       fprintf(out, " [[--] <PROGRAM-ARG-1> [<PROGRAM_ARG-2> ...]]");
309   }
310 
311   fprintf(out, "\n\n");
312 
313   // Now print out all the detailed information about the various options:  long
314   // form, short form and help text:
315   //   -- long_name <argument>
316   //   - short <argument>
317   //   help text
318 
319   // This variable is used to keep track of which options' info we've printed
320   // out, because some options can be in
321   // more than one usage level, but we only want to print the long form of its
322   // information once.
323 
324   Driver::OptionData::OptionSet options_seen;
325   Driver::OptionData::OptionSet::iterator pos;
326 
327   indent_level += 5;
328 
329   for (const auto &opt : g_options) {
330     // Only print this option if we haven't already seen it.
331     pos = options_seen.find(opt.short_option);
332     if (pos == options_seen.end()) {
333       CommandArgumentType arg_type = opt.argument_type;
334       const char *arg_name =
335           SBCommandInterpreter::GetArgumentTypeAsCString(arg_type);
336 
337       options_seen.insert(opt.short_option);
338       fprintf(out, "%*s-%c ", indent_level, "", opt.short_option);
339       if (arg_type != eArgTypeNone)
340         fprintf(out, "<%s>", arg_name);
341       fprintf(out, "\n");
342       fprintf(out, "%*s--%s ", indent_level, "", opt.long_option);
343       if (arg_type != eArgTypeNone)
344         fprintf(out, "<%s>", arg_name);
345       fprintf(out, "\n");
346       indent_level += 5;
347       OutputFormattedUsageText(out, indent_level, opt.usage_text,
348                                screen_width);
349       indent_level -= 5;
350       fprintf(out, "\n");
351     }
352   }
353 
354   indent_level -= 5;
355 
356   fprintf(out, "\n%*sNotes:\n", indent_level, "");
357   indent_level += 5;
358 
359   fprintf(out,
360           "\n%*sMultiple \"-s\" and \"-o\" options can be provided.  They will "
361           "be processed"
362           "\n%*sfrom left to right in order, with the source files and commands"
363           "\n%*sinterleaved.  The same is true of the \"-S\" and \"-O\" "
364           "options.  The before"
365           "\n%*sfile and after file sets can intermixed freely, the command "
366           "parser will"
367           "\n%*ssort them out.  The order of the file specifiers (\"-c\", "
368           "\"-f\", etc.) is"
369           "\n%*snot significant in this regard.\n\n",
370           indent_level, "", indent_level, "", indent_level, "", indent_level,
371           "", indent_level, "", indent_level, "");
372 
373   fprintf(
374       out,
375       "\n%*sIf you don't provide -f then the first argument will be the file "
376       "to be"
377       "\n%*sdebugged which means that '%s -- <filename> [<ARG1> [<ARG2>]]' also"
378       "\n%*sworks.  But remember to end the options with \"--\" if any of your"
379       "\n%*sarguments have a \"-\" in them.\n\n",
380       indent_level, "", indent_level, "", name, indent_level, "", indent_level,
381       "");
382 }
383 
384  static void BuildGetOptTable(std::vector<option> &getopt_table) {
385   getopt_table.resize(g_num_options + 1);
386 
387   std::bitset<256> option_seen;
388   uint32_t j = 0;
389   for (const auto &opt : g_options) {
390     char short_opt = opt.short_option;
391 
392     if (option_seen.test(short_opt) == false) {
393       getopt_table[j].name = opt.long_option;
394       getopt_table[j].has_arg = opt.option_has_arg;
395       getopt_table[j].flag = NULL;
396       getopt_table[j].val = opt.short_option;
397       option_seen.set(short_opt);
398       ++j;
399     }
400   }
401 
402   getopt_table[j].name = NULL;
403   getopt_table[j].has_arg = 0;
404   getopt_table[j].flag = NULL;
405   getopt_table[j].val = 0;
406 }
407 
408 Driver::OptionData::OptionData()
409     : m_args(), m_script_lang(lldb::eScriptLanguageDefault), m_core_file(),
410       m_crash_log(), m_initial_commands(), m_after_file_commands(),
411       m_after_crash_commands(), m_debug_mode(false), m_source_quietly(false),
412       m_print_version(false), m_print_python_path(false), m_print_help(false),
413       m_wait_for(false), m_repl(false), m_repl_lang(eLanguageTypeUnknown),
414       m_repl_options(), m_process_name(),
415       m_process_pid(LLDB_INVALID_PROCESS_ID), m_use_external_editor(false),
416       m_batch(false), m_seen_options() {}
417 
418 Driver::OptionData::~OptionData() {}
419 
420 void Driver::OptionData::Clear() {
421   m_args.clear();
422   m_script_lang = lldb::eScriptLanguageDefault;
423   m_initial_commands.clear();
424   m_after_file_commands.clear();
425 
426   // If there is a local .lldbinit, add that to the
427   // list of things to be sourced, if the settings
428   // permit it.
429   SBFileSpec local_lldbinit(".lldbinit", true);
430 
431   SBFileSpec homedir_dot_lldb = SBHostOS::GetUserHomeDirectory();
432   homedir_dot_lldb.AppendPathComponent(".lldbinit");
433 
434   // Only read .lldbinit in the current working directory
435   // if it's not the same as the .lldbinit in the home
436   // directory (which is already being read in).
437   if (local_lldbinit.Exists() &&
438       strcmp(local_lldbinit.GetDirectory(), homedir_dot_lldb.GetDirectory()) !=
439           0) {
440     char path[2048];
441     local_lldbinit.GetPath(path, 2047);
442     InitialCmdEntry entry(path, true, true, true);
443     m_after_file_commands.push_back(entry);
444   }
445 
446   m_debug_mode = false;
447   m_source_quietly = false;
448   m_print_help = false;
449   m_print_version = false;
450   m_print_python_path = false;
451   m_use_external_editor = false;
452   m_wait_for = false;
453   m_process_name.erase();
454   m_batch = false;
455   m_after_crash_commands.clear();
456 
457   m_process_pid = LLDB_INVALID_PROCESS_ID;
458 }
459 
460 void Driver::OptionData::AddInitialCommand(const char *command,
461                                            CommandPlacement placement,
462                                            bool is_file, SBError &error) {
463   std::vector<InitialCmdEntry> *command_set;
464   switch (placement) {
465   case eCommandPlacementBeforeFile:
466     command_set = &(m_initial_commands);
467     break;
468   case eCommandPlacementAfterFile:
469     command_set = &(m_after_file_commands);
470     break;
471   case eCommandPlacementAfterCrash:
472     command_set = &(m_after_crash_commands);
473     break;
474   }
475 
476   if (is_file) {
477     SBFileSpec file(command);
478     if (file.Exists())
479       command_set->push_back(InitialCmdEntry(command, is_file, false));
480     else if (file.ResolveExecutableLocation()) {
481       char final_path[PATH_MAX];
482       file.GetPath(final_path, sizeof(final_path));
483       command_set->push_back(InitialCmdEntry(final_path, is_file, false));
484     } else
485       error.SetErrorStringWithFormat(
486           "file specified in --source (-s) option doesn't exist: '%s'", optarg);
487   } else
488     command_set->push_back(InitialCmdEntry(command, is_file, false));
489 }
490 
491 void Driver::ResetOptionValues() { m_option_data.Clear(); }
492 
493 const char *Driver::GetFilename() const {
494   if (m_option_data.m_args.empty())
495     return NULL;
496   return m_option_data.m_args.front().c_str();
497 }
498 
499 const char *Driver::GetCrashLogFilename() const {
500   if (m_option_data.m_crash_log.empty())
501     return NULL;
502   return m_option_data.m_crash_log.c_str();
503 }
504 
505 lldb::ScriptLanguage Driver::GetScriptLanguage() const {
506   return m_option_data.m_script_lang;
507 }
508 
509 void Driver::WriteCommandsForSourcing(CommandPlacement placement,
510                                       SBStream &strm) {
511   std::vector<OptionData::InitialCmdEntry> *command_set;
512   switch (placement) {
513   case eCommandPlacementBeforeFile:
514     command_set = &m_option_data.m_initial_commands;
515     break;
516   case eCommandPlacementAfterFile:
517     command_set = &m_option_data.m_after_file_commands;
518     break;
519   case eCommandPlacementAfterCrash:
520     command_set = &m_option_data.m_after_crash_commands;
521     break;
522   }
523 
524   for (const auto &command_entry : *command_set) {
525     const char *command = command_entry.contents.c_str();
526     if (command_entry.is_file) {
527       // If this command_entry is a file to be sourced, and it's the ./.lldbinit
528       // file (the .lldbinit
529       // file in the current working directory), only read it if
530       // target.load-cwd-lldbinit is 'true'.
531       if (command_entry.is_cwd_lldbinit_file_read) {
532         SBStringList strlist = m_debugger.GetInternalVariableValue(
533             "target.load-cwd-lldbinit", m_debugger.GetInstanceName());
534         if (strlist.GetSize() == 1 &&
535             strcmp(strlist.GetStringAtIndex(0), "warn") == 0) {
536           FILE *output = m_debugger.GetOutputFileHandle();
537           ::fprintf(
538               output,
539               "There is a .lldbinit file in the current directory which is not "
540               "being read.\n"
541               "To silence this warning without sourcing in the local "
542               ".lldbinit,\n"
543               "add the following to the lldbinit file in your home directory:\n"
544               "    settings set target.load-cwd-lldbinit false\n"
545               "To allow lldb to source .lldbinit files in the current working "
546               "directory,\n"
547               "set the value of this variable to true.  Only do so if you "
548               "understand and\n"
549               "accept the security risk.\n");
550           return;
551         }
552         if (strlist.GetSize() == 1 &&
553             strcmp(strlist.GetStringAtIndex(0), "false") == 0) {
554           return;
555         }
556       }
557       bool source_quietly =
558           m_option_data.m_source_quietly || command_entry.source_quietly;
559       strm.Printf("command source -s %i '%s'\n", source_quietly, command);
560     } else
561       strm.Printf("%s\n", command);
562   }
563 }
564 
565 bool Driver::GetDebugMode() const { return m_option_data.m_debug_mode; }
566 
567 // Check the arguments that were passed to this program to make sure they are
568 // valid and to get their
569 // argument values (if any).  Return a boolean value indicating whether or not
570 // to start up the full
571 // debugger (i.e. the Command Interpreter) or not.  Return FALSE if the
572 // arguments were invalid OR
573 // if the user only wanted help or version information.
574 
575 SBError Driver::ParseArgs(int argc, const char *argv[], FILE *out_fh,
576                           bool &exiting) {
577   static_assert(g_num_options > 0, "cannot handle arguments");
578 
579   ResetOptionValues();
580 
581   // No arguments or just program name, nothing to parse.
582   if (argc <= 1)
583     return SBError();
584 
585   SBError error;
586   std::vector<option> long_options_vector;
587   BuildGetOptTable(long_options_vector);
588   if (long_options_vector.empty()) {
589     error.SetErrorStringWithFormat("invalid long options");
590     return error;
591   }
592 
593   // Build the option_string argument for call to getopt_long_only.
594   std::string option_string;
595   auto sentinel_it = std::prev(std::end(long_options_vector));
596   for (auto long_opt_it = std::begin(long_options_vector);
597             long_opt_it != sentinel_it; ++long_opt_it) {
598     if (long_opt_it->flag == nullptr) {
599       option_string.push_back(static_cast<char>(long_opt_it->val));
600       switch (long_opt_it->has_arg) {
601       default:
602       case no_argument:
603         break;
604       case required_argument:
605         option_string.push_back(':');
606         break;
607       case optional_argument:
608         option_string.append("::");
609         break;
610       }
611     }
612   }
613 
614   // This is kind of a pain, but since we make the debugger in the Driver's
615   // constructor, we can't
616   // know at that point whether we should read in init files yet.  So we don't
617   // read them in in the
618   // Driver constructor, then set the flags back to "read them in" here, and
619   // then if we see the
620   // "-n" flag, we'll turn it off again.  Finally we have to read them in by
621   // hand later in the
622   // main loop.
623 
624   m_debugger.SkipLLDBInitFiles(false);
625   m_debugger.SkipAppInitFiles(false);
626 
627 // Prepare for & make calls to getopt_long_only.
628 #if __GLIBC__
629   optind = 0;
630 #else
631   optreset = 1;
632   optind = 1;
633 #endif
634   int val;
635   while (1) {
636     int long_options_index = -1;
637     val = ::getopt_long_only(argc, const_cast<char **>(argv),
638                              option_string.c_str(), long_options_vector.data(),
639                              &long_options_index);
640 
641     if (val == -1)
642       break;
643     else if (val == '?') {
644       m_option_data.m_print_help = true;
645       error.SetErrorStringWithFormat("unknown or ambiguous option");
646       break;
647     } else if (val == 0)
648       continue;
649     else {
650       m_option_data.m_seen_options.insert((char)val);
651       if (long_options_index == -1) {
652         auto long_opt_it = std::find_if(std::begin(long_options_vector), sentinel_it,
653             [val](const option &long_option) { return long_option.val == val; });
654         if (std::end(long_options_vector) != long_opt_it)
655           long_options_index =
656               std::distance(std::begin(long_options_vector), long_opt_it);
657       }
658 
659       if (long_options_index >= 0) {
660         const int short_option = g_options[long_options_index].short_option;
661 
662         switch (short_option) {
663         case 'h':
664           m_option_data.m_print_help = true;
665           break;
666 
667         case 'v':
668           m_option_data.m_print_version = true;
669           break;
670 
671         case 'P':
672           m_option_data.m_print_python_path = true;
673           break;
674 
675         case 'b':
676           m_option_data.m_batch = true;
677           break;
678 
679         case 'c': {
680           SBFileSpec file(optarg);
681           if (file.Exists()) {
682             m_option_data.m_core_file = optarg;
683           } else
684             error.SetErrorStringWithFormat(
685                 "file specified in --core (-c) option doesn't exist: '%s'",
686                 optarg);
687         } break;
688 
689         case 'e':
690           m_option_data.m_use_external_editor = true;
691           break;
692 
693         case 'x':
694           m_debugger.SkipLLDBInitFiles(true);
695           m_debugger.SkipAppInitFiles(true);
696           break;
697 
698         case 'X':
699           m_debugger.SetUseColor(false);
700           break;
701 
702         case 'f': {
703           SBFileSpec file(optarg);
704           if (file.Exists()) {
705             m_option_data.m_args.push_back(optarg);
706           } else if (file.ResolveExecutableLocation()) {
707             char path[PATH_MAX];
708             file.GetPath(path, sizeof(path));
709             m_option_data.m_args.push_back(path);
710           } else
711             error.SetErrorStringWithFormat(
712                 "file specified in --file (-f) option doesn't exist: '%s'",
713                 optarg);
714         } break;
715 
716         case 'a':
717           if (!m_debugger.SetDefaultArchitecture(optarg))
718             error.SetErrorStringWithFormat(
719                 "invalid architecture in the -a or --arch option: '%s'",
720                 optarg);
721           break;
722 
723         case 'l':
724           m_option_data.m_script_lang = m_debugger.GetScriptingLanguage(optarg);
725           break;
726 
727         case 'd':
728           m_option_data.m_debug_mode = true;
729           break;
730 
731         case 'Q':
732           m_option_data.m_source_quietly = true;
733           break;
734 
735         case 'K':
736           m_option_data.AddInitialCommand(optarg, eCommandPlacementAfterCrash,
737                                           true, error);
738           break;
739         case 'k':
740           m_option_data.AddInitialCommand(optarg, eCommandPlacementAfterCrash,
741                                           false, error);
742           break;
743 
744         case 'n':
745           m_option_data.m_process_name = optarg;
746           break;
747 
748         case 'w':
749           m_option_data.m_wait_for = true;
750           break;
751 
752         case 'p': {
753           char *remainder;
754           m_option_data.m_process_pid = strtol(optarg, &remainder, 0);
755           if (remainder == optarg || *remainder != '\0')
756             error.SetErrorStringWithFormat(
757                 "Could not convert process PID: \"%s\" into a pid.", optarg);
758         } break;
759 
760         case 'r':
761           m_option_data.m_repl = true;
762           if (optarg && optarg[0])
763             m_option_data.m_repl_options = optarg;
764           else
765             m_option_data.m_repl_options.clear();
766           break;
767 
768         case 'R':
769           m_option_data.m_repl_lang =
770               SBLanguageRuntime::GetLanguageTypeFromString(optarg);
771           if (m_option_data.m_repl_lang == eLanguageTypeUnknown) {
772             error.SetErrorStringWithFormat("Unrecognized language name: \"%s\"",
773                                            optarg);
774           }
775           break;
776 
777         case 's':
778           m_option_data.AddInitialCommand(optarg, eCommandPlacementAfterFile,
779                                           true, error);
780           break;
781         case 'o':
782           m_option_data.AddInitialCommand(optarg, eCommandPlacementAfterFile,
783                                           false, error);
784           break;
785         case 'S':
786           m_option_data.AddInitialCommand(optarg, eCommandPlacementBeforeFile,
787                                           true, error);
788           break;
789         case 'O':
790           m_option_data.AddInitialCommand(optarg, eCommandPlacementBeforeFile,
791                                           false, error);
792           break;
793         default:
794           m_option_data.m_print_help = true;
795           error.SetErrorStringWithFormat("unrecognized option %c",
796                                          short_option);
797           break;
798         }
799       } else {
800         error.SetErrorStringWithFormat("invalid option with value %i", val);
801       }
802       if (error.Fail()) {
803         return error;
804       }
805     }
806   }
807 
808   if (error.Fail() || m_option_data.m_print_help) {
809     ShowUsage(out_fh, m_option_data);
810     exiting = true;
811   } else if (m_option_data.m_print_version) {
812     ::fprintf(out_fh, "%s\n", m_debugger.GetVersionString());
813     exiting = true;
814   } else if (m_option_data.m_print_python_path) {
815     SBFileSpec python_file_spec = SBHostOS::GetLLDBPythonPath();
816     if (python_file_spec.IsValid()) {
817       char python_path[PATH_MAX];
818       size_t num_chars = python_file_spec.GetPath(python_path, PATH_MAX);
819       if (num_chars < PATH_MAX) {
820         ::fprintf(out_fh, "%s\n", python_path);
821       } else
822         ::fprintf(out_fh, "<PATH TOO LONG>\n");
823     } else
824       ::fprintf(out_fh, "<COULD NOT FIND PATH>\n");
825     exiting = true;
826   } else if (m_option_data.m_process_name.empty() &&
827              m_option_data.m_process_pid == LLDB_INVALID_PROCESS_ID) {
828     // Any arguments that are left over after option parsing are for
829     // the program. If a file was specified with -f then the filename
830     // is already in the m_option_data.m_args array, and any remaining args
831     // are arguments for the inferior program. If no file was specified with
832     // -f, then what is left is the program name followed by any arguments.
833 
834     // Skip any options we consumed with getopt_long_only
835     argc -= optind;
836     argv += optind;
837 
838     if (argc > 0) {
839       for (int arg_idx = 0; arg_idx < argc; ++arg_idx) {
840         const char *arg = argv[arg_idx];
841         if (arg)
842           m_option_data.m_args.push_back(arg);
843       }
844     }
845 
846   } else {
847     // Skip any options we consumed with getopt_long_only
848     argc -= optind;
849 
850     if (argc > 0)
851       ::fprintf(out_fh,
852                 "Warning: program arguments are ignored when attaching.\n");
853   }
854 
855   return error;
856 }
857 
858 static ::FILE *PrepareCommandsForSourcing(const char *commands_data,
859                                           size_t commands_size, int fds[2]) {
860   enum PIPES { READ, WRITE }; // Constants 0 and 1 for READ and WRITE
861 
862   ::FILE *commands_file = NULL;
863   fds[0] = -1;
864   fds[1] = -1;
865   int err = 0;
866 #ifdef _WIN32
867   err = _pipe(fds, commands_size, O_BINARY);
868 #else
869   err = pipe(fds);
870 #endif
871   if (err == 0) {
872     ssize_t nrwr = write(fds[WRITE], commands_data, commands_size);
873     if (nrwr < 0) {
874       fprintf(stderr, "error: write(%i, %p, %" PRIu64 ") failed (errno = %i) "
875                       "when trying to open LLDB commands pipe\n",
876               fds[WRITE], static_cast<const void *>(commands_data),
877               static_cast<uint64_t>(commands_size), errno);
878     } else if (static_cast<size_t>(nrwr) == commands_size) {
879 // Close the write end of the pipe so when we give the read end to
880 // the debugger/command interpreter it will exit when it consumes all
881 // of the data
882 #ifdef _WIN32
883       _close(fds[WRITE]);
884       fds[WRITE] = -1;
885 #else
886       close(fds[WRITE]);
887       fds[WRITE] = -1;
888 #endif
889       // Now open the read file descriptor in a FILE * that we can give to
890       // the debugger as an input handle
891       commands_file = fdopen(fds[READ], "r");
892       if (commands_file) {
893         fds[READ] =
894             -1; // The FILE * 'commands_file' now owns the read descriptor
895                 // Hand ownership if the FILE * over to the debugger for
896                 // "commands_file".
897       } else {
898         fprintf(stderr, "error: fdopen(%i, \"r\") failed (errno = %i) when "
899                         "trying to open LLDB commands pipe\n",
900                 fds[READ], errno);
901       }
902     }
903   } else {
904     fprintf(stderr,
905             "error: can't create pipe file descriptors for LLDB commands\n");
906   }
907 
908   return commands_file;
909 }
910 
911 void CleanupAfterCommandSourcing(int fds[2]) {
912   enum PIPES { READ, WRITE }; // Constants 0 and 1 for READ and WRITE
913 
914   // Close any pipes that we still have ownership of
915   if (fds[WRITE] != -1) {
916 #ifdef _WIN32
917     _close(fds[WRITE]);
918     fds[WRITE] = -1;
919 #else
920     close(fds[WRITE]);
921     fds[WRITE] = -1;
922 #endif
923   }
924 
925   if (fds[READ] != -1) {
926 #ifdef _WIN32
927     _close(fds[READ]);
928     fds[READ] = -1;
929 #else
930     close(fds[READ]);
931     fds[READ] = -1;
932 #endif
933   }
934 }
935 
936 std::string EscapeString(std::string arg) {
937   std::string::size_type pos = 0;
938   while ((pos = arg.find_first_of("\"\\", pos)) != std::string::npos) {
939     arg.insert(pos, 1, '\\');
940     pos += 2;
941   }
942   return '"' + arg + '"';
943 }
944 
945 int Driver::MainLoop() {
946   if (::tcgetattr(STDIN_FILENO, &g_old_stdin_termios) == 0) {
947     g_old_stdin_termios_is_valid = true;
948     atexit(reset_stdin_termios);
949   }
950 
951 #ifndef _MSC_VER
952   // Disabling stdin buffering with MSVC's 2015 CRT exposes a bug in fgets
953   // which causes it to miss newlines depending on whether there have been an
954   // odd or even number of characters.  Bug has been reported to MS via Connect.
955   ::setbuf(stdin, NULL);
956 #endif
957   ::setbuf(stdout, NULL);
958 
959   m_debugger.SetErrorFileHandle(stderr, false);
960   m_debugger.SetOutputFileHandle(stdout, false);
961   m_debugger.SetInputFileHandle(stdin,
962                                 false); // Don't take ownership of STDIN yet...
963 
964   m_debugger.SetUseExternalEditor(m_option_data.m_use_external_editor);
965 
966   struct winsize window_size;
967   if (isatty(STDIN_FILENO) &&
968       ::ioctl(STDIN_FILENO, TIOCGWINSZ, &window_size) == 0) {
969     if (window_size.ws_col > 0)
970       m_debugger.SetTerminalWidth(window_size.ws_col);
971   }
972 
973   SBCommandInterpreter sb_interpreter = m_debugger.GetCommandInterpreter();
974 
975   // Before we handle any options from the command line, we parse the
976   // .lldbinit file in the user's home directory.
977   SBCommandReturnObject result;
978   sb_interpreter.SourceInitFileInHomeDirectory(result);
979   if (GetDebugMode()) {
980     result.PutError(m_debugger.GetErrorFileHandle());
981     result.PutOutput(m_debugger.GetOutputFileHandle());
982   }
983 
984   // We allow the user to specify an exit code when calling quit which we will
985   // return when exiting.
986   m_debugger.GetCommandInterpreter().AllowExitCodeOnQuit(true);
987 
988   // Now we handle options we got from the command line
989   SBStream commands_stream;
990 
991   // First source in the commands specified to be run before the file arguments
992   // are processed.
993   WriteCommandsForSourcing(eCommandPlacementBeforeFile, commands_stream);
994 
995   const size_t num_args = m_option_data.m_args.size();
996   if (num_args > 0) {
997     char arch_name[64];
998     if (m_debugger.GetDefaultArchitecture(arch_name, sizeof(arch_name)))
999       commands_stream.Printf("target create --arch=%s %s", arch_name,
1000                              EscapeString(m_option_data.m_args[0]).c_str());
1001     else
1002       commands_stream.Printf("target create %s",
1003                              EscapeString(m_option_data.m_args[0]).c_str());
1004 
1005     if (!m_option_data.m_core_file.empty()) {
1006       commands_stream.Printf(" --core %s",
1007                              EscapeString(m_option_data.m_core_file).c_str());
1008     }
1009     commands_stream.Printf("\n");
1010 
1011     if (num_args > 1) {
1012       commands_stream.Printf("settings set -- target.run-args ");
1013       for (size_t arg_idx = 1; arg_idx < num_args; ++arg_idx)
1014         commands_stream.Printf(
1015             " %s", EscapeString(m_option_data.m_args[arg_idx]).c_str());
1016       commands_stream.Printf("\n");
1017     }
1018   } else if (!m_option_data.m_core_file.empty()) {
1019     commands_stream.Printf("target create --core %s\n",
1020                            EscapeString(m_option_data.m_core_file).c_str());
1021   } else if (!m_option_data.m_process_name.empty()) {
1022     commands_stream.Printf("process attach --name %s",
1023                            EscapeString(m_option_data.m_process_name).c_str());
1024 
1025     if (m_option_data.m_wait_for)
1026       commands_stream.Printf(" --waitfor");
1027 
1028     commands_stream.Printf("\n");
1029 
1030   } else if (LLDB_INVALID_PROCESS_ID != m_option_data.m_process_pid) {
1031     commands_stream.Printf("process attach --pid %" PRIu64 "\n",
1032                            m_option_data.m_process_pid);
1033   }
1034 
1035   WriteCommandsForSourcing(eCommandPlacementAfterFile, commands_stream);
1036 
1037   if (GetDebugMode()) {
1038     result.PutError(m_debugger.GetErrorFileHandle());
1039     result.PutOutput(m_debugger.GetOutputFileHandle());
1040   }
1041 
1042   bool handle_events = true;
1043   bool spawn_thread = false;
1044 
1045   if (m_option_data.m_repl) {
1046     const char *repl_options = NULL;
1047     if (!m_option_data.m_repl_options.empty())
1048       repl_options = m_option_data.m_repl_options.c_str();
1049     SBError error(m_debugger.RunREPL(m_option_data.m_repl_lang, repl_options));
1050     if (error.Fail()) {
1051       const char *error_cstr = error.GetCString();
1052       if (error_cstr && error_cstr[0])
1053         fprintf(stderr, "error: %s\n", error_cstr);
1054       else
1055         fprintf(stderr, "error: %u\n", error.GetError());
1056     }
1057   } else {
1058     // Check if we have any data in the commands stream, and if so, save it to a
1059     // temp file
1060     // so we can then run the command interpreter using the file contents.
1061     const char *commands_data = commands_stream.GetData();
1062     const size_t commands_size = commands_stream.GetSize();
1063 
1064     // The command file might have requested that we quit, this variable will
1065     // track that.
1066     bool quit_requested = false;
1067     bool stopped_for_crash = false;
1068     if (commands_data && commands_size) {
1069       int initial_commands_fds[2];
1070       bool success = true;
1071       FILE *commands_file = PrepareCommandsForSourcing(
1072           commands_data, commands_size, initial_commands_fds);
1073       if (commands_file) {
1074         m_debugger.SetInputFileHandle(commands_file, true);
1075 
1076         // Set the debugger into Sync mode when running the command file.
1077         // Otherwise command files
1078         // that run the target won't run in a sensible way.
1079         bool old_async = m_debugger.GetAsync();
1080         m_debugger.SetAsync(false);
1081         int num_errors;
1082 
1083         SBCommandInterpreterRunOptions options;
1084         options.SetStopOnError(true);
1085         if (m_option_data.m_batch)
1086           options.SetStopOnCrash(true);
1087 
1088         m_debugger.RunCommandInterpreter(handle_events, spawn_thread, options,
1089                                          num_errors, quit_requested,
1090                                          stopped_for_crash);
1091 
1092         if (m_option_data.m_batch && stopped_for_crash &&
1093             !m_option_data.m_after_crash_commands.empty()) {
1094           int crash_command_fds[2];
1095           SBStream crash_commands_stream;
1096           WriteCommandsForSourcing(eCommandPlacementAfterCrash,
1097                                    crash_commands_stream);
1098           const char *crash_commands_data = crash_commands_stream.GetData();
1099           const size_t crash_commands_size = crash_commands_stream.GetSize();
1100           commands_file = PrepareCommandsForSourcing(
1101               crash_commands_data, crash_commands_size, crash_command_fds);
1102           if (commands_file) {
1103             bool local_quit_requested;
1104             bool local_stopped_for_crash;
1105             m_debugger.SetInputFileHandle(commands_file, true);
1106 
1107             m_debugger.RunCommandInterpreter(
1108                 handle_events, spawn_thread, options, num_errors,
1109                 local_quit_requested, local_stopped_for_crash);
1110             if (local_quit_requested)
1111               quit_requested = true;
1112           }
1113         }
1114         m_debugger.SetAsync(old_async);
1115       } else
1116         success = false;
1117 
1118       // Close any pipes that we still have ownership of
1119       CleanupAfterCommandSourcing(initial_commands_fds);
1120 
1121       // Something went wrong with command pipe
1122       if (!success) {
1123         exit(1);
1124       }
1125     }
1126 
1127     // Now set the input file handle to STDIN and run the command
1128     // interpreter again in interactive mode and let the debugger
1129     // take ownership of stdin
1130 
1131     bool go_interactive = true;
1132     if (quit_requested)
1133       go_interactive = false;
1134     else if (m_option_data.m_batch && !stopped_for_crash)
1135       go_interactive = false;
1136 
1137     if (go_interactive) {
1138       m_debugger.SetInputFileHandle(stdin, true);
1139       m_debugger.RunCommandInterpreter(handle_events, spawn_thread);
1140     }
1141   }
1142 
1143   reset_stdin_termios();
1144   fclose(stdin);
1145 
1146   int exit_code = sb_interpreter.GetQuitStatus();
1147   SBDebugger::Destroy(m_debugger);
1148   return exit_code;
1149 }
1150 
1151 void Driver::ResizeWindow(unsigned short col) {
1152   GetDebugger().SetTerminalWidth(col);
1153 }
1154 
1155 void sigwinch_handler(int signo) {
1156   struct winsize window_size;
1157   if (isatty(STDIN_FILENO) &&
1158       ::ioctl(STDIN_FILENO, TIOCGWINSZ, &window_size) == 0) {
1159     if ((window_size.ws_col > 0) && g_driver != NULL) {
1160       g_driver->ResizeWindow(window_size.ws_col);
1161     }
1162   }
1163 }
1164 
1165 void sigint_handler(int signo) {
1166   static std::atomic_flag g_interrupt_sent = ATOMIC_FLAG_INIT;
1167   if (g_driver) {
1168     if (!g_interrupt_sent.test_and_set()) {
1169       g_driver->GetDebugger().DispatchInputInterrupt();
1170       g_interrupt_sent.clear();
1171       return;
1172     }
1173   }
1174 
1175   _exit(signo);
1176 }
1177 
1178 void sigtstp_handler(int signo) {
1179   if (g_driver)
1180     g_driver->GetDebugger().SaveInputTerminalState();
1181 
1182   signal(signo, SIG_DFL);
1183   kill(getpid(), signo);
1184   signal(signo, sigtstp_handler);
1185 }
1186 
1187 void sigcont_handler(int signo) {
1188   if (g_driver)
1189     g_driver->GetDebugger().RestoreInputTerminalState();
1190 
1191   signal(signo, SIG_DFL);
1192   kill(getpid(), signo);
1193   signal(signo, sigcont_handler);
1194 }
1195 
1196 int
1197 #ifdef _MSC_VER
1198 wmain(int argc, wchar_t const *wargv[])
1199 #else
1200 main(int argc, char const *argv[])
1201 #endif
1202 {
1203 #ifdef _MSC_VER
1204   // Convert wide arguments to UTF-8
1205   std::vector<std::string> argvStrings(argc);
1206   std::vector<const char *> argvPointers(argc);
1207   for (int i = 0; i != argc; ++i) {
1208     llvm::convertWideToUTF8(wargv[i], argvStrings[i]);
1209     argvPointers[i] = argvStrings[i].c_str();
1210   }
1211   const char **argv = argvPointers.data();
1212 #endif
1213 
1214   llvm::StringRef ToolName = argv[0];
1215   llvm::sys::PrintStackTraceOnErrorSignal(ToolName);
1216   llvm::PrettyStackTraceProgram X(argc, argv);
1217 
1218   SBDebugger::Initialize();
1219 
1220   SBHostOS::ThreadCreated("<lldb.driver.main-thread>");
1221 
1222   signal(SIGINT, sigint_handler);
1223 #if !defined(_MSC_VER)
1224   signal(SIGPIPE, SIG_IGN);
1225   signal(SIGWINCH, sigwinch_handler);
1226   signal(SIGTSTP, sigtstp_handler);
1227   signal(SIGCONT, sigcont_handler);
1228 #endif
1229 
1230   int exit_code = 0;
1231   // Create a scope for driver so that the driver object will destroy itself
1232   // before SBDebugger::Terminate() is called.
1233   {
1234     Driver driver;
1235 
1236     bool exiting = false;
1237     SBError error(driver.ParseArgs(argc, argv, stdout, exiting));
1238     if (error.Fail()) {
1239       exit_code = 1;
1240       const char *error_cstr = error.GetCString();
1241       if (error_cstr)
1242         ::fprintf(stderr, "error: %s\n", error_cstr);
1243     } else if (!exiting) {
1244       exit_code = driver.MainLoop();
1245     }
1246   }
1247 
1248   SBDebugger::Terminate();
1249   return exit_code;
1250 }
1251