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