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()
22 #elif defined(__ANDROID_NDK__)
31 #include "lldb/API/SBBreakpoint.h"
32 #include "lldb/API/SBCommandInterpreter.h"
33 #include "lldb/API/SBCommandReturnObject.h"
34 #include "lldb/API/SBCommunication.h"
35 #include "lldb/API/SBDebugger.h"
36 #include "lldb/API/SBEvent.h"
37 #include "lldb/API/SBHostOS.h"
38 #include "lldb/API/SBLanguageRuntime.h"
39 #include "lldb/API/SBListener.h"
40 #include "lldb/API/SBStream.h"
41 #include "lldb/API/SBTarget.h"
42 #include "lldb/API/SBThread.h"
43 #include "lldb/API/SBProcess.h"
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.
60 reset_stdin_termios ()
62 if (g_old_stdin_termios_is_valid)
64 g_old_stdin_termios_is_valid = false;
65 ::tcsetattr (STDIN_FILENO, TCSANOW, &g_old_stdin_termios);
71 uint32_t usage_mask; // Used to mark options that can be used together. If (1 << n & usage_mask) != 0
72 // then this option belongs to option set n.
73 bool required; // This option is required (in the current usage level)
74 const char * long_option; // Full name for this option.
75 int short_option; // Single character for this option.
76 int option_has_arg; // no_argument, required_argument or optional_argument
77 uint32_t completion_type; // Cookie the option class can use to do define the argument completion.
78 lldb::CommandArgumentType argument_type; // Type of argument this option takes
79 const char * usage_text; // Full text explaining what this options does and what (if any) argument to
83 #define LLDB_3_TO_5 LLDB_OPT_SET_3|LLDB_OPT_SET_4|LLDB_OPT_SET_5
84 #define LLDB_4_TO_5 LLDB_OPT_SET_4|LLDB_OPT_SET_5
86 static OptionDefinition g_options[] =
88 { LLDB_OPT_SET_1, true , "help" , 'h', no_argument , 0, eArgTypeNone,
89 "Prints out the usage information for the LLDB debugger." },
90 { LLDB_OPT_SET_2, true , "version" , 'v', no_argument , 0, eArgTypeNone,
91 "Prints out the current version number of the LLDB debugger." },
92 { LLDB_OPT_SET_3, true , "arch" , 'a', required_argument, 0, eArgTypeArchitecture,
93 "Tells the debugger to use the specified architecture when starting and running the program. <architecture> must "
94 "be one of the architectures for which the program was compiled." },
95 { LLDB_OPT_SET_3, true , "file" , 'f', required_argument, 0, eArgTypeFilename,
96 "Tells the debugger to use the file <filename> as the program to be debugged." },
97 { LLDB_OPT_SET_3, false, "core" , 'c', required_argument, 0, eArgTypeFilename,
98 "Tells the debugger to use the fullpath to <path> as the core file." },
99 { LLDB_OPT_SET_5, true , "attach-pid" , 'p', required_argument, 0, eArgTypePid,
100 "Tells the debugger to attach to a process with the given pid." },
101 { LLDB_OPT_SET_4, true , "attach-name" , 'n', required_argument, 0, eArgTypeProcessName,
102 "Tells the debugger to attach to a process with the given name." },
103 { LLDB_OPT_SET_4, true , "wait-for" , 'w', no_argument , 0, eArgTypeNone,
104 "Tells the debugger to wait for a process with the given pid or name to launch before attaching." },
105 { LLDB_3_TO_5, false, "source" , 's', required_argument, 0, eArgTypeFilename,
106 "Tells the debugger to read in and execute the lldb commands in the given file, after any file provided on the command line has been loaded." },
107 { LLDB_3_TO_5, false, "one-line" , 'o', required_argument, 0, eArgTypeNone,
108 "Tells the debugger to execute this one-line lldb command after any file provided on the command line has been loaded." },
109 { LLDB_3_TO_5, false, "source-before-file" , 'S', required_argument, 0, eArgTypeFilename,
110 "Tells the debugger to read in and execute the lldb commands in the given file, before any file provided on the command line has been loaded." },
111 { LLDB_3_TO_5, false, "one-line-before-file" , 'O', required_argument, 0, eArgTypeNone,
112 "Tells the debugger to execute this one-line lldb command before any file provided on the command line has been loaded." },
113 { LLDB_3_TO_5, false, "one-line-on-crash" , 'k', required_argument, 0, eArgTypeNone,
114 "When in batch mode, tells the debugger to execute this one-line lldb command if the target crashes." },
115 { LLDB_3_TO_5, false, "source-on-crash" , 'K', required_argument, 0, eArgTypeFilename,
116 "When in batch mode, tells the debugger to source this file of lldb commands if the target crashes." },
117 { LLDB_3_TO_5, false, "source-quietly" , 'Q', no_argument , 0, eArgTypeNone,
118 "Tells the debugger to execute this one-line lldb command before any file provided on the command line has been loaded." },
119 { LLDB_3_TO_5, false, "batch" , 'b', no_argument , 0, eArgTypeNone,
120 "Tells the debugger to running the commands from -s, -S, -o & -O, and then quit. However if any run command stopped due to a signal or crash, "
121 "the debugger will return to the interactive prompt at the place of the crash." },
122 { LLDB_3_TO_5, false, "editor" , 'e', no_argument , 0, eArgTypeNone,
123 "Tells the debugger to open source files using the host's \"external editor\" mechanism." },
124 { LLDB_3_TO_5, false, "no-lldbinit" , 'x', no_argument , 0, eArgTypeNone,
125 "Do not automatically parse any '.lldbinit' files." },
126 { LLDB_3_TO_5, false, "no-use-colors" , 'X', no_argument , 0, eArgTypeNone,
127 "Do not use colors." },
128 { LLDB_OPT_SET_6, true , "python-path" , 'P', no_argument , 0, eArgTypeNone,
129 "Prints out the path to the lldb.py file for this version of lldb." },
130 { LLDB_3_TO_5, false, "script-language", 'l', required_argument, 0, eArgTypeScriptLang,
131 "Tells the debugger to use the specified scripting language for user-defined scripts, rather than the default. "
132 "Valid scripting languages that can be specified include Python, Perl, Ruby and Tcl. Currently only the Python "
133 "extensions have been implemented." },
134 { LLDB_3_TO_5, false, "debug" , 'd', no_argument , 0, eArgTypeNone,
135 "Tells the debugger to print out extra information for debugging itself." },
136 { LLDB_OPT_SET_7, true , "repl" , 'r', optional_argument, 0, eArgTypeNone,
137 "Runs lldb in REPL mode with a stub process." },
138 { LLDB_OPT_SET_7, true , "repl-language" , 'R', required_argument, 0, eArgTypeNone,
139 "Chooses the language for the REPL." },
140 { 0, false, NULL , 0 , 0 , 0, eArgTypeNone, NULL }
143 static const uint32_t last_option_set_with_args = 2;
146 SBBroadcaster ("Driver"),
147 m_debugger (SBDebugger::Create(false)),
150 // We want to be able to handle CTRL+D in the terminal to have it terminate
152 m_debugger.SetCloseInputOnEOF (false);
162 // This function takes INDENT, which tells how many spaces to output at the front
163 // of each line; TEXT, which is the text that is to be output. It outputs the
164 // text, on multiple lines if necessary, to RESULT, with INDENT spaces at the
165 // front of each line. It breaks lines on spaces, tabs or newlines, shortening
166 // the line if necessary to not break in the middle of a word. It assumes that
167 // each output line should contain a maximum of OUTPUT_MAX_COLUMNS characters.
170 OutputFormattedUsageText (FILE *out, int indent, const char *text, int output_max_columns)
172 int len = strlen (text);
173 std::string text_string (text);
175 // Force indentation to be reasonable.
176 if (indent >= output_max_columns)
179 // Will it all fit on one line?
181 if (len + indent < output_max_columns)
182 // Output as a single line
183 fprintf (out, "%*s%s\n", indent, "", text);
186 // We need to break it up into multiple lines.
187 int text_width = output_max_columns - indent - 1;
193 while (end < final_end)
195 // Dont start the 'text' on a space, since we're already outputting the indentation.
196 while ((start < final_end) && (text[start] == ' '))
199 end = start + text_width;
204 // If we're not at the end of the text, make sure we break the line on white space.
206 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
209 sub_len = end - start;
210 std::string substring = text_string.substr (start, sub_len);
211 fprintf (out, "%*s%s\n", indent, "", substring.c_str());
218 ShowUsage (FILE *out, OptionDefinition *option_table, Driver::OptionData data)
220 uint32_t screen_width = 80;
221 uint32_t indent_level = 0;
222 const char *name = "lldb";
224 fprintf (out, "\nUsage:\n\n");
229 // First, show each usage level set of options, e.g. <cmd> [options-for-level-0]
230 // <cmd> [options-for-level-1]
233 uint32_t num_options;
234 uint32_t num_option_sets = 0;
236 for (num_options = 0; option_table[num_options].long_option != NULL; ++num_options)
238 uint32_t this_usage_mask = option_table[num_options].usage_mask;
239 if (this_usage_mask == LLDB_OPT_SET_ALL)
241 if (num_option_sets == 0)
246 for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++)
248 if (this_usage_mask & 1 << j)
250 if (num_option_sets <= j)
251 num_option_sets = j + 1;
257 for (uint32_t opt_set = 0; opt_set < num_option_sets; opt_set++)
259 uint32_t opt_set_mask;
261 opt_set_mask = 1 << opt_set;
265 fprintf (out, "%*s%s", indent_level, "", name);
266 bool is_help_line = false;
268 for (uint32_t i = 0; i < num_options; ++i)
270 if (option_table[i].usage_mask & opt_set_mask)
272 CommandArgumentType arg_type = option_table[i].argument_type;
273 const char *arg_name = SBCommandInterpreter::GetArgumentTypeAsCString (arg_type);
274 // This is a bit of a hack, but there's no way to say certain options don't have arguments yet...
275 // so we do it by hand here.
276 if (option_table[i].short_option == 'h')
279 if (option_table[i].required)
281 if (option_table[i].option_has_arg == required_argument)
282 fprintf (out, " -%c <%s>", option_table[i].short_option, arg_name);
283 else if (option_table[i].option_has_arg == optional_argument)
284 fprintf (out, " -%c [<%s>]", option_table[i].short_option, arg_name);
286 fprintf (out, " -%c", option_table[i].short_option);
290 if (option_table[i].option_has_arg == required_argument)
291 fprintf (out, " [-%c <%s>]", option_table[i].short_option, arg_name);
292 else if (option_table[i].option_has_arg == optional_argument)
293 fprintf (out, " [-%c [<%s>]]", option_table[i].short_option, arg_name);
295 fprintf (out, " [-%c]", option_table[i].short_option);
299 if (!is_help_line && (opt_set <= last_option_set_with_args))
300 fprintf (out, " [[--] <PROGRAM-ARG-1> [<PROGRAM_ARG-2> ...]]");
303 fprintf (out, "\n\n");
305 // Now print out all the detailed information about the various options: long form, short form and help text:
306 // -- long_name <argument>
307 // - short <argument>
310 // This variable is used to keep track of which options' info we've printed out, because some options can be in
311 // more than one usage level, but we only want to print the long form of its information once.
313 Driver::OptionData::OptionSet options_seen;
314 Driver::OptionData::OptionSet::iterator pos;
318 for (uint32_t i = 0; i < num_options; ++i)
320 // Only print this option if we haven't already seen it.
321 pos = options_seen.find (option_table[i].short_option);
322 if (pos == options_seen.end())
324 CommandArgumentType arg_type = option_table[i].argument_type;
325 const char *arg_name = SBCommandInterpreter::GetArgumentTypeAsCString (arg_type);
327 options_seen.insert (option_table[i].short_option);
328 fprintf (out, "%*s-%c ", indent_level, "", option_table[i].short_option);
329 if (arg_type != eArgTypeNone)
330 fprintf (out, "<%s>", arg_name);
332 fprintf (out, "%*s--%s ", indent_level, "", option_table[i].long_option);
333 if (arg_type != eArgTypeNone)
334 fprintf (out, "<%s>", arg_name);
337 OutputFormattedUsageText (out, indent_level, option_table[i].usage_text, screen_width);
345 fprintf (out, "\n%*sNotes:\n",
349 fprintf (out, "\n%*sMultiple \"-s\" and \"-o\" options can be provided. They will be processed"
350 "\n%*sfrom left to right in order, with the source files and commands"
351 "\n%*sinterleaved. The same is true of the \"-S\" and \"-O\" options. The before"
352 "\n%*sfile and after file sets can intermixed freely, the command parser will"
353 "\n%*ssort them out. The order of the file specifiers (\"-c\", \"-f\", etc.) is"
354 "\n%*snot significant in this regard.\n\n",
362 fprintf (out, "\n%*sIf you don't provide -f then the first argument will be the file to be"
363 "\n%*sdebugged which means that '%s -- <filename> [<ARG1> [<ARG2>]]' also"
364 "\n%*sworks. But remember to end the options with \"--\" if any of your"
365 "\n%*sarguments have a \"-\" in them.\n\n",
374 BuildGetOptTable (OptionDefinition *expanded_option_table, std::vector<struct option> &getopt_table,
375 uint32_t num_options)
377 if (num_options == 0)
382 std::bitset<256> option_seen;
384 getopt_table.resize (num_options + 1);
386 for (i = 0, j = 0; i < num_options; ++i)
388 char short_opt = expanded_option_table[i].short_option;
390 if (option_seen.test(short_opt) == false)
392 getopt_table[j].name = expanded_option_table[i].long_option;
393 getopt_table[j].has_arg = expanded_option_table[i].option_has_arg;
394 getopt_table[j].flag = NULL;
395 getopt_table[j].val = expanded_option_table[i].short_option;
396 option_seen.set(short_opt);
401 getopt_table[j].name = NULL;
402 getopt_table[j].has_arg = 0;
403 getopt_table[j].flag = NULL;
404 getopt_table[j].val = 0;
408 Driver::OptionData::OptionData () :
410 m_script_lang (lldb::eScriptLanguageDefault),
413 m_initial_commands (),
414 m_after_file_commands (),
415 m_after_crash_commands(),
416 m_debug_mode (false),
417 m_source_quietly(false),
418 m_print_version (false),
419 m_print_python_path (false),
420 m_print_help (false),
423 m_repl_lang (eLanguageTypeUnknown),
426 m_process_pid(LLDB_INVALID_PROCESS_ID),
427 m_use_external_editor(false),
433 Driver::OptionData::~OptionData ()
438 Driver::OptionData::Clear ()
441 m_script_lang = lldb::eScriptLanguageDefault;
442 m_initial_commands.clear ();
443 m_after_file_commands.clear ();
444 // If there is a local .lldbinit, source that:
445 SBFileSpec local_lldbinit("./.lldbinit", true);
446 if (local_lldbinit.Exists())
449 local_lldbinit.GetPath(path, 2047);
450 InitialCmdEntry entry(path, true, true);
451 m_after_file_commands.push_back (entry);
454 m_debug_mode = false;
455 m_source_quietly = false;
456 m_print_help = false;
457 m_print_version = false;
458 m_print_python_path = false;
459 m_use_external_editor = false;
461 m_process_name.erase();
463 m_after_crash_commands.clear();
465 m_process_pid = LLDB_INVALID_PROCESS_ID;
469 Driver::OptionData::AddInitialCommand (const char *command, CommandPlacement placement, bool is_file, SBError &error)
471 std::vector<InitialCmdEntry> *command_set;
474 case eCommandPlacementBeforeFile:
475 command_set = &(m_initial_commands);
477 case eCommandPlacementAfterFile:
478 command_set = &(m_after_file_commands);
480 case eCommandPlacementAfterCrash:
481 command_set = &(m_after_crash_commands);
487 SBFileSpec file(command);
489 command_set->push_back (InitialCmdEntry(command, is_file));
490 else if (file.ResolveExecutableLocation())
492 char final_path[PATH_MAX];
493 file.GetPath (final_path, sizeof(final_path));
494 command_set->push_back (InitialCmdEntry(final_path, is_file));
497 error.SetErrorStringWithFormat("file specified in --source (-s) option doesn't exist: '%s'", optarg);
500 command_set->push_back (InitialCmdEntry(command, is_file));
504 Driver::ResetOptionValues ()
506 m_option_data.Clear ();
510 Driver::GetFilename() const
512 if (m_option_data.m_args.empty())
514 return m_option_data.m_args.front().c_str();
518 Driver::GetCrashLogFilename() const
520 if (m_option_data.m_crash_log.empty())
522 return m_option_data.m_crash_log.c_str();
526 Driver::GetScriptLanguage() const
528 return m_option_data.m_script_lang;
532 Driver::WriteCommandsForSourcing (CommandPlacement placement, SBStream &strm)
534 std::vector<OptionData::InitialCmdEntry> *command_set;
537 case eCommandPlacementBeforeFile:
538 command_set = &m_option_data.m_initial_commands;
540 case eCommandPlacementAfterFile:
541 command_set = &m_option_data.m_after_file_commands;
543 case eCommandPlacementAfterCrash:
544 command_set = &m_option_data.m_after_crash_commands;
548 for (const auto &command_entry : *command_set)
550 const char *command = command_entry.contents.c_str();
551 if (command_entry.is_file)
553 bool source_quietly = m_option_data.m_source_quietly || command_entry.source_quietly;
554 strm.Printf("command source -s %i '%s'\n", source_quietly, command);
557 strm.Printf("%s\n", command);
562 Driver::GetDebugMode() const
564 return m_option_data.m_debug_mode;
568 // Check the arguments that were passed to this program to make sure they are valid and to get their
569 // argument values (if any). Return a boolean value indicating whether or not to start up the full
570 // debugger (i.e. the Command Interpreter) or not. Return FALSE if the arguments were invalid OR
571 // if the user only wanted help or version information.
574 Driver::ParseArgs (int argc, const char *argv[], FILE *out_fh, bool &exiting)
576 ResetOptionValues ();
578 SBCommandReturnObject result;
581 std::string option_string;
582 struct option *long_options = NULL;
583 std::vector<struct option> long_options_vector;
584 uint32_t num_options;
586 for (num_options = 0; g_options[num_options].long_option != NULL; ++num_options)
589 if (num_options == 0)
592 error.SetErrorStringWithFormat ("invalid number of options");
596 BuildGetOptTable (g_options, long_options_vector, num_options);
598 if (long_options_vector.empty())
601 long_options = &long_options_vector.front();
603 if (long_options == NULL)
605 error.SetErrorStringWithFormat ("invalid long options");
609 // Build the option_string argument for call to getopt_long_only.
611 for (int i = 0; long_options[i].name != NULL; ++i)
613 if (long_options[i].flag == NULL)
615 option_string.push_back ((char) long_options[i].val);
616 switch (long_options[i].has_arg)
621 case required_argument:
622 option_string.push_back (':');
624 case optional_argument:
625 option_string.append ("::");
631 // This is kind of a pain, but since we make the debugger in the Driver's constructor, we can't
632 // know at that point whether we should read in init files yet. So we don't read them in in the
633 // Driver constructor, then set the flags back to "read them in" here, and then if we see the
634 // "-n" flag, we'll turn it off again. Finally we have to read them in by hand later in the
637 m_debugger.SkipLLDBInitFiles (false);
638 m_debugger.SkipAppInitFiles (false);
640 // Prepare for & make calls to getopt_long_only.
650 int long_options_index = -1;
651 val = ::getopt_long_only (argc, const_cast<char **>(argv), option_string.c_str(), long_options, &long_options_index);
657 m_option_data.m_print_help = true;
658 error.SetErrorStringWithFormat ("unknown or ambiguous option");
665 m_option_data.m_seen_options.insert ((char) val);
666 if (long_options_index == -1)
669 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val;
672 if (long_options[i].val == val)
674 long_options_index = i;
680 if (long_options_index >= 0)
682 const int short_option = g_options[long_options_index].short_option;
684 switch (short_option)
687 m_option_data.m_print_help = true;
691 m_option_data.m_print_version = true;
695 m_option_data.m_print_python_path = true;
699 m_option_data.m_batch = true;
704 SBFileSpec file(optarg);
707 m_option_data.m_core_file = optarg;
710 error.SetErrorStringWithFormat("file specified in --core (-c) option doesn't exist: '%s'", optarg);
715 m_option_data.m_use_external_editor = true;
719 m_debugger.SkipLLDBInitFiles (true);
720 m_debugger.SkipAppInitFiles (true);
724 m_debugger.SetUseColor (false);
729 SBFileSpec file(optarg);
732 m_option_data.m_args.push_back (optarg);
734 else if (file.ResolveExecutableLocation())
737 file.GetPath (path, sizeof(path));
738 m_option_data.m_args.push_back (path);
741 error.SetErrorStringWithFormat("file specified in --file (-f) option doesn't exist: '%s'", optarg);
746 if (!m_debugger.SetDefaultArchitecture (optarg))
747 error.SetErrorStringWithFormat("invalid architecture in the -a or --arch option: '%s'", optarg);
751 m_option_data.m_script_lang = m_debugger.GetScriptingLanguage (optarg);
755 m_option_data.m_debug_mode = true;
759 m_option_data.m_source_quietly = true;
763 m_option_data.AddInitialCommand(optarg, eCommandPlacementAfterCrash, true, error);
766 m_option_data.AddInitialCommand(optarg, eCommandPlacementAfterCrash, false, error);
770 m_option_data.m_process_name = optarg;
774 m_option_data.m_wait_for = true;
780 m_option_data.m_process_pid = strtol (optarg, &remainder, 0);
781 if (remainder == optarg || *remainder != '\0')
782 error.SetErrorStringWithFormat ("Could not convert process PID: \"%s\" into a pid.",
788 m_option_data.m_repl = true;
789 if (optarg && optarg[0])
790 m_option_data.m_repl_options = optarg;
792 m_option_data.m_repl_options.clear();
796 m_option_data.m_repl_lang = SBLanguageRuntime::GetLanguageTypeFromString (optarg);
797 if (m_option_data.m_repl_lang == eLanguageTypeUnknown)
799 error.SetErrorStringWithFormat ("Unrecognized language name: \"%s\"", optarg);
804 m_option_data.AddInitialCommand(optarg, eCommandPlacementAfterFile, true, error);
807 m_option_data.AddInitialCommand(optarg, eCommandPlacementAfterFile, false, error);
810 m_option_data.AddInitialCommand(optarg, eCommandPlacementBeforeFile, true, error);
813 m_option_data.AddInitialCommand(optarg, eCommandPlacementBeforeFile, false, error);
816 m_option_data.m_print_help = true;
817 error.SetErrorStringWithFormat ("unrecognized option %c", short_option);
823 error.SetErrorStringWithFormat ("invalid option with value %i", val);
832 if (error.Fail() || m_option_data.m_print_help)
834 ShowUsage (out_fh, g_options, m_option_data);
837 else if (m_option_data.m_print_version)
839 ::fprintf (out_fh, "%s\n", m_debugger.GetVersionString());
842 else if (m_option_data.m_print_python_path)
844 SBFileSpec python_file_spec = SBHostOS::GetLLDBPythonPath();
845 if (python_file_spec.IsValid())
847 char python_path[PATH_MAX];
848 size_t num_chars = python_file_spec.GetPath(python_path, PATH_MAX);
849 if (num_chars < PATH_MAX)
851 ::fprintf (out_fh, "%s\n", python_path);
854 ::fprintf (out_fh, "<PATH TOO LONG>\n");
857 ::fprintf (out_fh, "<COULD NOT FIND PATH>\n");
860 else if (m_option_data.m_process_name.empty() && m_option_data.m_process_pid == LLDB_INVALID_PROCESS_ID)
862 // Any arguments that are left over after option parsing are for
863 // the program. If a file was specified with -f then the filename
864 // is already in the m_option_data.m_args array, and any remaining args
865 // are arguments for the inferior program. If no file was specified with
866 // -f, then what is left is the program name followed by any arguments.
868 // Skip any options we consumed with getopt_long_only
874 for (int arg_idx=0; arg_idx<argc; ++arg_idx)
876 const char *arg = argv[arg_idx];
878 m_option_data.m_args.push_back (arg);
885 // Skip any options we consumed with getopt_long_only
887 //argv += optind; // Commented out to keep static analyzer happy
890 ::fprintf (out_fh, "Warning: program arguments are ignored when attaching.\n");
897 PrepareCommandsForSourcing (const char *commands_data, size_t commands_size, int fds[2])
899 enum PIPES { READ, WRITE }; // Constants 0 and 1 for READ and WRITE
901 ::FILE *commands_file = NULL;
906 err = _pipe(fds, commands_size, O_BINARY);
912 ssize_t nrwr = write(fds[WRITE], commands_data, commands_size);
915 fprintf(stderr, "error: write(%i, %p, %" PRIu64 ") failed (errno = %i) "
916 "when trying to open LLDB commands pipe\n",
917 fds[WRITE], commands_data, static_cast<uint64_t>(commands_size), errno);
919 else if (static_cast<size_t>(nrwr) == commands_size)
921 // Close the write end of the pipe so when we give the read end to
922 // the debugger/command interpreter it will exit when it consumes all
925 _close(fds[WRITE]); fds[WRITE] = -1;
927 close(fds[WRITE]); fds[WRITE] = -1;
929 // Now open the read file descriptor in a FILE * that we can give to
930 // the debugger as an input handle
931 commands_file = fdopen(fds[READ], "r");
934 fds[READ] = -1; // The FILE * 'commands_file' now owns the read descriptor
935 // Hand ownership if the FILE * over to the debugger for "commands_file".
940 "error: fdopen(%i, \"r\") failed (errno = %i) when "
941 "trying to open LLDB commands pipe\n",
948 fprintf(stderr, "error: can't create pipe file descriptors for LLDB commands\n");
951 return commands_file;
955 CleanupAfterCommandSourcing (int fds[2])
957 enum PIPES { READ, WRITE }; // Constants 0 and 1 for READ and WRITE
959 // Close any pipes that we still have ownership of
960 if ( fds[WRITE] != -1)
963 _close(fds[WRITE]); fds[WRITE] = -1;
965 close(fds[WRITE]); fds[WRITE] = -1;
970 if ( fds[READ] != -1)
973 _close(fds[READ]); fds[READ] = -1;
975 close(fds[READ]); fds[READ] = -1;
982 EscapeString (std::string arg)
984 std::string::size_type pos = 0;
985 while ((pos = arg.find_first_of("\"\\", pos)) != std::string::npos)
987 arg.insert (pos, 1, '\\');
990 return '"' + arg + '"';
996 if (::tcgetattr(STDIN_FILENO, &g_old_stdin_termios) == 0)
998 g_old_stdin_termios_is_valid = true;
999 atexit (reset_stdin_termios);
1002 ::setbuf (stdin, NULL);
1003 ::setbuf (stdout, NULL);
1005 m_debugger.SetErrorFileHandle (stderr, false);
1006 m_debugger.SetOutputFileHandle (stdout, false);
1007 m_debugger.SetInputFileHandle (stdin, false); // Don't take ownership of STDIN yet...
1009 m_debugger.SetUseExternalEditor(m_option_data.m_use_external_editor);
1011 struct winsize window_size;
1012 if (isatty (STDIN_FILENO)
1013 && ::ioctl (STDIN_FILENO, TIOCGWINSZ, &window_size) == 0)
1015 if (window_size.ws_col > 0)
1016 m_debugger.SetTerminalWidth (window_size.ws_col);
1019 SBCommandInterpreter sb_interpreter = m_debugger.GetCommandInterpreter();
1021 // Before we handle any options from the command line, we parse the
1022 // .lldbinit file in the user's home directory.
1023 SBCommandReturnObject result;
1024 sb_interpreter.SourceInitFileInHomeDirectory(result);
1027 result.PutError (m_debugger.GetErrorFileHandle());
1028 result.PutOutput (m_debugger.GetOutputFileHandle());
1031 // Now we handle options we got from the command line
1032 SBStream commands_stream;
1034 // First source in the commands specified to be run before the file arguments are processed.
1035 WriteCommandsForSourcing(eCommandPlacementBeforeFile, commands_stream);
1037 const size_t num_args = m_option_data.m_args.size();
1041 if (m_debugger.GetDefaultArchitecture (arch_name, sizeof (arch_name)))
1042 commands_stream.Printf("target create --arch=%s %s", arch_name, EscapeString(m_option_data.m_args[0]).c_str());
1044 commands_stream.Printf("target create %s", EscapeString(m_option_data.m_args[0]).c_str());
1046 if (!m_option_data.m_core_file.empty())
1048 commands_stream.Printf(" --core %s", EscapeString(m_option_data.m_core_file).c_str());
1050 commands_stream.Printf("\n");
1054 commands_stream.Printf ("settings set -- target.run-args ");
1055 for (size_t arg_idx = 1; arg_idx < num_args; ++arg_idx)
1056 commands_stream.Printf(" %s", EscapeString(m_option_data.m_args[arg_idx]).c_str());
1057 commands_stream.Printf("\n");
1060 else if (!m_option_data.m_core_file.empty())
1062 commands_stream.Printf("target create --core %s\n", EscapeString(m_option_data.m_core_file).c_str());
1064 else if (!m_option_data.m_process_name.empty())
1066 commands_stream.Printf ("process attach --name %s", EscapeString(m_option_data.m_process_name).c_str());
1068 if (m_option_data.m_wait_for)
1069 commands_stream.Printf(" --waitfor");
1071 commands_stream.Printf("\n");
1074 else if (LLDB_INVALID_PROCESS_ID != m_option_data.m_process_pid)
1076 commands_stream.Printf ("process attach --pid %" PRIu64 "\n", m_option_data.m_process_pid);
1079 WriteCommandsForSourcing(eCommandPlacementAfterFile, commands_stream);
1083 result.PutError(m_debugger.GetErrorFileHandle());
1084 result.PutOutput(m_debugger.GetOutputFileHandle());
1087 bool handle_events = true;
1088 bool spawn_thread = false;
1090 if (m_option_data.m_repl)
1092 const char *repl_options = NULL;
1093 if (!m_option_data.m_repl_options.empty())
1094 repl_options = m_option_data.m_repl_options.c_str();
1095 SBError error (m_debugger.RunREPL(m_option_data.m_repl_lang, repl_options));
1098 const char *error_cstr = error.GetCString();
1099 if (error_cstr && error_cstr[0])
1100 fprintf (stderr, "error: %s\n", error_cstr);
1102 fprintf (stderr, "error: %u\n", error.GetError());
1107 // Check if we have any data in the commands stream, and if so, save it to a temp file
1108 // so we can then run the command interpreter using the file contents.
1109 const char *commands_data = commands_stream.GetData();
1110 const size_t commands_size = commands_stream.GetSize();
1112 // The command file might have requested that we quit, this variable will track that.
1113 bool quit_requested = false;
1114 bool stopped_for_crash = false;
1115 if (commands_data && commands_size)
1117 int initial_commands_fds[2];
1118 bool success = true;
1119 FILE *commands_file = PrepareCommandsForSourcing (commands_data, commands_size, initial_commands_fds);
1122 m_debugger.SetInputFileHandle (commands_file, true);
1124 // Set the debugger into Sync mode when running the command file. Otherwise command files
1125 // that run the target won't run in a sensible way.
1126 bool old_async = m_debugger.GetAsync();
1127 m_debugger.SetAsync(false);
1130 SBCommandInterpreterRunOptions options;
1131 options.SetStopOnError (true);
1132 if (m_option_data.m_batch)
1133 options.SetStopOnCrash (true);
1135 m_debugger.RunCommandInterpreter(handle_events,
1142 if (m_option_data.m_batch && stopped_for_crash && !m_option_data.m_after_crash_commands.empty())
1144 int crash_command_fds[2];
1145 SBStream crash_commands_stream;
1146 WriteCommandsForSourcing (eCommandPlacementAfterCrash, crash_commands_stream);
1147 const char *crash_commands_data = crash_commands_stream.GetData();
1148 const size_t crash_commands_size = crash_commands_stream.GetSize();
1149 commands_file = PrepareCommandsForSourcing (crash_commands_data, crash_commands_size, crash_command_fds);
1152 bool local_quit_requested;
1153 bool local_stopped_for_crash;
1154 m_debugger.SetInputFileHandle (commands_file, true);
1156 m_debugger.RunCommandInterpreter(handle_events,
1160 local_quit_requested,
1161 local_stopped_for_crash);
1162 if (local_quit_requested)
1163 quit_requested = true;
1167 m_debugger.SetAsync(old_async);
1172 // Close any pipes that we still have ownership of
1173 CleanupAfterCommandSourcing(initial_commands_fds);
1175 // Something went wrong with command pipe
1183 // Now set the input file handle to STDIN and run the command
1184 // interpreter again in interactive mode and let the debugger
1185 // take ownership of stdin
1187 bool go_interactive = true;
1189 go_interactive = false;
1190 else if (m_option_data.m_batch && !stopped_for_crash)
1191 go_interactive = false;
1195 m_debugger.SetInputFileHandle (stdin, true);
1196 m_debugger.RunCommandInterpreter(handle_events, spawn_thread);
1200 reset_stdin_termios();
1203 SBDebugger::Destroy (m_debugger);
1208 Driver::ResizeWindow (unsigned short col)
1210 GetDebugger().SetTerminalWidth (col);
1214 sigwinch_handler (int signo)
1216 struct winsize window_size;
1217 if (isatty (STDIN_FILENO)
1218 && ::ioctl (STDIN_FILENO, TIOCGWINSZ, &window_size) == 0)
1220 if ((window_size.ws_col > 0) && g_driver != NULL)
1222 g_driver->ResizeWindow (window_size.ws_col);
1228 sigint_handler (int signo)
1230 static bool g_interrupt_sent = false;
1233 if (!g_interrupt_sent)
1235 g_interrupt_sent = true;
1236 g_driver->GetDebugger().DispatchInputInterrupt();
1237 g_interrupt_sent = false;
1246 sigtstp_handler (int signo)
1248 g_driver->GetDebugger().SaveInputTerminalState();
1249 signal (signo, SIG_DFL);
1250 kill (getpid(), signo);
1251 signal (signo, sigtstp_handler);
1255 sigcont_handler (int signo)
1257 g_driver->GetDebugger().RestoreInputTerminalState();
1258 signal (signo, SIG_DFL);
1259 kill (getpid(), signo);
1260 signal (signo, sigcont_handler);
1264 main (int argc, char const *argv[], const char *envp[])
1267 // disable buffering on windows
1268 setvbuf(stdout, NULL, _IONBF, 0);
1269 setvbuf(stdin , NULL, _IONBF, 0);
1272 SBDebugger::Initialize();
1274 SBHostOS::ThreadCreated ("<lldb.driver.main-thread>");
1276 signal (SIGPIPE, SIG_IGN);
1277 signal (SIGWINCH, sigwinch_handler);
1278 signal (SIGINT, sigint_handler);
1279 signal (SIGTSTP, sigtstp_handler);
1280 signal (SIGCONT, sigcont_handler);
1282 // Create a scope for driver so that the driver object will destroy itself
1283 // before SBDebugger::Terminate() is called.
1287 bool exiting = false;
1288 SBError error (driver.ParseArgs (argc, argv, stdout, exiting));
1291 const char *error_cstr = error.GetCString ();
1293 ::fprintf (stderr, "error: %s\n", error_cstr);
1301 SBDebugger::Terminate();