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