]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/tools/lldb-mi/Driver.cpp
Update LLDB snapshot to upstream r225923 (git 2b588ecd)
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / tools / lldb-mi / Driver.cpp
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 // In-house headers:
11 #include "MICmnConfig.h"
12
13 #if MICONFIG_COMPILE_MIDRIVER_WITH_LLDBDRIVER
14
15 #ifndef _MSC_VER
16 #include <stdio.h>
17 #include <string.h>
18 #include <stdlib.h>
19 #include <limits.h>
20 #include <fcntl.h>
21 #include <string>
22 #endif // _MSC_VER
23
24 #include "Platform.h" // CODETAG_IOR_SIGNALS
25 #include "Driver.h"
26
27 #ifdef _MSC_VER
28 #include <lldb\Host\windows\getopt\GetOptInc.h>
29 #endif // _MSC_VER
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/SBEvent.h>
35 #include <lldb/API/SBHostOS.h>
36 #include <lldb/API/SBListener.h>
37 #include <lldb/API/SBStream.h>
38 #include <lldb/API/SBTarget.h>
39 #include <lldb/API/SBThread.h>
40 #include <lldb/API/SBProcess.h>
41
42 using namespace lldb;
43
44 static void reset_stdin_termios();
45 static bool g_old_stdin_termios_is_valid = false;
46 static struct termios g_old_stdin_termios;
47
48 static char *g_debugger_name = (char *)"";
49 Driver *g_driver = NULL;
50
51 // In the Driver::MainLoop, we change the terminal settings.  This function is
52 // added as an atexit handler to make sure we clean them up.
53 static void
54 reset_stdin_termios()
55 {
56     if (g_old_stdin_termios_is_valid)
57     {
58         g_old_stdin_termios_is_valid = false;
59         ::tcsetattr(STDIN_FILENO, TCSANOW, &g_old_stdin_termios);
60     }
61 }
62
63 typedef struct
64 {
65     uint32_t usage_mask;                     // Used to mark options that can be used together.  If (1 << n & usage_mask) != 0
66                                              // then this option belongs to option set n.
67     bool required;                           // This option is required (in the current usage level)
68     const char *long_option;                 // Full name for this option.
69     int short_option;                        // Single character for this option.
70     int option_has_arg;                      // no_argument, required_argument or optional_argument
71     uint32_t completion_type;                // Cookie the option class can use to do define the argument completion.
72     lldb::CommandArgumentType argument_type; // Type of argument this option takes
73     const char *usage_text;                  // Full text explaining what this options does and what (if any) argument to
74                                              // pass it.
75 } OptionDefinition;
76
77 #define LLDB_3_TO_5 LLDB_OPT_SET_3 | LLDB_OPT_SET_4 | LLDB_OPT_SET_5
78 #define LLDB_4_TO_5 LLDB_OPT_SET_4 | LLDB_OPT_SET_5
79
80 static OptionDefinition g_options[] = {
81     {LLDB_OPT_SET_1, true, "help", 'h', no_argument, 0, eArgTypeNone, "Prints out the usage information for the LLDB debugger."},
82     {LLDB_OPT_SET_2, true, "version", 'v', no_argument, 0, eArgTypeNone, "Prints out the current version number of the LLDB debugger."},
83     {LLDB_OPT_SET_3, true, "arch", 'a', required_argument, 0, eArgTypeArchitecture,
84      "Tells the debugger to use the specified architecture when starting and running the program.  <architecture> must "
85      "be one of the architectures for which the program was compiled."},
86     {LLDB_OPT_SET_3, true, "file", 'f', required_argument, 0, eArgTypeFilename,
87      "Tells the debugger to use the file <filename> as the program to be debugged."},
88     {LLDB_OPT_SET_3, false, "core", 'c', required_argument, 0, eArgTypeFilename,
89      "Tells the debugger to use the fullpath to <path> as the core file."},
90     {LLDB_OPT_SET_5, true, "attach-pid", 'p', required_argument, 0, eArgTypePid,
91      "Tells the debugger to attach to a process with the given pid."},
92     {LLDB_OPT_SET_4, true, "attach-name", 'n', required_argument, 0, eArgTypeProcessName,
93      "Tells the debugger to attach to a process with the given name."},
94     {LLDB_OPT_SET_4, true, "wait-for", 'w', no_argument, 0, eArgTypeNone,
95      "Tells the debugger to wait for a process with the given pid or name to launch before attaching."},
96     {LLDB_3_TO_5, false, "source", 's', required_argument, 0, eArgTypeFilename, "Tells the debugger to read in and execute the lldb "
97                                                                                 "commands in the given file, after any file provided on "
98                                                                                 "the command line has been loaded."},
99     {LLDB_3_TO_5, false, "one-line", 'o', required_argument, 0, eArgTypeNone,
100      "Tells the debugger to execute this one-line lldb command after any file provided on the command line has been loaded."},
101     {LLDB_3_TO_5, false, "source-before-file", 'S', required_argument, 0, eArgTypeFilename,
102      "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 "
103      "loaded."},
104     {LLDB_3_TO_5, false, "one-line-before-file", 'O', required_argument, 0, eArgTypeNone,
105      "Tells the debugger to execute this one-line lldb command before any file provided on the command line has been loaded."},
106     {LLDB_3_TO_5, false, "source-quietly", 'Q', no_argument, 0, eArgTypeNone,
107      "Tells the debugger suppress output from commands provided in the -s, -S, -O and -o commands."},
108     {LLDB_3_TO_5, false, "editor", 'e', no_argument, 0, eArgTypeNone,
109      "Tells the debugger to open source files using the host's \"external editor\" mechanism."},
110     {LLDB_3_TO_5, false, "no-lldbinit", 'x', no_argument, 0, eArgTypeNone, "Do not automatically parse any '.lldbinit' files."},
111     {LLDB_3_TO_5, false, "no-use-colors", 'X', no_argument, 0, eArgTypeNone, "Do not use colors."},
112     {LLDB_OPT_SET_6, true, "python-path", 'P', no_argument, 0, eArgTypeNone,
113      "Prints out the path to the lldb.py file for this version of lldb."},
114     {LLDB_3_TO_5, false, "script-language", 'l', required_argument, 0, eArgTypeScriptLang,
115      "Tells the debugger to use the specified scripting language for user-defined scripts, rather than the default.  "
116      "Valid scripting languages that can be specified include Python, Perl, Ruby and Tcl.  Currently only the Python "
117      "extensions have been implemented."},
118     {LLDB_3_TO_5, false, "debug", 'd', no_argument, 0, eArgTypeNone,
119      "Tells the debugger to print out extra information for debugging itself."},
120     {0, false, NULL, 0, 0, 0, eArgTypeNone, NULL}};
121
122 static const uint32_t last_option_set_with_args = 2;
123
124 Driver::Driver()
125     : SBBroadcaster("Driver")
126     , m_debugger(SBDebugger::Create(false))
127     , m_option_data()
128 {
129     // We want to be able to handle CTRL+D in the terminal to have it terminate
130     // certain input
131     m_debugger.SetCloseInputOnEOF(false);
132     g_debugger_name = (char *)m_debugger.GetInstanceName();
133     if (g_debugger_name == NULL)
134         g_debugger_name = (char *)"";
135     g_driver = this;
136 }
137
138 Driver::~Driver()
139 {
140     g_driver = NULL;
141     g_debugger_name = NULL;
142 }
143
144 // This function takes INDENT, which tells how many spaces to output at the front
145 // of each line; TEXT, which is the text that is to be output. It outputs the
146 // text, on multiple lines if necessary, to RESULT, with INDENT spaces at the
147 // front of each line.  It breaks lines on spaces, tabs or newlines, shortening
148 // the line if necessary to not break in the middle of a word. It assumes that
149 // each output line should contain a maximum of OUTPUT_MAX_COLUMNS characters.
150
151 void
152 OutputFormattedUsageText(FILE *out, int indent, const char *text, int output_max_columns)
153 {
154     int len = strlen(text);
155     std::string text_string(text);
156
157     // Force indentation to be reasonable.
158     if (indent >= output_max_columns)
159         indent = 0;
160
161     // Will it all fit on one line?
162
163     if (len + indent < output_max_columns)
164         // Output as a single line
165         fprintf(out, "%*s%s\n", indent, "", text);
166     else
167     {
168         // We need to break it up into multiple lines.
169         int text_width = output_max_columns - indent - 1;
170         int start = 0;
171         int end = start;
172         int final_end = len;
173         int sub_len;
174
175         while (end < final_end)
176         {
177             // Dont start the 'text' on a space, since we're already outputting the indentation.
178             while ((start < final_end) && (text[start] == ' '))
179                 start++;
180
181             end = start + text_width;
182             if (end > final_end)
183                 end = final_end;
184             else
185             {
186                 // If we're not at the end of the text, make sure we break the line on white space.
187                 while (end > start && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
188                     end--;
189             }
190             sub_len = end - start;
191             std::string substring = text_string.substr(start, sub_len);
192             fprintf(out, "%*s%s\n", indent, "", substring.c_str());
193             start = end + 1;
194         }
195     }
196 }
197
198 void
199 ShowUsage(FILE *out, OptionDefinition *option_table, Driver::OptionData data)
200 {
201     uint32_t screen_width = 80;
202     uint32_t indent_level = 0;
203     const char *name = "lldb";
204
205     fprintf(out, "\nUsage:\n\n");
206
207     indent_level += 2;
208
209     // First, show each usage level set of options, e.g. <cmd> [options-for-level-0]
210     //                                                   <cmd> [options-for-level-1]
211     //                                                   etc.
212
213     uint32_t num_options;
214     uint32_t num_option_sets = 0;
215
216     for (num_options = 0; option_table[num_options].long_option != NULL; ++num_options)
217     {
218         uint32_t this_usage_mask = option_table[num_options].usage_mask;
219         if (this_usage_mask == LLDB_OPT_SET_ALL)
220         {
221             if (num_option_sets == 0)
222                 num_option_sets = 1;
223         }
224         else
225         {
226             for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++)
227             {
228                 if (this_usage_mask & 1 << j)
229                 {
230                     if (num_option_sets <= j)
231                         num_option_sets = j + 1;
232                 }
233             }
234         }
235     }
236
237     for (uint32_t opt_set = 0; opt_set < num_option_sets; opt_set++)
238     {
239         uint32_t opt_set_mask;
240
241         opt_set_mask = 1 << opt_set;
242
243         if (opt_set > 0)
244             fprintf(out, "\n");
245         fprintf(out, "%*s%s", indent_level, "", name);
246         bool is_help_line = false;
247
248         for (uint32_t i = 0; i < num_options; ++i)
249         {
250             if (option_table[i].usage_mask & opt_set_mask)
251             {
252                 CommandArgumentType arg_type = option_table[i].argument_type;
253                 const char *arg_name = SBCommandInterpreter::GetArgumentTypeAsCString(arg_type);
254                 // This is a bit of a hack, but there's no way to say certain options don't have arguments yet...
255                 // so we do it by hand here.
256                 if (option_table[i].short_option == 'h')
257                     is_help_line = true;
258
259                 if (option_table[i].required)
260                 {
261                     if (option_table[i].option_has_arg == required_argument)
262                         fprintf(out, " -%c <%s>", option_table[i].short_option, arg_name);
263                     else if (option_table[i].option_has_arg == optional_argument)
264                         fprintf(out, " -%c [<%s>]", option_table[i].short_option, arg_name);
265                     else
266                         fprintf(out, " -%c", option_table[i].short_option);
267                 }
268                 else
269                 {
270                     if (option_table[i].option_has_arg == required_argument)
271                         fprintf(out, " [-%c <%s>]", option_table[i].short_option, arg_name);
272                     else if (option_table[i].option_has_arg == optional_argument)
273                         fprintf(out, " [-%c [<%s>]]", option_table[i].short_option, arg_name);
274                     else
275                         fprintf(out, " [-%c]", option_table[i].short_option);
276                 }
277             }
278         }
279         if (!is_help_line && (opt_set <= last_option_set_with_args))
280             fprintf(out, " [[--] <PROGRAM-ARG-1> [<PROGRAM_ARG-2> ...]]");
281     }
282
283     fprintf(out, "\n\n");
284
285     // Now print out all the detailed information about the various options:  long form, short form and help text:
286     //   -- long_name <argument>
287     //   - short <argument>
288     //   help text
289
290     // This variable is used to keep track of which options' info we've printed out, because some options can be in
291     // more than one usage level, but we only want to print the long form of its information once.
292
293     Driver::OptionData::OptionSet options_seen;
294     Driver::OptionData::OptionSet::iterator pos;
295
296     indent_level += 5;
297
298     for (uint32_t i = 0; i < num_options; ++i)
299     {
300         // Only print this option if we haven't already seen it.
301         pos = options_seen.find(option_table[i].short_option);
302         if (pos == options_seen.end())
303         {
304             CommandArgumentType arg_type = option_table[i].argument_type;
305             const char *arg_name = SBCommandInterpreter::GetArgumentTypeAsCString(arg_type);
306
307             options_seen.insert(option_table[i].short_option);
308             fprintf(out, "%*s-%c ", indent_level, "", option_table[i].short_option);
309             if (arg_type != eArgTypeNone)
310                 fprintf(out, "<%s>", arg_name);
311             fprintf(out, "\n");
312             fprintf(out, "%*s--%s ", indent_level, "", option_table[i].long_option);
313             if (arg_type != eArgTypeNone)
314                 fprintf(out, "<%s>", arg_name);
315             fprintf(out, "\n");
316             indent_level += 5;
317             OutputFormattedUsageText(out, indent_level, option_table[i].usage_text, screen_width);
318             indent_level -= 5;
319             fprintf(out, "\n");
320         }
321     }
322
323     indent_level -= 5;
324
325     fprintf(out, "\n%*sNotes:\n", indent_level, "");
326     indent_level += 5;
327
328     fprintf(out, "\n%*sMultiple \"-s\" and \"-o\" options can be provided.  They will be processed from left to right in order, "
329                  "\n%*swith the source files and commands interleaved.  The same is true of the \"-S\" and \"-O\" options."
330                  "\n%*sThe before file and after file sets can intermixed freely, the command parser will sort them out."
331                  "\n%*sThe order of the file specifiers (\"-c\", \"-f\", etc.) is not significant in this regard.\n\n",
332             indent_level, "", indent_level, "", indent_level, "", indent_level, "");
333
334     fprintf(out, "\n%*sIf you don't provide -f then the first argument will be the file to be debugged"
335                  "\n%*swhich means that '%s -- <filename> [<ARG1> [<ARG2>]]' also works."
336                  "\n%*sBut remember to end the options with \"--\" if any of your arguments have a \"-\" in them.\n\n",
337             indent_level, "", indent_level, "", name, indent_level, "");
338 }
339
340 void
341 BuildGetOptTable(OptionDefinition *expanded_option_table, std::vector<struct option> &getopt_table, uint32_t num_options)
342 {
343     if (num_options == 0)
344         return;
345
346     uint32_t i;
347     uint32_t j;
348     std::bitset<256> option_seen;
349
350     getopt_table.resize(num_options + 1);
351
352     for (i = 0, j = 0; i < num_options; ++i)
353     {
354         char short_opt = expanded_option_table[i].short_option;
355
356         if (option_seen.test(short_opt) == false)
357         {
358             getopt_table[j].name = expanded_option_table[i].long_option;
359             getopt_table[j].has_arg = expanded_option_table[i].option_has_arg;
360             getopt_table[j].flag = NULL;
361             getopt_table[j].val = expanded_option_table[i].short_option;
362             option_seen.set(short_opt);
363             ++j;
364         }
365     }
366
367     getopt_table[j].name = NULL;
368     getopt_table[j].has_arg = 0;
369     getopt_table[j].flag = NULL;
370     getopt_table[j].val = 0;
371 }
372
373 Driver::OptionData::OptionData()
374     : m_args()
375     , m_script_lang(lldb::eScriptLanguageDefault)
376     , m_core_file()
377     , m_crash_log()
378     , m_initial_commands()
379     , m_after_file_commands()
380     , m_debug_mode(false)
381     , m_source_quietly(false)
382     , m_print_version(false)
383     , m_print_python_path(false)
384     , m_print_help(false)
385     , m_wait_for(false)
386     , m_process_name()
387     , m_process_pid(LLDB_INVALID_PROCESS_ID)
388     , m_use_external_editor(false)
389     , m_seen_options()
390 {
391 }
392
393 Driver::OptionData::~OptionData()
394 {
395 }
396
397 void
398 Driver::OptionData::Clear()
399 {
400     m_args.clear();
401     m_script_lang = lldb::eScriptLanguageDefault;
402     m_initial_commands.clear();
403     m_after_file_commands.clear();
404     m_debug_mode = false;
405     m_source_quietly = false;
406     m_print_help = false;
407     m_print_version = false;
408     m_print_python_path = false;
409     m_use_external_editor = false;
410     m_wait_for = false;
411     m_process_name.erase();
412     m_process_pid = LLDB_INVALID_PROCESS_ID;
413 }
414
415 void
416 Driver::OptionData::AddInitialCommand(const char *command, bool before_file, bool is_file, SBError &error)
417 {
418     std::vector<std::pair<bool, std::string>> *command_set;
419     if (before_file)
420         command_set = &(m_initial_commands);
421     else
422         command_set = &(m_after_file_commands);
423
424     if (is_file)
425     {
426         SBFileSpec file(command);
427         if (file.Exists())
428             command_set->push_back(std::pair<bool, std::string>(true, optarg));
429         else if (file.ResolveExecutableLocation())
430         {
431             char final_path[PATH_MAX];
432             file.GetPath(final_path, sizeof(final_path));
433             std::string path_str(final_path);
434             command_set->push_back(std::pair<bool, std::string>(true, path_str));
435         }
436         else
437             error.SetErrorStringWithFormat("file specified in --source (-s) option doesn't exist: '%s'", optarg);
438     }
439     else
440         command_set->push_back(std::pair<bool, std::string>(false, optarg));
441 }
442
443 void
444 Driver::ResetOptionValues()
445 {
446     m_option_data.Clear();
447 }
448
449 const char *
450 Driver::GetFilename() const
451 {
452     if (m_option_data.m_args.empty())
453         return NULL;
454     return m_option_data.m_args.front().c_str();
455 }
456
457 const char *
458 Driver::GetCrashLogFilename() const
459 {
460     if (m_option_data.m_crash_log.empty())
461         return NULL;
462     return m_option_data.m_crash_log.c_str();
463 }
464
465 lldb::ScriptLanguage
466 Driver::GetScriptLanguage() const
467 {
468     return m_option_data.m_script_lang;
469 }
470
471 void
472 Driver::ExecuteInitialCommands(bool before_file)
473 {
474     size_t num_commands;
475     std::vector<std::pair<bool, std::string>> *command_set;
476     if (before_file)
477         command_set = &(m_option_data.m_initial_commands);
478     else
479         command_set = &(m_option_data.m_after_file_commands);
480
481     num_commands = command_set->size();
482     SBCommandReturnObject result;
483     bool old_async = GetDebugger().GetAsync();
484     GetDebugger().SetAsync(false);
485     for (size_t idx = 0; idx < num_commands; idx++)
486     {
487         bool is_file = (*command_set)[idx].first;
488         const char *command = (*command_set)[idx].second.c_str();
489         char command_string[PATH_MAX * 2];
490         const bool dump_stream_only_if_no_immediate = true;
491         const char *executed_command = command;
492         if (is_file)
493         {
494             ::snprintf(command_string, sizeof(command_string), "command source -s %i '%s'", m_option_data.m_source_quietly, command);
495             executed_command = command_string;
496         }
497
498         m_debugger.GetCommandInterpreter().HandleCommand(executed_command, result, false);
499         if (!m_option_data.m_source_quietly || result.Succeeded() == false)
500         {
501             const size_t output_size = result.GetOutputSize();
502             if (output_size > 0)
503             {
504                 const char *cstr = result.GetOutput(dump_stream_only_if_no_immediate);
505                 if (cstr)
506                     printf("%s", cstr);
507             }
508             const size_t error_size = result.GetErrorSize();
509             if (error_size > 0)
510             {
511                 const char *cstr = result.GetError(dump_stream_only_if_no_immediate);
512                 if (cstr)
513                     printf("%s", cstr);
514             }
515         }
516
517         if (result.Succeeded() == false)
518         {
519             const char *type = before_file ? "before file" : "after_file";
520             if (is_file)
521                 ::fprintf(stderr, "Aborting %s command execution, command file: '%s' failed.\n", type, command);
522             else
523                 ::fprintf(stderr, "Aborting %s command execution, command: '%s' failed.\n", type, command);
524             break;
525         }
526         result.Clear();
527     }
528     GetDebugger().SetAsync(old_async);
529 }
530
531 bool
532 Driver::GetDebugMode() const
533 {
534     return m_option_data.m_debug_mode;
535 }
536
537 // Check the arguments that were passed to this program to make sure they are valid and to get their
538 // argument values (if any).  Return a boolean value indicating whether or not to start up the full
539 // debugger (i.e. the Command Interpreter) or not.  Return FALSE if the arguments were invalid OR
540 // if the user only wanted help or version information.
541
542 SBError
543 Driver::ParseArgs(int argc, const char *argv[], FILE *out_fh, bool &exiting)
544 {
545     ResetOptionValues();
546
547     SBCommandReturnObject result;
548
549     SBError error;
550     std::string option_string;
551     struct option *long_options = NULL;
552     std::vector<struct option> long_options_vector;
553     uint32_t num_options;
554
555     for (num_options = 0; g_options[num_options].long_option != NULL; ++num_options)
556         /* Do Nothing. */;
557
558     if (num_options == 0)
559     {
560         if (argc > 1)
561             error.SetErrorStringWithFormat("invalid number of options");
562         return error;
563     }
564
565     BuildGetOptTable(g_options, long_options_vector, num_options);
566
567     if (long_options_vector.empty())
568         long_options = NULL;
569     else
570         long_options = &long_options_vector.front();
571
572     if (long_options == NULL)
573     {
574         error.SetErrorStringWithFormat("invalid long options");
575         return error;
576     }
577
578     // Build the option_string argument for call to getopt_long_only.
579
580     for (int i = 0; long_options[i].name != NULL; ++i)
581     {
582         if (long_options[i].flag == NULL)
583         {
584             option_string.push_back((char)long_options[i].val);
585             switch (long_options[i].has_arg)
586             {
587                 default:
588                 case no_argument:
589                     break;
590                 case required_argument:
591                     option_string.push_back(':');
592                     break;
593                 case optional_argument:
594                     option_string.append("::");
595                     break;
596             }
597         }
598     }
599
600     // This is kind of a pain, but since we make the debugger in the Driver's constructor, we can't
601     // know at that point whether we should read in init files yet.  So we don't read them in in the
602     // Driver constructor, then set the flags back to "read them in" here, and then if we see the
603     // "-n" flag, we'll turn it off again.  Finally we have to read them in by hand later in the
604     // main loop.
605
606     m_debugger.SkipLLDBInitFiles(false);
607     m_debugger.SkipAppInitFiles(false);
608
609 // Prepare for & make calls to getopt_long_only.
610 #if __GLIBC__
611     optind = 0;
612 #else
613     optreset = 1;
614     optind = 1;
615 #endif
616     int val;
617     while (1)
618     {
619         int long_options_index = -1;
620         val = ::getopt_long_only(argc, const_cast<char **>(argv), option_string.c_str(), long_options, &long_options_index);
621
622         if (val == -1)
623             break;
624         else if (val == '?')
625         {
626             m_option_data.m_print_help = true;
627             error.SetErrorStringWithFormat("unknown or ambiguous option");
628             break;
629         }
630         else if (val == 0)
631             continue;
632         else
633         {
634             m_option_data.m_seen_options.insert((char)val);
635             if (long_options_index == -1)
636             {
637                 for (int i = 0; long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val; ++i)
638                 {
639                     if (long_options[i].val == val)
640                     {
641                         long_options_index = i;
642                         break;
643                     }
644                 }
645             }
646
647             if (long_options_index >= 0)
648             {
649                 const int short_option = g_options[long_options_index].short_option;
650
651                 switch (short_option)
652                 {
653                     case 'h':
654                         m_option_data.m_print_help = true;
655                         break;
656
657                     case 'v':
658                         m_option_data.m_print_version = true;
659                         break;
660
661                     case 'P':
662                         m_option_data.m_print_python_path = true;
663                         break;
664
665                     case 'c':
666                     {
667                         SBFileSpec file(optarg);
668                         if (file.Exists())
669                         {
670                             m_option_data.m_core_file = optarg;
671                         }
672                         else
673                             error.SetErrorStringWithFormat("file specified in --core (-c) option doesn't exist: '%s'", optarg);
674                     }
675                     break;
676
677                     case 'e':
678                         m_option_data.m_use_external_editor = true;
679                         break;
680
681                     case 'x':
682                         m_debugger.SkipLLDBInitFiles(true);
683                         m_debugger.SkipAppInitFiles(true);
684                         break;
685
686                     case 'X':
687                         m_debugger.SetUseColor(false);
688                         break;
689
690                     case 'f':
691                     {
692                         SBFileSpec file(optarg);
693                         if (file.Exists())
694                         {
695                             m_option_data.m_args.push_back(optarg);
696                         }
697                         else if (file.ResolveExecutableLocation())
698                         {
699                             char path[PATH_MAX];
700                             file.GetPath(path, sizeof(path));
701                             m_option_data.m_args.push_back(path);
702                         }
703                         else
704                             error.SetErrorStringWithFormat("file specified in --file (-f) option doesn't exist: '%s'", optarg);
705                     }
706                     break;
707
708                     case 'a':
709                         if (!m_debugger.SetDefaultArchitecture(optarg))
710                             error.SetErrorStringWithFormat("invalid architecture in the -a or --arch option: '%s'", optarg);
711                         break;
712
713                     case 'l':
714                         m_option_data.m_script_lang = m_debugger.GetScriptingLanguage(optarg);
715                         break;
716
717                     case 'd':
718                         m_option_data.m_debug_mode = true;
719                         break;
720
721                     case 'Q':
722                         m_option_data.m_source_quietly = true;
723                         break;
724
725                     case 'n':
726                         m_option_data.m_process_name = optarg;
727                         break;
728
729                     case 'w':
730                         m_option_data.m_wait_for = true;
731                         break;
732
733                     case 'p':
734                     {
735                         char *remainder;
736                         m_option_data.m_process_pid = strtol(optarg, &remainder, 0);
737                         if (remainder == optarg || *remainder != '\0')
738                             error.SetErrorStringWithFormat("Could not convert process PID: \"%s\" into a pid.", optarg);
739                     }
740                     break;
741                     case 's':
742                         m_option_data.AddInitialCommand(optarg, false, true, error);
743                         break;
744                     case 'o':
745                         m_option_data.AddInitialCommand(optarg, false, false, error);
746                         break;
747                     case 'S':
748                         m_option_data.AddInitialCommand(optarg, true, true, error);
749                         break;
750                     case 'O':
751                         m_option_data.AddInitialCommand(optarg, true, false, error);
752                         break;
753                     default:
754                         m_option_data.m_print_help = true;
755                         error.SetErrorStringWithFormat("unrecognized option %c", short_option);
756                         break;
757                 }
758             }
759             else
760             {
761                 error.SetErrorStringWithFormat("invalid option with value %i", val);
762             }
763             if (error.Fail())
764             {
765                 return error;
766             }
767         }
768     }
769
770     if (error.Fail() || m_option_data.m_print_help)
771     {
772         ShowUsage(out_fh, g_options, m_option_data);
773         exiting = true;
774     }
775     else if (m_option_data.m_print_version)
776     {
777         ::fprintf(out_fh, "%s\n", m_debugger.GetVersionString());
778         exiting = true;
779     }
780     else if (m_option_data.m_print_python_path)
781     {
782         SBFileSpec python_file_spec = SBHostOS::GetLLDBPythonPath();
783         if (python_file_spec.IsValid())
784         {
785             char python_path[PATH_MAX];
786             size_t num_chars = python_file_spec.GetPath(python_path, PATH_MAX);
787             if (num_chars < PATH_MAX)
788             {
789                 ::fprintf(out_fh, "%s\n", python_path);
790             }
791             else
792                 ::fprintf(out_fh, "<PATH TOO LONG>\n");
793         }
794         else
795             ::fprintf(out_fh, "<COULD NOT FIND PATH>\n");
796         exiting = true;
797     }
798     else if (m_option_data.m_process_name.empty() && m_option_data.m_process_pid == LLDB_INVALID_PROCESS_ID)
799     {
800         // Any arguments that are left over after option parsing are for
801         // the program. If a file was specified with -f then the filename
802         // is already in the m_option_data.m_args array, and any remaining args
803         // are arguments for the inferior program. If no file was specified with
804         // -f, then what is left is the program name followed by any arguments.
805
806         // Skip any options we consumed with getopt_long_only
807         argc -= optind;
808         argv += optind;
809
810         if (argc > 0)
811         {
812             for (int arg_idx = 0; arg_idx < argc; ++arg_idx)
813             {
814                 const char *arg = argv[arg_idx];
815                 if (arg)
816                     m_option_data.m_args.push_back(arg);
817             }
818         }
819     }
820     else
821     {
822         // Skip any options we consumed with getopt_long_only
823         argc -= optind;
824         // argv += optind; // Commented out to keep static analyzer happy
825
826         if (argc > 0)
827             ::fprintf(out_fh, "Warning: program arguments are ignored when attaching.\n");
828     }
829
830     return error;
831 }
832
833 void
834 Driver::MainLoop()
835 {
836     if (::tcgetattr(STDIN_FILENO, &g_old_stdin_termios) == 0)
837     {
838         g_old_stdin_termios_is_valid = true;
839         atexit(reset_stdin_termios);
840     }
841
842     ::setbuf(stdin, NULL);
843     ::setbuf(stdout, NULL);
844
845     m_debugger.SetErrorFileHandle(stderr, false);
846     m_debugger.SetOutputFileHandle(stdout, false);
847     m_debugger.SetInputFileHandle(stdin, true);
848
849     m_debugger.SetUseExternalEditor(m_option_data.m_use_external_editor);
850
851     struct winsize window_size;
852     if (isatty(STDIN_FILENO) && ::ioctl(STDIN_FILENO, TIOCGWINSZ, &window_size) == 0)
853     {
854         if (window_size.ws_col > 0)
855             m_debugger.SetTerminalWidth(window_size.ws_col);
856     }
857
858     SBCommandInterpreter sb_interpreter = m_debugger.GetCommandInterpreter();
859
860     // Before we handle any options from the command line, we parse the
861     // .lldbinit file in the user's home directory.
862     SBCommandReturnObject result;
863     sb_interpreter.SourceInitFileInHomeDirectory(result);
864     if (GetDebugMode())
865     {
866         result.PutError(m_debugger.GetErrorFileHandle());
867         result.PutOutput(m_debugger.GetOutputFileHandle());
868     }
869
870     // Now we handle options we got from the command line
871     // First source in the commands specified to be run before the file arguments are processed.
872     ExecuteInitialCommands(true);
873
874     // Was there a core file specified?
875     std::string core_file_spec("");
876     if (!m_option_data.m_core_file.empty())
877         core_file_spec.append("--core ").append(m_option_data.m_core_file);
878
879     char command_string[PATH_MAX * 2];
880     const size_t num_args = m_option_data.m_args.size();
881     if (num_args > 0)
882     {
883         char arch_name[64];
884         if (m_debugger.GetDefaultArchitecture(arch_name, sizeof(arch_name)))
885             ::snprintf(command_string, sizeof(command_string), "target create --arch=%s %s \"%s\"", arch_name, core_file_spec.c_str(),
886                        m_option_data.m_args[0].c_str());
887         else
888             ::snprintf(command_string, sizeof(command_string), "target create %s \"%s\"", core_file_spec.c_str(),
889                        m_option_data.m_args[0].c_str());
890
891         m_debugger.HandleCommand(command_string);
892
893         if (num_args > 1)
894         {
895             m_debugger.HandleCommand("settings clear target.run-args");
896             char arg_cstr[1024];
897             for (size_t arg_idx = 1; arg_idx < num_args; ++arg_idx)
898             {
899                 ::snprintf(arg_cstr, sizeof(arg_cstr), "settings append target.run-args \"%s\"", m_option_data.m_args[arg_idx].c_str());
900                 m_debugger.HandleCommand(arg_cstr);
901             }
902         }
903     }
904     else if (!core_file_spec.empty())
905     {
906         ::snprintf(command_string, sizeof(command_string), "target create %s", core_file_spec.c_str());
907         m_debugger.HandleCommand(command_string);
908         ;
909     }
910     else if (!m_option_data.m_process_name.empty())
911     {
912         ::snprintf(command_string, sizeof(command_string), "process attach --name '%s'%s", m_option_data.m_process_name.c_str(),
913                    m_option_data.m_wait_for ? " --waitfor" : "");
914         m_debugger.HandleCommand(command_string);
915     }
916     else if (LLDB_INVALID_PROCESS_ID != m_option_data.m_process_pid)
917     {
918         ::snprintf(command_string, sizeof(command_string), "process attach --pid %" PRIu64, m_option_data.m_process_pid);
919         m_debugger.HandleCommand(command_string);
920     }
921
922     ExecuteInitialCommands(false);
923
924     // Now that all option parsing is done, we try and parse the .lldbinit
925     // file in the current working directory
926     sb_interpreter.SourceInitFileInCurrentWorkingDirectory(result);
927     if (GetDebugMode())
928     {
929         result.PutError(m_debugger.GetErrorFileHandle());
930         result.PutOutput(m_debugger.GetOutputFileHandle());
931     }
932
933     bool handle_events = true;
934     bool spawn_thread = false;
935     m_debugger.RunCommandInterpreter(handle_events, spawn_thread);
936
937     reset_stdin_termios();
938     fclose(stdin);
939
940     SBDebugger::Destroy(m_debugger);
941 }
942
943 void
944 Driver::ResizeWindow(unsigned short col)
945 {
946     GetDebugger().SetTerminalWidth(col);
947 }
948
949 //++ ------------------------------------------------------------------------------------
950 // Details: Setup *this driver so it works as pass through (child) driver for the MI
951 //          driver. Called by the parent (MI driver) driver.
952 //          This driver has setup code in two places. The original in MainLoop() and
953 //          in int main() (when MICONFIG_COMPILE_MIDRIVER_VERSION == 0) so that code can
954 //          remain as much near to the original code as possible. If MI driver is the main
955 //          driver (when MICONFIG_COMPILE_MIDRIVER_VERSION == 1) then this function is
956 //          used to set up the Driver to work with the MI driver.
957 // Type:    Method.
958 // Args:    vwErrMsg    - (W) On failure current error discription.
959 // Return:  MIstatus::success - Functional succeeded.
960 //          MIstatus::failure - Functional failed.
961 // Throws:  None.
962 //--
963 bool
964 Driver::MISetup(CMIUtilString &vwErrMsg)
965 {
966     bool bOk = MIstatus::success;
967
968     // Is *this driver a pass through driver to the MI driver
969     CMIDriverBase *pParent = GetDriversParent();
970     if (pParent == nullptr)
971     {
972         // No it is not.
973         // If MI is the main driver (which passes through to *this driver) then
974         // *this driver needs to be initialized after MI is initialize to have a valid
975         // pointer to the parent driver. *this is the parent's pass thru driver.
976         assert(pParent == nullptr);
977         return MIstatus::success; // Allow success for if Driver is the main driver
978     }
979
980     // MI driver may have streams it wants *this driver to use - still to be sorted
981     m_debugger.SetErrorFileHandle(pParent->GetStderr(), false);  // MI may redirect to its own stream
982     m_debugger.SetOutputFileHandle(pParent->GetStdout(), false); // MI likely to NULL this
983     m_debugger.SetInputFileHandle(pParent->GetStdin(), false);   // MI could use this to feed input
984
985     // ToDo: Do I need this?
986     m_debugger.SetUseExternalEditor(m_option_data.m_use_external_editor);
987
988     // ToDo: Do I need this?
989     struct winsize window_size;
990     if (isatty(STDIN_FILENO) && ::ioctl(STDIN_FILENO, TIOCGWINSZ, &window_size) == 0)
991     {
992         if (window_size.ws_col > 0)
993             m_debugger.SetTerminalWidth(window_size.ws_col);
994     }
995
996     return bOk;
997 }
998
999 //++ ------------------------------------------------------------------------------------
1000 // Details: Initialize setup *this driver ready for use.
1001 // Type:    Overridden.
1002 // Args:    None.
1003 // Return:  MIstatus::success - Functional succeeded.
1004 //          MIstatus::failure - Functional failed.
1005 // Throws:  None.
1006 //--
1007 bool
1008 Driver::DoInitialize(void)
1009 {
1010     // Do nothing
1011     return MIstatus::success;
1012 }
1013
1014 //++ ------------------------------------------------------------------------------------
1015 // Details: Unbind detach or release resources used by *this driver.
1016 // Type:    Overridden.
1017 // Args:    None.
1018 // Return:  MIstatus::success - Functional succeeded.
1019 //          MIstatus::failure - Functional failed.
1020 // Throws:  None.
1021 //--
1022 bool
1023 Driver::DoShutdown(void)
1024 {
1025     SBDebugger::Destroy(m_debugger);
1026
1027     // Is *this driver a pass through driver to the MI driver
1028     CMIDriverBase *pParent = GetDriversParent();
1029     if (pParent == nullptr)
1030     {
1031         // See DoInitialize().
1032         assert(pParent == nullptr);
1033         return MIstatus::success;
1034     }
1035
1036     // Put stuff here when *this driver is a pass thru driver to the MI driver
1037
1038     return MIstatus::success;
1039 }
1040
1041 //++ ------------------------------------------------------------------------------------
1042 // Details: Retrieve the name for *this driver.
1043 // Type:    Overridden.
1044 // Args:    None.
1045 // Return:  CMIUtilString & - Driver name.
1046 // Throws:  None.
1047 //--
1048 const CMIUtilString &
1049 Driver::GetName(void) const
1050 {
1051     static CMIUtilString name("LLDB driver");
1052     return name;
1053 }
1054
1055 //++ ------------------------------------------------------------------------------------
1056 // Details: Retrieve *this driver's last error condition.
1057 // Type:    Overridden.
1058 // Args:    None.
1059 // Return:  CMIUtilString - Text description.
1060 // Throws:  None.
1061 //--
1062 CMIUtilString
1063 Driver::GetError(void) const
1064 {
1065     // Do nothing - to implement
1066     return CMIUtilString();
1067 }
1068
1069 //++ ------------------------------------------------------------------------------------
1070 // Details: Call this function puts *this driver to work.
1071 // Type:    Overridden.
1072 // Args:    None.
1073 // Return:  MIstatus::success - Functional succeeded.
1074 //          MIstatus::failure - Functional failed.
1075 // Throws:  None.
1076 //--
1077 bool
1078 Driver::DoMainLoop(void)
1079 {
1080     MainLoop();
1081
1082     return MIstatus::success;
1083 }
1084
1085 //++ ------------------------------------------------------------------------------------
1086 // Details: Call *this driver to resize the console window.
1087 // Type:    Overridden.
1088 // Args:    vTermWidth  - (R) New window column size.
1089 // Return:  MIstatus::success - Functional succeeded.
1090 //          MIstatus::failure - Functional failed.
1091 // Throws:  None.
1092 //--
1093 void
1094 Driver::DoResizeWindow(const uint32_t vTermWidth)
1095 {
1096     ResizeWindow((unsigned short)vTermWidth);
1097 }
1098
1099 //++ ------------------------------------------------------------------------------------
1100 // Details: Call *this driver to return it's debugger.
1101 // Type:    Overridden.
1102 // Args:    None.
1103 // Return:  lldb::SBDebugger & - LLDB debugger object reference.
1104 // Throws:  None.
1105 //--
1106 lldb::SBDebugger &
1107 Driver::GetTheDebugger(void)
1108 {
1109     return GetDebugger();
1110 }
1111
1112 //++ ------------------------------------------------------------------------------------
1113 // Details: Proxy function to allow the driver implementation to validate executable
1114 //          command line arguments.
1115 // Type:    Overrideable.
1116 // Args:    argc        - (R)   An integer that contains the count of arguments that follow in
1117 //                              argv. The argc parameter is always greater than or equal to 1.
1118 //          argv        - (R)   An array of null-terminated strings representing command-line
1119 //                              arguments entered by the user of the program. By convention,
1120 //                              argv[0] is the command with which the program is invoked.
1121 //          vpStdOut    - (R)   Pointer to a standard output stream.
1122 //          vwbExiting  - (W)   True = *this want to exit, Reasons: help, invalid arg(s),
1123 //                              version information only.
1124 //                              False = Continue to work, start debugger i.e. Command
1125 //                              interpreter.
1126 // Return:  lldb::SBError - LLDB current error status.
1127 // Throws:  None.
1128 //--
1129 lldb::SBError
1130 Driver::DoParseArgs(const int argc, const char *argv[], FILE *vpStdOut, bool &vwbExiting)
1131 {
1132     return ParseArgs(argc, argv, vpStdOut, vwbExiting);
1133 }
1134
1135 //++ ------------------------------------------------------------------------------------
1136 // Details: A client can ask if *this driver is GDB/MI compatible.
1137 // Type:    Overridden.
1138 // Args:    None.
1139 // Return:  True - GBD/MI compatible LLDB front end.
1140 //          False - Not GBD/MI compatible LLDB front end.
1141 // Throws:  None.
1142 //--
1143 bool
1144 Driver::GetDriverIsGDBMICompatibleDriver(void) const
1145 {
1146     return false;
1147 }
1148
1149 //++ ------------------------------------------------------------------------------------
1150 // Details: This function allows *this driver to call on another driver to perform work
1151 //          should this driver not be able to handle the client data input.
1152 //          SetDriverToFallThruTo() specifies the fall through to driver.
1153 //          Check the error message if the function returns a failure.
1154 // Type:    Overridden.
1155 // Args:    vCmd        - (R) Command instruction to interpret.
1156 //          vwErrMsg    - (W) Error description on command failing.
1157 // Return:  MIstatus::success - Command succeeded.
1158 //          MIstatus::failure - Command failed.
1159 // Throws:  None.
1160 //--
1161 bool
1162 Driver::DoFallThruToAnotherDriver(const CMIUtilString &vCmd, CMIUtilString &vwErrMsg)
1163 {
1164     bool bOk = MIstatus::success;
1165     vwErrMsg.empty();
1166
1167     // ToDo: Implement do work on other driver after this driver said "Give up you try"
1168     // This may nto be required if the feature to 'fall through' is not required
1169     SBCommandReturnObject returnObj = lldb::SBCommandReturnObject();
1170     SBCommandInterpreter cmdIntrp = m_debugger.GetCommandInterpreter();
1171     const lldb::ReturnStatus cmdResult = cmdIntrp.HandleCommand(vCmd.c_str(), returnObj);
1172     MIunused(cmdResult);
1173     if (returnObj.Succeeded() == false)
1174     {
1175         bOk = MIstatus::failure;
1176         vwErrMsg = returnObj.GetError();
1177     }
1178
1179     return bOk;
1180 }
1181
1182 //++ ------------------------------------------------------------------------------------
1183 // Details: This function allows *this driver to call functionality on the parent driver
1184 //          ask for information for example.
1185 // Type:    Overridden.
1186 // Args:    vrOtherDriver     - (R) Reference to another driver object.
1187 // Return:  MIstatus::success - Functional succeeded.
1188 //          MIstatus::failure - Functional failed.
1189 // Throws:  None.
1190 //--
1191 bool
1192 Driver::SetDriverParent(const CMIDriverBase &vrOtherDriver)
1193 {
1194     m_pDriverParent = const_cast<CMIDriverBase *>(&vrOtherDriver);
1195
1196     return MIstatus::success;
1197 }
1198
1199 //++ ------------------------------------------------------------------------------------
1200 // Details: Set a unique ID for *this driver. It cannot be empty.
1201 // Type:    Overridden.
1202 // Args:    vId - (R) Text description.
1203 // Return:  MIstatus::success - Functional succeeded.
1204 //          MIstatus::failure - Functional failed.
1205 // Throws:  None.
1206 //--
1207 bool
1208 Driver::SetId(const CMIUtilString &vId)
1209 {
1210     if (vId.empty())
1211     {
1212         // Invalid to have it empty
1213         return MIstatus::failure;
1214     }
1215
1216     m_strDriverId = vId;
1217     return MIstatus::success;
1218 }
1219
1220 //++ ------------------------------------------------------------------------------------
1221 // Details: Get the unique ID for *this driver.
1222 // Type:    Overridden.
1223 // Args:    None.
1224 // Return:  CMIUtilString & - Text description.
1225 // Throws:  None.
1226 //--
1227 const CMIUtilString &
1228 Driver::GetId(void) const
1229 {
1230     return m_strDriverId;
1231 }
1232
1233 //++ ------------------------------------------------------------------------------------
1234 // Details: Create *this driver. Function contains functionality that needs to be called
1235 //          prior to constructing the *this driver.
1236 // Type:    Static method.
1237 // Args:    None.
1238 // Return:  Driver * - Ptr to the LLDB driver object.
1239 // Throws:  None.
1240 //--
1241 Driver *
1242 Driver::CreateSelf(void)
1243 {
1244     lldb::SBDebugger::Initialize();
1245
1246     Driver *pDriver = new Driver;
1247     return pDriver;
1248 }
1249
1250 //++ ------------------------------------------------------------------------------------
1251 // Details: Retrieve the name for *this driver.
1252 // Type:    Overridden.
1253 // Args:    None.
1254 // Return:  CMIUtilString - Driver name.
1255 // Throws:  None.
1256 //--
1257 const CMIUtilString &
1258 Driver::GetDriverName(void) const
1259 {
1260     return GetName();
1261 }
1262
1263 //++ ------------------------------------------------------------------------------------
1264 // Details: Get the unique ID for *this driver.
1265 // Type:    Overridden.
1266 // Args:    None.
1267 // Return:  CMIUtilString & - Text description.
1268 // Throws:  None.
1269 //--
1270 const CMIUtilString &
1271 Driver::GetDriverId(void) const
1272 {
1273     return GetId();
1274 }
1275
1276 #endif // MICONFIG_COMPILE_MIDRIVER_WITH_LLDBDRIVER