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