1 //===-- Driver.cpp ----------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
18 // Includes for pipe()
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"
45 #if !defined(__APPLE__)
46 #include "llvm/Support/DataTypes.h"
51 static void reset_stdin_termios();
52 static bool g_old_stdin_termios_is_valid = false;
53 static struct termios g_old_stdin_termios;
55 static Driver *g_driver = NULL;
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);
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
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
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,
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 "
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,
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 "
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 "
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,
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}};
160 static const uint32_t last_option_set_with_args = 2;
163 : SBBroadcaster("Driver"), m_debugger(SBDebugger::Create(false)),
165 // We want to be able to handle CTRL+D in the terminal to have it terminate
167 m_debugger.SetCloseInputOnEOF(false);
171 Driver::~Driver() { g_driver = NULL; }
173 // This function takes INDENT, which tells how many spaces to output at the
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.
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);
186 // Force indentation to be reasonable.
187 if (indent >= output_max_columns)
190 // Will it all fit on one line?
192 if (len + indent < output_max_columns)
193 // Output as a single line
194 fprintf(out, "%*s%s\n", indent, "", text);
196 // We need to break it up into multiple lines.
197 int text_width = output_max_columns - indent - 1;
203 while (end < final_end) {
204 // Dont start the 'text' on a space, since we're already outputting the
206 while ((start < final_end) && (text[start] == ' '))
209 end = start + text_width;
213 // If we're not at the end of the text, make sure we break the line on
215 while (end > start && text[end] != ' ' && text[end] != '\t' &&
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());
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";
233 fprintf(out, "\nUsage:\n\n");
237 // First, show each usage level set of options, e.g. <cmd>
238 // [options-for-level-0]
240 // [options-for-level-1]
243 uint32_t num_options;
244 uint32_t num_option_sets = 0;
246 for (num_options = 0; option_table[num_options].long_option != NULL;
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)
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;
262 for (uint32_t opt_set = 0; opt_set < num_option_sets; opt_set++) {
263 uint32_t opt_set_mask;
265 opt_set_mask = 1 << opt_set;
269 fprintf(out, "%*s%s", indent_level, "", name);
270 bool is_help_line = false;
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')
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);
289 fprintf(out, " -%c", option_table[i].short_option);
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,
297 fprintf(out, " [-%c]", option_table[i].short_option);
301 if (!is_help_line && (opt_set <= last_option_set_with_args))
302 fprintf(out, " [[--] <PROGRAM-ARG-1> [<PROGRAM_ARG-2> ...]]");
305 fprintf(out, "\n\n");
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>
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
318 Driver::OptionData::OptionSet options_seen;
319 Driver::OptionData::OptionSet::iterator pos;
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);
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);
336 fprintf(out, "%*s--%s ", indent_level, "", option_table[i].long_option);
337 if (arg_type != eArgTypeNone)
338 fprintf(out, "<%s>", arg_name);
341 OutputFormattedUsageText(out, indent_level, option_table[i].usage_text,
350 fprintf(out, "\n%*sNotes:\n", indent_level, "");
354 "\n%*sMultiple \"-s\" and \"-o\" options can be provided. They will "
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 "
361 "\n%*ssort them out. The order of the file specifiers (\"-c\", "
363 "\n%*snot significant in this regard.\n\n",
364 indent_level, "", indent_level, "", indent_level, "", indent_level,
365 "", indent_level, "", indent_level, "");
369 "\n%*sIf you don't provide -f then the first argument will be the file "
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,
378 void BuildGetOptTable(OptionDefinition *expanded_option_table,
379 std::vector<struct option> &getopt_table,
380 uint32_t num_options) {
381 if (num_options == 0)
386 std::bitset<256> option_seen;
388 getopt_table.resize(num_options + 1);
390 for (i = 0, j = 0; i < num_options; ++i) {
391 char short_opt = expanded_option_table[i].short_option;
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);
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;
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() {}
419 Driver::OptionData::~OptionData() {}
421 void Driver::OptionData::Clear() {
423 m_script_lang = lldb::eScriptLanguageDefault;
424 m_initial_commands.clear();
425 m_after_file_commands.clear();
427 // If there is a local .lldbinit, add that to the
428 // list of things to be sourced, if the settings
430 SBFileSpec local_lldbinit(".lldbinit", true);
432 SBFileSpec homedir_dot_lldb = SBHostOS::GetUserHomeDirectory();
433 homedir_dot_lldb.AppendPathComponent(".lldbinit");
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()) !=
442 local_lldbinit.GetPath(path, 2047);
443 InitialCmdEntry entry(path, true, true, true);
444 m_after_file_commands.push_back(entry);
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;
454 m_process_name.erase();
456 m_after_crash_commands.clear();
458 m_process_pid = LLDB_INVALID_PROCESS_ID;
461 void Driver::OptionData::AddInitialCommand(const char *command,
462 CommandPlacement placement,
463 bool is_file, SBError &error) {
464 std::vector<InitialCmdEntry> *command_set;
466 case eCommandPlacementBeforeFile:
467 command_set = &(m_initial_commands);
469 case eCommandPlacementAfterFile:
470 command_set = &(m_after_file_commands);
472 case eCommandPlacementAfterCrash:
473 command_set = &(m_after_crash_commands);
478 SBFileSpec file(command);
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));
486 error.SetErrorStringWithFormat(
487 "file specified in --source (-s) option doesn't exist: '%s'", optarg);
489 command_set->push_back(InitialCmdEntry(command, is_file, false));
492 void Driver::ResetOptionValues() { m_option_data.Clear(); }
494 const char *Driver::GetFilename() const {
495 if (m_option_data.m_args.empty())
497 return m_option_data.m_args.front().c_str();
500 const char *Driver::GetCrashLogFilename() const {
501 if (m_option_data.m_crash_log.empty())
503 return m_option_data.m_crash_log.c_str();
506 lldb::ScriptLanguage Driver::GetScriptLanguage() const {
507 return m_option_data.m_script_lang;
510 void Driver::WriteCommandsForSourcing(CommandPlacement placement,
512 std::vector<OptionData::InitialCmdEntry> *command_set;
514 case eCommandPlacementBeforeFile:
515 command_set = &m_option_data.m_initial_commands;
517 case eCommandPlacementAfterFile:
518 command_set = &m_option_data.m_after_file_commands;
520 case eCommandPlacementAfterCrash:
521 command_set = &m_option_data.m_after_crash_commands;
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();
540 "There is a .lldbinit file in the current directory which is not "
542 "To silence this warning without sourcing in the local "
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 "
548 "set the value of this variable to true. Only do so if you "
550 "accept the security risk.\n");
553 if (strlist.GetSize() == 1 &&
554 strcmp(strlist.GetStringAtIndex(0), "false") == 0) {
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);
562 strm.Printf("%s\n", command);
566 bool Driver::GetDebugMode() const { return m_option_data.m_debug_mode; }
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.
576 SBError Driver::ParseArgs(int argc, const char *argv[], FILE *out_fh,
580 SBCommandReturnObject result;
583 std::string option_string;
584 struct option *long_options = NULL;
585 std::vector<struct option> long_options_vector;
586 uint32_t num_options;
588 for (num_options = 0; g_options[num_options].long_option != NULL;
592 if (num_options == 0) {
594 error.SetErrorStringWithFormat("invalid number of options");
598 BuildGetOptTable(g_options, long_options_vector, num_options);
600 if (long_options_vector.empty())
603 long_options = &long_options_vector.front();
605 if (long_options == NULL) {
606 error.SetErrorStringWithFormat("invalid long options");
610 // Build the option_string argument for call to getopt_long_only.
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) {
619 case required_argument:
620 option_string.push_back(':');
622 case optional_argument:
623 option_string.append("::");
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
639 m_debugger.SkipLLDBInitFiles(false);
640 m_debugger.SkipAppInitFiles(false);
642 // Prepare for & make calls to getopt_long_only.
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);
658 else if (val == '?') {
659 m_option_data.m_print_help = true;
660 error.SetErrorStringWithFormat("unknown or ambiguous option");
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;
670 if (long_options[i].val == val) {
671 long_options_index = i;
677 if (long_options_index >= 0) {
678 const int short_option = g_options[long_options_index].short_option;
680 switch (short_option) {
682 m_option_data.m_print_help = true;
686 m_option_data.m_print_version = true;
690 m_option_data.m_print_python_path = true;
694 m_option_data.m_batch = true;
698 SBFileSpec file(optarg);
700 m_option_data.m_core_file = optarg;
702 error.SetErrorStringWithFormat(
703 "file specified in --core (-c) option doesn't exist: '%s'",
708 m_option_data.m_use_external_editor = true;
712 m_debugger.SkipLLDBInitFiles(true);
713 m_debugger.SkipAppInitFiles(true);
717 m_debugger.SetUseColor(false);
721 SBFileSpec file(optarg);
723 m_option_data.m_args.push_back(optarg);
724 } else if (file.ResolveExecutableLocation()) {
726 file.GetPath(path, sizeof(path));
727 m_option_data.m_args.push_back(path);
729 error.SetErrorStringWithFormat(
730 "file specified in --file (-f) option doesn't exist: '%s'",
735 if (!m_debugger.SetDefaultArchitecture(optarg))
736 error.SetErrorStringWithFormat(
737 "invalid architecture in the -a or --arch option: '%s'",
742 m_option_data.m_script_lang = m_debugger.GetScriptingLanguage(optarg);
746 m_option_data.m_debug_mode = true;
750 m_option_data.m_source_quietly = true;
754 m_option_data.AddInitialCommand(optarg, eCommandPlacementAfterCrash,
758 m_option_data.AddInitialCommand(optarg, eCommandPlacementAfterCrash,
763 m_option_data.m_process_name = optarg;
767 m_option_data.m_wait_for = true;
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);
779 m_option_data.m_repl = true;
780 if (optarg && optarg[0])
781 m_option_data.m_repl_options = optarg;
783 m_option_data.m_repl_options.clear();
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\"",
796 m_option_data.AddInitialCommand(optarg, eCommandPlacementAfterFile,
800 m_option_data.AddInitialCommand(optarg, eCommandPlacementAfterFile,
804 m_option_data.AddInitialCommand(optarg, eCommandPlacementBeforeFile,
808 m_option_data.AddInitialCommand(optarg, eCommandPlacementBeforeFile,
812 m_option_data.m_print_help = true;
813 error.SetErrorStringWithFormat("unrecognized option %c",
818 error.SetErrorStringWithFormat("invalid option with value %i", val);
826 if (error.Fail() || m_option_data.m_print_help) {
827 ShowUsage(out_fh, g_options, m_option_data);
829 } else if (m_option_data.m_print_version) {
830 ::fprintf(out_fh, "%s\n", m_debugger.GetVersionString());
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);
840 ::fprintf(out_fh, "<PATH TOO LONG>\n");
842 ::fprintf(out_fh, "<COULD NOT FIND PATH>\n");
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.
852 // Skip any options we consumed with getopt_long_only
857 for (int arg_idx = 0; arg_idx < argc; ++arg_idx) {
858 const char *arg = argv[arg_idx];
860 m_option_data.m_args.push_back(arg);
865 // Skip any options we consumed with getopt_long_only
867 // argv += optind; // Commented out to keep static analyzer happy
871 "Warning: program arguments are ignored when attaching.\n");
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
881 ::FILE *commands_file = NULL;
886 err = _pipe(fds, commands_size, O_BINARY);
891 ssize_t nrwr = write(fds[WRITE], commands_data, commands_size);
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
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");
913 -1; // The FILE * 'commands_file' now owns the read descriptor
914 // Hand ownership if the FILE * over to the debugger for
917 fprintf(stderr, "error: fdopen(%i, \"r\") failed (errno = %i) when "
918 "trying to open LLDB commands pipe\n",
924 "error: can't create pipe file descriptors for LLDB commands\n");
927 return commands_file;
930 void CleanupAfterCommandSourcing(int fds[2]) {
931 enum PIPES { READ, WRITE }; // Constants 0 and 1 for READ and WRITE
933 // Close any pipes that we still have ownership of
934 if (fds[WRITE] != -1) {
944 if (fds[READ] != -1) {
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, '\\');
961 return '"' + arg + '"';
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);
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);
976 ::setbuf(stdout, NULL);
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...
983 m_debugger.SetUseExternalEditor(m_option_data.m_use_external_editor);
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);
992 SBCommandInterpreter sb_interpreter = m_debugger.GetCommandInterpreter();
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());
1003 // Now we handle options we got from the command line
1004 SBStream commands_stream;
1006 // First source in the commands specified to be run before the file arguments
1008 WriteCommandsForSourcing(eCommandPlacementBeforeFile, commands_stream);
1010 const size_t num_args = m_option_data.m_args.size();
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());
1017 commands_stream.Printf("target create %s",
1018 EscapeString(m_option_data.m_args[0]).c_str());
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());
1024 commands_stream.Printf("\n");
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");
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());
1040 if (m_option_data.m_wait_for)
1041 commands_stream.Printf(" --waitfor");
1043 commands_stream.Printf("\n");
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);
1050 WriteCommandsForSourcing(eCommandPlacementAfterFile, commands_stream);
1052 if (GetDebugMode()) {
1053 result.PutError(m_debugger.GetErrorFileHandle());
1054 result.PutOutput(m_debugger.GetOutputFileHandle());
1057 bool handle_events = true;
1058 bool spawn_thread = false;
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));
1066 const char *error_cstr = error.GetCString();
1067 if (error_cstr && error_cstr[0])
1068 fprintf(stderr, "error: %s\n", error_cstr);
1070 fprintf(stderr, "error: %u\n", error.GetError());
1073 // Check if we have any data in the commands stream, and if so, save it to a
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();
1079 // The command file might have requested that we quit, this variable will
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);
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);
1098 SBCommandInterpreterRunOptions options;
1099 options.SetStopOnError(true);
1100 if (m_option_data.m_batch)
1101 options.SetStopOnCrash(true);
1103 m_debugger.RunCommandInterpreter(handle_events, spawn_thread, options,
1104 num_errors, quit_requested,
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);
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;
1129 m_debugger.SetAsync(old_async);
1133 // Close any pipes that we still have ownership of
1134 CleanupAfterCommandSourcing(initial_commands_fds);
1136 // Something went wrong with command pipe
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
1146 bool go_interactive = true;
1148 go_interactive = false;
1149 else if (m_option_data.m_batch && !stopped_for_crash)
1150 go_interactive = false;
1152 if (go_interactive) {
1153 m_debugger.SetInputFileHandle(stdin, true);
1154 m_debugger.RunCommandInterpreter(handle_events, spawn_thread);
1158 reset_stdin_termios();
1161 SBDebugger::Destroy(m_debugger);
1164 void Driver::ResizeWindow(unsigned short col) {
1165 GetDebugger().SetTerminalWidth(col);
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);
1178 void sigint_handler(int signo) {
1179 static bool g_interrupt_sent = false;
1181 if (!g_interrupt_sent) {
1182 g_interrupt_sent = true;
1183 g_driver->GetDebugger().DispatchInputInterrupt();
1184 g_interrupt_sent = false;
1192 void sigtstp_handler(int signo) {
1194 g_driver->GetDebugger().SaveInputTerminalState();
1196 signal(signo, SIG_DFL);
1197 kill(getpid(), signo);
1198 signal(signo, sigtstp_handler);
1201 void sigcont_handler(int signo) {
1203 g_driver->GetDebugger().RestoreInputTerminalState();
1205 signal(signo, SIG_DFL);
1206 kill(getpid(), signo);
1207 signal(signo, sigcont_handler);
1212 wmain(int argc, wchar_t const *wargv[])
1214 main(int argc, char const *argv[])
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();
1225 const char **argv = argvPointers.data();
1228 SBDebugger::Initialize();
1230 SBHostOS::ThreadCreated("<lldb.driver.main-thread>");
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);
1240 // Create a scope for driver so that the driver object will destroy itself
1241 // before SBDebugger::Terminate() is called.
1245 bool exiting = false;
1246 SBError error(driver.ParseArgs(argc, argv, stdout, exiting));
1248 const char *error_cstr = error.GetCString();
1250 ::fprintf(stderr, "error: %s\n", error_cstr);
1251 } else if (!exiting) {
1256 SBDebugger::Terminate();