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