blob: 96fd4cfc038cb44ef3fce863f5a37b523db09844 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- 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 <getopt.h>
13#include <libgen.h>
14#include <sys/ioctl.h>
15#include <termios.h>
16#include <unistd.h>
Eli Friedmana382d472010-06-09 09:50:17 +000017#include <string.h>
18#include <stdlib.h>
19#include <limits.h>
Eli Friedman07b16272010-06-09 19:11:30 +000020#include <fcntl.h>
Daniel Malead01b2952012-11-29 21:49:15 +000021#include <inttypes.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022
23#include <string>
24
25#include "IOChannel.h"
Jim Inghame6bc6cb2012-02-08 05:23:15 +000026#include "lldb/API/SBBreakpoint.h"
Eli Friedmana382d472010-06-09 09:50:17 +000027#include "lldb/API/SBCommandInterpreter.h"
28#include "lldb/API/SBCommandReturnObject.h"
29#include "lldb/API/SBCommunication.h"
30#include "lldb/API/SBDebugger.h"
31#include "lldb/API/SBEvent.h"
32#include "lldb/API/SBHostOS.h"
33#include "lldb/API/SBListener.h"
Jim Ingham85e8b812011-02-19 02:53:09 +000034#include "lldb/API/SBStream.h"
Eli Friedmana382d472010-06-09 09:50:17 +000035#include "lldb/API/SBTarget.h"
36#include "lldb/API/SBThread.h"
37#include "lldb/API/SBProcess.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000038
39using namespace lldb;
40
41static void reset_stdin_termios ();
Greg Claytonf571b892012-02-02 19:28:31 +000042static bool g_old_stdin_termios_is_valid = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043static struct termios g_old_stdin_termios;
44
Caroline Ticedd759852010-09-09 17:45:09 +000045static char *g_debugger_name = (char *) "";
Caroline Ticeefed6132010-11-19 20:47:54 +000046static Driver *g_driver = NULL;
Caroline Ticedd759852010-09-09 17:45:09 +000047
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048// In the Driver::MainLoop, we change the terminal settings. This function is
49// added as an atexit handler to make sure we clean them up.
50static void
51reset_stdin_termios ()
52{
Greg Claytonf571b892012-02-02 19:28:31 +000053 if (g_old_stdin_termios_is_valid)
54 {
55 g_old_stdin_termios_is_valid = false;
56 ::tcsetattr (STDIN_FILENO, TCSANOW, &g_old_stdin_termios);
57 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +000058}
59
Greg Claytone0d378b2011-03-24 21:19:54 +000060typedef struct
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061{
Greg Claytone0d378b2011-03-24 21:19:54 +000062 uint32_t usage_mask; // Used to mark options that can be used together. If (1 << n & usage_mask) != 0
63 // then this option belongs to option set n.
64 bool required; // This option is required (in the current usage level)
65 const char * long_option; // Full name for this option.
Greg Clayton3bcdfc02012-12-04 00:32:51 +000066 int short_option; // Single character for this option.
Greg Claytone0d378b2011-03-24 21:19:54 +000067 int option_has_arg; // no_argument, required_argument or optional_argument
Greg Claytonab65b342011-04-13 22:47:15 +000068 uint32_t completion_type; // Cookie the option class can use to do define the argument completion.
Greg Claytone0d378b2011-03-24 21:19:54 +000069 lldb::CommandArgumentType argument_type; // Type of argument this option takes
70 const char * usage_text; // Full text explaining what this options does and what (if any) argument to
71 // pass it.
72} OptionDefinition;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000073
Jim Inghame64f0dc2011-09-13 23:25:31 +000074#define LLDB_3_TO_5 LLDB_OPT_SET_3|LLDB_OPT_SET_4|LLDB_OPT_SET_5
75#define LLDB_4_TO_5 LLDB_OPT_SET_4|LLDB_OPT_SET_5
76
Greg Claytone0d378b2011-03-24 21:19:54 +000077static OptionDefinition g_options[] =
78{
Filipe Cabecinhasd0b87d82012-09-11 18:11:16 +000079 { LLDB_OPT_SET_1, true , "help" , 'h', no_argument , 0, eArgTypeNone,
Jim Ingham12e9a202011-09-15 21:30:02 +000080 "Prints out the usage information for the LLDB debugger." },
Filipe Cabecinhasd0b87d82012-09-11 18:11:16 +000081 { LLDB_OPT_SET_2, true , "version" , 'v', no_argument , 0, eArgTypeNone,
Jim Ingham12e9a202011-09-15 21:30:02 +000082 "Prints out the current version number of the LLDB debugger." },
Filipe Cabecinhasd0b87d82012-09-11 18:11:16 +000083 { LLDB_OPT_SET_3, true , "arch" , 'a', required_argument, 0, eArgTypeArchitecture,
Jim Ingham12e9a202011-09-15 21:30:02 +000084 "Tells the debugger to use the specified architecture when starting and running the program. <architecture> must "
85 "be one of the architectures for which the program was compiled." },
Filipe Cabecinhasd0b87d82012-09-11 18:11:16 +000086 { LLDB_OPT_SET_3, true , "file" , 'f', required_argument, 0, eArgTypeFilename,
Jim Ingham12e9a202011-09-15 21:30:02 +000087 "Tells the debugger to use the file <filename> as the program to be debugged." },
Jason Molenda67c3cf52012-10-24 03:29:40 +000088 { LLDB_OPT_SET_3, false, "core" , 'c', required_argument, 0, eArgTypeFilename,
Johnny Cheneb46f782012-08-15 22:10:42 +000089 "Tells the debugger to use the fullpath to <path> as the core file." },
Filipe Cabecinhasd0b87d82012-09-11 18:11:16 +000090 { LLDB_OPT_SET_4, true , "attach-name" , 'n', required_argument, 0, eArgTypeProcessName,
Jim Ingham12e9a202011-09-15 21:30:02 +000091 "Tells the debugger to attach to a process with the given name." },
Filipe Cabecinhasd0b87d82012-09-11 18:11:16 +000092 { LLDB_OPT_SET_4, true , "wait-for" , 'w', no_argument , 0, eArgTypeNone,
Jim Ingham12e9a202011-09-15 21:30:02 +000093 "Tells the debugger to wait for a process with the given pid or name to launch before attaching." },
Filipe Cabecinhasd0b87d82012-09-11 18:11:16 +000094 { LLDB_OPT_SET_5, true , "attach-pid" , 'p', required_argument, 0, eArgTypePid,
Jim Ingham12e9a202011-09-15 21:30:02 +000095 "Tells the debugger to attach to a process with the given pid." },
Filipe Cabecinhasd0b87d82012-09-11 18:11:16 +000096 { LLDB_3_TO_5, false, "script-language", 'l', required_argument, 0, eArgTypeScriptLang,
Jim Ingham12e9a202011-09-15 21:30:02 +000097 "Tells the debugger to use the specified scripting language for user-defined scripts, rather than the default. "
98 "Valid scripting languages that can be specified include Python, Perl, Ruby and Tcl. Currently only the Python "
99 "extensions have been implemented." },
Filipe Cabecinhasd0b87d82012-09-11 18:11:16 +0000100 { LLDB_3_TO_5, false, "debug" , 'd', no_argument , 0, eArgTypeNone,
Jim Ingham12e9a202011-09-15 21:30:02 +0000101 "Tells the debugger to print out extra information for debugging itself." },
Filipe Cabecinhasd0b87d82012-09-11 18:11:16 +0000102 { LLDB_3_TO_5, false, "source" , 's', required_argument, 0, eArgTypeFilename,
Jim Ingham12e9a202011-09-15 21:30:02 +0000103 "Tells the debugger to read in and execute the file <file>, which should contain lldb commands." },
Filipe Cabecinhasd0b87d82012-09-11 18:11:16 +0000104 { LLDB_3_TO_5, false, "editor" , 'e', no_argument , 0, eArgTypeNone,
Jim Ingham12e9a202011-09-15 21:30:02 +0000105 "Tells the debugger to open source files using the host's \"external editor\" mechanism." },
Filipe Cabecinhasd0b87d82012-09-11 18:11:16 +0000106 { LLDB_3_TO_5, false, "no-lldbinit" , 'x', no_argument , 0, eArgTypeNone,
Jim Ingham12e9a202011-09-15 21:30:02 +0000107 "Do not automatically parse any '.lldbinit' files." },
Filipe Cabecinhasd0b87d82012-09-11 18:11:16 +0000108 { 0, false, NULL , 0 , 0 , 0, eArgTypeNone, NULL }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000109};
110
Jim Inghame64f0dc2011-09-13 23:25:31 +0000111static const uint32_t last_option_set_with_args = 2;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000112
113Driver::Driver () :
114 SBBroadcaster ("Driver"),
Jim Ingham06942692011-08-13 00:22:20 +0000115 m_debugger (SBDebugger::Create(false)),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000116 m_editline_pty (),
117 m_editline_slave_fh (NULL),
118 m_editline_reader (),
119 m_io_channel_ap (),
120 m_option_data (),
Daniel Malea926758b2012-12-17 17:40:07 +0000121 m_waiting_for_command (false),
122 m_done(false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000123{
Greg Claytonfc3f0272011-05-29 04:06:55 +0000124 // We want to be able to handle CTRL+D in the terminal to have it terminate
125 // certain input
126 m_debugger.SetCloseInputOnEOF (false);
Caroline Ticedd759852010-09-09 17:45:09 +0000127 g_debugger_name = (char *) m_debugger.GetInstanceName();
128 if (g_debugger_name == NULL)
129 g_debugger_name = (char *) "";
Caroline Ticeefed6132010-11-19 20:47:54 +0000130 g_driver = this;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000131}
132
133Driver::~Driver ()
134{
Caroline Ticeefed6132010-11-19 20:47:54 +0000135 g_driver = NULL;
136 g_debugger_name = NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000137}
138
139void
140Driver::CloseIOChannelFile ()
141{
Johnny Chene26c7212012-05-16 22:01:10 +0000142 // Write an End of File sequence to the file descriptor to ensure any
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000143 // read functions can exit.
144 char eof_str[] = "\x04";
145 ::write (m_editline_pty.GetMasterFileDescriptor(), eof_str, strlen(eof_str));
146
147 m_editline_pty.CloseMasterFileDescriptor();
148
149 if (m_editline_slave_fh)
150 {
151 ::fclose (m_editline_slave_fh);
152 m_editline_slave_fh = NULL;
153 }
154}
155
Greg Claytonc982c762010-07-09 20:39:50 +0000156// This function takes INDENT, which tells how many spaces to output at the front
157// of each line; TEXT, which is the text that is to be output. It outputs the
158// text, on multiple lines if necessary, to RESULT, with INDENT spaces at the
159// front of each line. It breaks lines on spaces, tabs or newlines, shortening
160// the line if necessary to not break in the middle of a word. It assumes that
161// each output line should contain a maximum of OUTPUT_MAX_COLUMNS characters.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000162
163void
Greg Claytonc982c762010-07-09 20:39:50 +0000164OutputFormattedUsageText (FILE *out, int indent, const char *text, int output_max_columns)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000165{
166 int len = strlen (text);
167 std::string text_string (text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000168
169 // Force indentation to be reasonable.
170 if (indent >= output_max_columns)
171 indent = 0;
172
173 // Will it all fit on one line?
174
175 if (len + indent < output_max_columns)
176 // Output as a single line
Greg Claytonc982c762010-07-09 20:39:50 +0000177 fprintf (out, "%*s%s\n", indent, "", text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000178 else
179 {
180 // We need to break it up into multiple lines.
181 int text_width = output_max_columns - indent - 1;
182 int start = 0;
183 int end = start;
184 int final_end = len;
185 int sub_len;
186
187 while (end < final_end)
188 {
189 // Dont start the 'text' on a space, since we're already outputting the indentation.
190 while ((start < final_end) && (text[start] == ' '))
191 start++;
192
193 end = start + text_width;
194 if (end > final_end)
195 end = final_end;
196 else
197 {
198 // If we're not at the end of the text, make sure we break the line on white space.
199 while (end > start
200 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
201 end--;
202 }
203 sub_len = end - start;
204 std::string substring = text_string.substr (start, sub_len);
Greg Claytonc982c762010-07-09 20:39:50 +0000205 fprintf (out, "%*s%s\n", indent, "", substring.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000206 start = end + 1;
207 }
208 }
209}
210
211void
Greg Claytone0d378b2011-03-24 21:19:54 +0000212ShowUsage (FILE *out, OptionDefinition *option_table, Driver::OptionData data)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000213{
214 uint32_t screen_width = 80;
215 uint32_t indent_level = 0;
216 const char *name = "lldb";
Jim Ingham86511212010-06-15 18:47:14 +0000217
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000218 fprintf (out, "\nUsage:\n\n");
219
220 indent_level += 2;
221
222
223 // First, show each usage level set of options, e.g. <cmd> [options-for-level-0]
224 // <cmd> [options-for-level-1]
225 // etc.
226
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000227 uint32_t num_options;
Jim Ingham86511212010-06-15 18:47:14 +0000228 uint32_t num_option_sets = 0;
229
230 for (num_options = 0; option_table[num_options].long_option != NULL; ++num_options)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000231 {
Jim Ingham86511212010-06-15 18:47:14 +0000232 uint32_t this_usage_mask = option_table[num_options].usage_mask;
233 if (this_usage_mask == LLDB_OPT_SET_ALL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000234 {
Jim Ingham86511212010-06-15 18:47:14 +0000235 if (num_option_sets == 0)
236 num_option_sets = 1;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000237 }
238 else
239 {
Greg Claytonc982c762010-07-09 20:39:50 +0000240 for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++)
Jim Ingham86511212010-06-15 18:47:14 +0000241 {
242 if (this_usage_mask & 1 << j)
243 {
244 if (num_option_sets <= j)
245 num_option_sets = j + 1;
246 }
247 }
248 }
249 }
250
251 for (uint32_t opt_set = 0; opt_set < num_option_sets; opt_set++)
252 {
253 uint32_t opt_set_mask;
254
255 opt_set_mask = 1 << opt_set;
256
257 if (opt_set > 0)
258 fprintf (out, "\n");
Greg Claytonc982c762010-07-09 20:39:50 +0000259 fprintf (out, "%*s%s", indent_level, "", name);
Jim Ingham556e6532011-08-16 23:15:02 +0000260 bool is_help_line = false;
Jim Ingham86511212010-06-15 18:47:14 +0000261
262 for (uint32_t i = 0; i < num_options; ++i)
263 {
264 if (option_table[i].usage_mask & opt_set_mask)
265 {
Caroline Ticedeaab222010-10-01 19:59:14 +0000266 CommandArgumentType arg_type = option_table[i].argument_type;
Greg Clayton9d0402b2011-02-20 02:15:07 +0000267 const char *arg_name = SBCommandInterpreter::GetArgumentTypeAsCString (arg_type);
Jim Ingham556e6532011-08-16 23:15:02 +0000268 // This is a bit of a hack, but there's no way to say certain options don't have arguments yet...
269 // so we do it by hand here.
270 if (option_table[i].short_option == 'h')
271 is_help_line = true;
272
Jim Ingham86511212010-06-15 18:47:14 +0000273 if (option_table[i].required)
274 {
275 if (option_table[i].option_has_arg == required_argument)
Greg Clayton9d0402b2011-02-20 02:15:07 +0000276 fprintf (out, " -%c <%s>", option_table[i].short_option, arg_name);
Jim Ingham86511212010-06-15 18:47:14 +0000277 else if (option_table[i].option_has_arg == optional_argument)
Greg Clayton9d0402b2011-02-20 02:15:07 +0000278 fprintf (out, " -%c [<%s>]", option_table[i].short_option, arg_name);
Jim Ingham86511212010-06-15 18:47:14 +0000279 else
280 fprintf (out, " -%c", option_table[i].short_option);
281 }
282 else
283 {
284 if (option_table[i].option_has_arg == required_argument)
Greg Clayton9d0402b2011-02-20 02:15:07 +0000285 fprintf (out, " [-%c <%s>]", option_table[i].short_option, arg_name);
Jim Ingham86511212010-06-15 18:47:14 +0000286 else if (option_table[i].option_has_arg == optional_argument)
Greg Clayton9d0402b2011-02-20 02:15:07 +0000287 fprintf (out, " [-%c [<%s>]]", option_table[i].short_option, arg_name);
Jim Ingham86511212010-06-15 18:47:14 +0000288 else
289 fprintf (out, " [-%c]", option_table[i].short_option);
290 }
291 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000292 }
Jim Inghame64f0dc2011-09-13 23:25:31 +0000293 if (!is_help_line && (opt_set <= last_option_set_with_args))
Jim Ingham556e6532011-08-16 23:15:02 +0000294 fprintf (out, " [[--] <PROGRAM-ARG-1> [<PROGRAM_ARG-2> ...]]");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000295 }
296
297 fprintf (out, "\n\n");
298
299 // Now print out all the detailed information about the various options: long form, short form and help text:
300 // -- long_name <argument>
301 // - short <argument>
302 // help text
303
304 // This variable is used to keep track of which options' info we've printed out, because some options can be in
305 // more than one usage level, but we only want to print the long form of its information once.
306
307 Driver::OptionData::OptionSet options_seen;
308 Driver::OptionData::OptionSet::iterator pos;
309
310 indent_level += 5;
311
Jim Ingham86511212010-06-15 18:47:14 +0000312 for (uint32_t i = 0; i < num_options; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000313 {
314 // Only print this option if we haven't already seen it.
315 pos = options_seen.find (option_table[i].short_option);
316 if (pos == options_seen.end())
317 {
Caroline Ticedeaab222010-10-01 19:59:14 +0000318 CommandArgumentType arg_type = option_table[i].argument_type;
Greg Clayton9d0402b2011-02-20 02:15:07 +0000319 const char *arg_name = SBCommandInterpreter::GetArgumentTypeAsCString (arg_type);
Caroline Ticedeaab222010-10-01 19:59:14 +0000320
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000321 options_seen.insert (option_table[i].short_option);
Greg Claytonc982c762010-07-09 20:39:50 +0000322 fprintf (out, "%*s-%c ", indent_level, "", option_table[i].short_option);
Caroline Ticedeaab222010-10-01 19:59:14 +0000323 if (arg_type != eArgTypeNone)
Greg Clayton9d0402b2011-02-20 02:15:07 +0000324 fprintf (out, "<%s>", arg_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000325 fprintf (out, "\n");
Greg Claytonc982c762010-07-09 20:39:50 +0000326 fprintf (out, "%*s--%s ", indent_level, "", option_table[i].long_option);
Caroline Ticedeaab222010-10-01 19:59:14 +0000327 if (arg_type != eArgTypeNone)
Greg Clayton9d0402b2011-02-20 02:15:07 +0000328 fprintf (out, "<%s>", arg_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000329 fprintf (out, "\n");
330 indent_level += 5;
Greg Claytonc982c762010-07-09 20:39:50 +0000331 OutputFormattedUsageText (out, indent_level, option_table[i].usage_text, screen_width);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000332 indent_level -= 5;
333 fprintf (out, "\n");
334 }
335 }
336
337 indent_level -= 5;
338
Jim Inghama9deaf92011-08-16 23:57:58 +0000339 fprintf (out, "\n%*s(If you don't provide -f then the first argument will be the file to be debugged"
340 "\n%*s so '%s -- <filename> [<ARG1> [<ARG2>]]' also works."
341 "\n%*s Remember to end the options with \"--\" if any of your arguments have a \"-\" in them.)\n\n",
342 indent_level, "",
343 indent_level, "",
344 name,
345 indent_level, "");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000346}
347
348void
Greg Claytone0d378b2011-03-24 21:19:54 +0000349BuildGetOptTable (OptionDefinition *expanded_option_table, std::vector<struct option> &getopt_table,
Caroline Tice4ab31c92010-10-12 21:57:09 +0000350 uint32_t num_options)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000351{
352 if (num_options == 0)
353 return;
354
355 uint32_t i;
356 uint32_t j;
357 std::bitset<256> option_seen;
358
Caroline Tice4ab31c92010-10-12 21:57:09 +0000359 getopt_table.resize (num_options + 1);
360
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000361 for (i = 0, j = 0; i < num_options; ++i)
Greg Claytonc982c762010-07-09 20:39:50 +0000362 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000363 char short_opt = expanded_option_table[i].short_option;
Greg Claytonc982c762010-07-09 20:39:50 +0000364
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000365 if (option_seen.test(short_opt) == false)
Greg Claytonc982c762010-07-09 20:39:50 +0000366 {
Caroline Tice4ab31c92010-10-12 21:57:09 +0000367 getopt_table[j].name = expanded_option_table[i].long_option;
368 getopt_table[j].has_arg = expanded_option_table[i].option_has_arg;
369 getopt_table[j].flag = NULL;
370 getopt_table[j].val = expanded_option_table[i].short_option;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000371 option_seen.set(short_opt);
372 ++j;
Greg Claytonc982c762010-07-09 20:39:50 +0000373 }
374 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000375
Caroline Tice4ab31c92010-10-12 21:57:09 +0000376 getopt_table[j].name = NULL;
377 getopt_table[j].has_arg = 0;
378 getopt_table[j].flag = NULL;
379 getopt_table[j].val = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000380
381}
382
Greg Clayton66111032010-06-23 01:19:29 +0000383Driver::OptionData::OptionData () :
Greg Clayton8d846da2010-12-08 22:23:24 +0000384 m_args(),
Greg Clayton66111032010-06-23 01:19:29 +0000385 m_script_lang (lldb::eScriptLanguageDefault),
Johnny Cheneb46f782012-08-15 22:10:42 +0000386 m_core_file (),
Greg Claytonc982c762010-07-09 20:39:50 +0000387 m_crash_log (),
Greg Clayton66111032010-06-23 01:19:29 +0000388 m_source_command_files (),
389 m_debug_mode (false),
Greg Claytonc982c762010-07-09 20:39:50 +0000390 m_print_version (false),
Greg Clayton66111032010-06-23 01:19:29 +0000391 m_print_help (false),
Jim Inghame64f0dc2011-09-13 23:25:31 +0000392 m_wait_for(false),
393 m_process_name(),
394 m_process_pid(LLDB_INVALID_PROCESS_ID),
Daniel Dunbara08823f2011-10-31 22:50:49 +0000395 m_use_external_editor(false),
Stephen Wilson71c21d12011-04-11 19:41:40 +0000396 m_seen_options()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000397{
Greg Clayton66111032010-06-23 01:19:29 +0000398}
399
400Driver::OptionData::~OptionData ()
401{
402}
403
404void
405Driver::OptionData::Clear ()
406{
Greg Clayton8d846da2010-12-08 22:23:24 +0000407 m_args.clear ();
Greg Clayton66111032010-06-23 01:19:29 +0000408 m_script_lang = lldb::eScriptLanguageDefault;
409 m_source_command_files.clear ();
410 m_debug_mode = false;
411 m_print_help = false;
412 m_print_version = false;
Jim Inghame40e4212010-08-30 19:44:40 +0000413 m_use_external_editor = false;
Jim Inghame64f0dc2011-09-13 23:25:31 +0000414 m_wait_for = false;
415 m_process_name.erase();
416 m_process_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton66111032010-06-23 01:19:29 +0000417}
418
419void
420Driver::ResetOptionValues ()
421{
422 m_option_data.Clear ();
423}
424
425const char *
426Driver::GetFilename() const
427{
Greg Clayton8d846da2010-12-08 22:23:24 +0000428 if (m_option_data.m_args.empty())
Greg Clayton66111032010-06-23 01:19:29 +0000429 return NULL;
Greg Clayton8d846da2010-12-08 22:23:24 +0000430 return m_option_data.m_args.front().c_str();
Greg Clayton66111032010-06-23 01:19:29 +0000431}
432
433const char *
434Driver::GetCrashLogFilename() const
435{
436 if (m_option_data.m_crash_log.empty())
437 return NULL;
438 return m_option_data.m_crash_log.c_str();
439}
440
441lldb::ScriptLanguage
442Driver::GetScriptLanguage() const
443{
444 return m_option_data.m_script_lang;
445}
446
447size_t
448Driver::GetNumSourceCommandFiles () const
449{
450 return m_option_data.m_source_command_files.size();
451}
452
453const char *
454Driver::GetSourceCommandFileAtIndex (uint32_t idx) const
455{
456 if (idx < m_option_data.m_source_command_files.size())
457 return m_option_data.m_source_command_files[idx].c_str();
458 return NULL;
459}
460
461bool
462Driver::GetDebugMode() const
463{
464 return m_option_data.m_debug_mode;
465}
466
467
468// Check the arguments that were passed to this program to make sure they are valid and to get their
469// argument values (if any). Return a boolean value indicating whether or not to start up the full
470// debugger (i.e. the Command Interpreter) or not. Return FALSE if the arguments were invalid OR
471// if the user only wanted help or version information.
472
473SBError
474Driver::ParseArgs (int argc, const char *argv[], FILE *out_fh, bool &exit)
475{
476 ResetOptionValues ();
477
478 SBCommandReturnObject result;
479
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000480 SBError error;
481 std::string option_string;
482 struct option *long_options = NULL;
Caroline Tice4ab31c92010-10-12 21:57:09 +0000483 std::vector<struct option> long_options_vector;
Greg Claytonc982c762010-07-09 20:39:50 +0000484 uint32_t num_options;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000485
Greg Claytonc982c762010-07-09 20:39:50 +0000486 for (num_options = 0; g_options[num_options].long_option != NULL; ++num_options)
487 /* Do Nothing. */;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000488
489 if (num_options == 0)
490 {
491 if (argc > 1)
492 error.SetErrorStringWithFormat ("invalid number of options");
493 return error;
494 }
495
Caroline Tice4ab31c92010-10-12 21:57:09 +0000496 BuildGetOptTable (g_options, long_options_vector, num_options);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000497
Caroline Tice4ab31c92010-10-12 21:57:09 +0000498 if (long_options_vector.empty())
499 long_options = NULL;
500 else
501 long_options = &long_options_vector.front();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000502
503 if (long_options == NULL)
504 {
505 error.SetErrorStringWithFormat ("invalid long options");
506 return error;
507 }
508
509 // Build the option_string argument for call to getopt_long.
510
511 for (int i = 0; long_options[i].name != NULL; ++i)
512 {
513 if (long_options[i].flag == NULL)
514 {
515 option_string.push_back ((char) long_options[i].val);
516 switch (long_options[i].has_arg)
517 {
518 default:
519 case no_argument:
520 break;
521 case required_argument:
522 option_string.push_back (':');
523 break;
524 case optional_argument:
525 option_string.append ("::");
526 break;
527 }
528 }
529 }
530
Jim Ingham06942692011-08-13 00:22:20 +0000531 // This is kind of a pain, but since we make the debugger in the Driver's constructor, we can't
532 // know at that point whether we should read in init files yet. So we don't read them in in the
533 // Driver constructor, then set the flags back to "read them in" here, and then if we see the
534 // "-n" flag, we'll turn it off again. Finally we have to read them in by hand later in the
535 // main loop.
536
537 m_debugger.SkipLLDBInitFiles (false);
538 m_debugger.SkipAppInitFiles (false);
539
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000540 // Prepare for & make calls to getopt_long.
Eli Friedmanadb35022010-06-13 19:18:49 +0000541#if __GLIBC__
542 optind = 0;
543#else
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000544 optreset = 1;
545 optind = 1;
Eli Friedmanadb35022010-06-13 19:18:49 +0000546#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000547 int val;
548 while (1)
549 {
550 int long_options_index = -1;
Greg Claytonc982c762010-07-09 20:39:50 +0000551 val = ::getopt_long (argc, const_cast<char **>(argv), option_string.c_str(), long_options, &long_options_index);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000552
553 if (val == -1)
554 break;
555 else if (val == '?')
556 {
Greg Clayton66111032010-06-23 01:19:29 +0000557 m_option_data.m_print_help = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000558 error.SetErrorStringWithFormat ("unknown or ambiguous option");
559 break;
560 }
561 else if (val == 0)
562 continue;
563 else
564 {
Greg Clayton66111032010-06-23 01:19:29 +0000565 m_option_data.m_seen_options.insert ((char) val);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000566 if (long_options_index == -1)
567 {
568 for (int i = 0;
569 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val;
570 ++i)
571 {
572 if (long_options[i].val == val)
573 {
574 long_options_index = i;
575 break;
576 }
577 }
578 }
579
580 if (long_options_index >= 0)
581 {
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000582 const int short_option = g_options[long_options_index].short_option;
Greg Clayton66111032010-06-23 01:19:29 +0000583
584 switch (short_option)
585 {
586 case 'h':
587 m_option_data.m_print_help = true;
588 break;
589
590 case 'v':
591 m_option_data.m_print_version = true;
592 break;
593
594 case 'c':
Johnny Cheneb46f782012-08-15 22:10:42 +0000595 {
596 SBFileSpec file(optarg);
597 if (file.Exists())
598 {
599 m_option_data.m_core_file = optarg;
600 }
601 else
602 error.SetErrorStringWithFormat("file specified in --core (-c) option doesn't exist: '%s'", optarg);
603 }
Greg Clayton66111032010-06-23 01:19:29 +0000604 break;
Johnny Cheneb46f782012-08-15 22:10:42 +0000605
Jim Inghame40e4212010-08-30 19:44:40 +0000606 case 'e':
607 m_option_data.m_use_external_editor = true;
608 break;
Greg Clayton6eee5aa2010-10-11 01:05:37 +0000609
Jim Inghame64f0dc2011-09-13 23:25:31 +0000610 case 'x':
Greg Clayton6eee5aa2010-10-11 01:05:37 +0000611 m_debugger.SkipLLDBInitFiles (true);
Jim Ingham06942692011-08-13 00:22:20 +0000612 m_debugger.SkipAppInitFiles (true);
Greg Clayton6eee5aa2010-10-11 01:05:37 +0000613 break;
614
Greg Clayton66111032010-06-23 01:19:29 +0000615 case 'f':
616 {
617 SBFileSpec file(optarg);
618 if (file.Exists())
Greg Clayton8d846da2010-12-08 22:23:24 +0000619 {
620 m_option_data.m_args.push_back (optarg);
621 }
Caroline Tice428a9a52010-09-10 04:48:55 +0000622 else if (file.ResolveExecutableLocation())
623 {
624 char path[PATH_MAX];
Johnny Chen25f3a3c2011-08-10 22:06:24 +0000625 file.GetPath (path, sizeof(path));
Greg Clayton8d846da2010-12-08 22:23:24 +0000626 m_option_data.m_args.push_back (path);
Caroline Tice428a9a52010-09-10 04:48:55 +0000627 }
Greg Clayton66111032010-06-23 01:19:29 +0000628 else
629 error.SetErrorStringWithFormat("file specified in --file (-f) option doesn't exist: '%s'", optarg);
630 }
631 break;
632
633 case 'a':
634 if (!m_debugger.SetDefaultArchitecture (optarg))
635 error.SetErrorStringWithFormat("invalid architecture in the -a or --arch option: '%s'", optarg);
636 break;
637
638 case 'l':
639 m_option_data.m_script_lang = m_debugger.GetScriptingLanguage (optarg);
640 break;
641
642 case 'd':
643 m_option_data.m_debug_mode = true;
644 break;
645
Jim Inghame64f0dc2011-09-13 23:25:31 +0000646 case 'n':
647 m_option_data.m_process_name = optarg;
648 break;
649
650 case 'w':
651 m_option_data.m_wait_for = true;
652 break;
653
654 case 'p':
655 {
656 char *remainder;
657 m_option_data.m_process_pid = strtol (optarg, &remainder, 0);
658 if (remainder == optarg || *remainder != '\0')
659 error.SetErrorStringWithFormat ("Could not convert process PID: \"%s\" into a pid.",
660 optarg);
661 }
662 break;
Greg Clayton66111032010-06-23 01:19:29 +0000663 case 's':
664 {
665 SBFileSpec file(optarg);
666 if (file.Exists())
667 m_option_data.m_source_command_files.push_back (optarg);
Caroline Tice428a9a52010-09-10 04:48:55 +0000668 else if (file.ResolveExecutableLocation())
669 {
670 char final_path[PATH_MAX];
Johnny Chen25f3a3c2011-08-10 22:06:24 +0000671 file.GetPath (final_path, sizeof(final_path));
Caroline Tice428a9a52010-09-10 04:48:55 +0000672 std::string path_str (final_path);
673 m_option_data.m_source_command_files.push_back (path_str);
674 }
Greg Clayton66111032010-06-23 01:19:29 +0000675 else
676 error.SetErrorStringWithFormat("file specified in --source (-s) option doesn't exist: '%s'", optarg);
677 }
678 break;
679
680 default:
681 m_option_data.m_print_help = true;
682 error.SetErrorStringWithFormat ("unrecognized option %c", short_option);
683 break;
684 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000685 }
686 else
687 {
688 error.SetErrorStringWithFormat ("invalid option with value %i", val);
689 }
690 if (error.Fail())
Caroline Tice4ab31c92010-10-12 21:57:09 +0000691 {
Greg Clayton66111032010-06-23 01:19:29 +0000692 return error;
Caroline Tice4ab31c92010-10-12 21:57:09 +0000693 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000694 }
695 }
Jim Ingham86511212010-06-15 18:47:14 +0000696
Greg Clayton66111032010-06-23 01:19:29 +0000697 if (error.Fail() || m_option_data.m_print_help)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000698 {
699 ShowUsage (out_fh, g_options, m_option_data);
Greg Claytone46dd322010-10-11 01:13:37 +0000700 exit = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000701 }
702 else if (m_option_data.m_print_version)
703 {
Greg Clayton66111032010-06-23 01:19:29 +0000704 ::fprintf (out_fh, "%s\n", m_debugger.GetVersionString());
705 exit = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000706 }
Jim Inghame64f0dc2011-09-13 23:25:31 +0000707 else if (m_option_data.m_process_name.empty() && m_option_data.m_process_pid == LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000708 {
Greg Clayton8d846da2010-12-08 22:23:24 +0000709 // Any arguments that are left over after option parsing are for
710 // the program. If a file was specified with -f then the filename
711 // is already in the m_option_data.m_args array, and any remaining args
712 // are arguments for the inferior program. If no file was specified with
713 // -f, then what is left is the program name followed by any arguments.
714
715 // Skip any options we consumed with getopt_long
716 argc -= optind;
717 argv += optind;
718
719 if (argc > 0)
720 {
721 for (int arg_idx=0; arg_idx<argc; ++arg_idx)
722 {
723 const char *arg = argv[arg_idx];
724 if (arg)
725 m_option_data.m_args.push_back (arg);
726 }
727 }
728
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000729 }
Jim Inghame64f0dc2011-09-13 23:25:31 +0000730 else
731 {
732 // Skip any options we consumed with getopt_long
733 argc -= optind;
Greg Clayton23f59502012-07-17 03:23:13 +0000734 //argv += optind; // Commented out to keep static analyzer happy
Jim Inghame64f0dc2011-09-13 23:25:31 +0000735
736 if (argc > 0)
737 ::fprintf (out_fh, "Warning: program arguments are ignored when attaching.\n");
738 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000739
Greg Clayton66111032010-06-23 01:19:29 +0000740 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000741}
742
Caroline Ticebd13b8d2010-09-29 18:35:42 +0000743size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000744Driver::GetProcessSTDOUT ()
745{
746 // The process has stuff waiting for stdout; get it and write it out to the appropriate place.
747 char stdio_buffer[1024];
748 size_t len;
Caroline Ticebd13b8d2010-09-29 18:35:42 +0000749 size_t total_bytes = 0;
Jim Ingham2976d002010-08-26 21:32:51 +0000750 while ((len = m_debugger.GetSelectedTarget().GetProcess().GetSTDOUT (stdio_buffer, sizeof (stdio_buffer))) > 0)
Caroline Ticebd13b8d2010-09-29 18:35:42 +0000751 {
Caroline Tice969ed3d2011-05-02 20:41:46 +0000752 m_io_channel_ap->OutWrite (stdio_buffer, len, ASYNC);
Caroline Ticebd13b8d2010-09-29 18:35:42 +0000753 total_bytes += len;
754 }
755 return total_bytes;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000756}
757
Caroline Ticebd13b8d2010-09-29 18:35:42 +0000758size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000759Driver::GetProcessSTDERR ()
760{
761 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
762 char stdio_buffer[1024];
763 size_t len;
Caroline Ticebd13b8d2010-09-29 18:35:42 +0000764 size_t total_bytes = 0;
Jim Ingham2976d002010-08-26 21:32:51 +0000765 while ((len = m_debugger.GetSelectedTarget().GetProcess().GetSTDERR (stdio_buffer, sizeof (stdio_buffer))) > 0)
Caroline Ticebd13b8d2010-09-29 18:35:42 +0000766 {
Caroline Tice969ed3d2011-05-02 20:41:46 +0000767 m_io_channel_ap->ErrWrite (stdio_buffer, len, ASYNC);
Caroline Ticebd13b8d2010-09-29 18:35:42 +0000768 total_bytes += len;
769 }
770 return total_bytes;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000771}
772
773void
Jim Ingham2976d002010-08-26 21:32:51 +0000774Driver::UpdateSelectedThread ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000775{
776 using namespace lldb;
Jim Ingham2976d002010-08-26 21:32:51 +0000777 SBProcess process(m_debugger.GetSelectedTarget().GetProcess());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000778 if (process.IsValid())
779 {
Jim Ingham2976d002010-08-26 21:32:51 +0000780 SBThread curr_thread (process.GetSelectedThread());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000781 SBThread thread;
782 StopReason curr_thread_stop_reason = eStopReasonInvalid;
783 curr_thread_stop_reason = curr_thread.GetStopReason();
784
785 if (!curr_thread.IsValid() ||
786 curr_thread_stop_reason == eStopReasonInvalid ||
787 curr_thread_stop_reason == eStopReasonNone)
788 {
789 // Prefer a thread that has just completed its plan over another thread as current thread.
790 SBThread plan_thread;
791 SBThread other_thread;
792 const size_t num_threads = process.GetNumThreads();
793 size_t i;
794 for (i = 0; i < num_threads; ++i)
795 {
796 thread = process.GetThreadAtIndex(i);
797 StopReason thread_stop_reason = thread.GetStopReason();
798 switch (thread_stop_reason)
799 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000800 case eStopReasonInvalid:
801 case eStopReasonNone:
802 break;
803
804 case eStopReasonTrace:
805 case eStopReasonBreakpoint:
806 case eStopReasonWatchpoint:
807 case eStopReasonSignal:
808 case eStopReasonException:
Greg Clayton90ba8112012-12-05 00:16:59 +0000809 case eStopReasonExec:
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000810 if (!other_thread.IsValid())
811 other_thread = thread;
812 break;
813 case eStopReasonPlanComplete:
814 if (!plan_thread.IsValid())
815 plan_thread = thread;
816 break;
817 }
818 }
819 if (plan_thread.IsValid())
Jim Ingham2976d002010-08-26 21:32:51 +0000820 process.SetSelectedThread (plan_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000821 else if (other_thread.IsValid())
Jim Ingham2976d002010-08-26 21:32:51 +0000822 process.SetSelectedThread (other_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000823 else
824 {
825 if (curr_thread.IsValid())
826 thread = curr_thread;
827 else
828 thread = process.GetThreadAtIndex(0);
829
830 if (thread.IsValid())
Jim Ingham2976d002010-08-26 21:32:51 +0000831 process.SetSelectedThread (thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000832 }
833 }
834 }
835}
836
Jim Inghame6bc6cb2012-02-08 05:23:15 +0000837// This function handles events that were broadcast by the process.
838void
839Driver::HandleBreakpointEvent (const SBEvent &event)
840{
841 using namespace lldb;
842 const uint32_t event_type = SBBreakpoint::GetBreakpointEventTypeFromEvent (event);
843
844 if (event_type & eBreakpointEventTypeAdded
845 || event_type & eBreakpointEventTypeRemoved
846 || event_type & eBreakpointEventTypeEnabled
847 || event_type & eBreakpointEventTypeDisabled
848 || event_type & eBreakpointEventTypeCommandChanged
849 || event_type & eBreakpointEventTypeConditionChanged
850 || event_type & eBreakpointEventTypeIgnoreChanged
851 || event_type & eBreakpointEventTypeLocationsResolved)
852 {
853 // Don't do anything about these events, since the breakpoint commands already echo these actions.
854 }
855 else if (event_type & eBreakpointEventTypeLocationsAdded)
856 {
857 char message[256];
858 uint32_t num_new_locations = SBBreakpoint::GetNumBreakpointLocationsFromEvent(event);
859 if (num_new_locations > 0)
860 {
861 SBBreakpoint breakpoint = SBBreakpoint::GetBreakpointFromEvent(event);
Jim Inghamfab10e82012-03-06 00:37:27 +0000862 int message_len = ::snprintf (message, sizeof(message), "%d location%s added to breakpoint %d\n",
Jim Inghame6bc6cb2012-02-08 05:23:15 +0000863 num_new_locations,
Jason Molenda65c28cb2012-09-28 01:50:47 +0000864 num_new_locations == 1 ? "" : "s",
Jim Inghame6bc6cb2012-02-08 05:23:15 +0000865 breakpoint.GetID());
866 m_io_channel_ap->OutWrite(message, message_len, ASYNC);
867 }
868 }
869 else if (event_type & eBreakpointEventTypeLocationsRemoved)
870 {
871 // These locations just get disabled, not sure it is worth spamming folks about this on the command line.
872 }
873 else if (event_type & eBreakpointEventTypeLocationsResolved)
874 {
875 // This might be an interesting thing to note, but I'm going to leave it quiet for now, it just looked noisy.
876 }
877}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000878
879// This function handles events that were broadcast by the process.
880void
881Driver::HandleProcessEvent (const SBEvent &event)
882{
883 using namespace lldb;
884 const uint32_t event_type = event.GetType();
885
886 if (event_type & SBProcess::eBroadcastBitSTDOUT)
887 {
888 // The process has stdout available, get it and write it out to the
889 // appropriate place.
Caroline Tice969ed3d2011-05-02 20:41:46 +0000890 GetProcessSTDOUT ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000891 }
892 else if (event_type & SBProcess::eBroadcastBitSTDERR)
893 {
894 // The process has stderr available, get it and write it out to the
895 // appropriate place.
Caroline Tice969ed3d2011-05-02 20:41:46 +0000896 GetProcessSTDERR ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000897 }
898 else if (event_type & SBProcess::eBroadcastBitStateChanged)
899 {
900 // Drain all stout and stderr so we don't see any output come after
901 // we print our prompts
Caroline Tice969ed3d2011-05-02 20:41:46 +0000902 GetProcessSTDOUT ();
903 GetProcessSTDERR ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000904 // Something changed in the process; get the event and report the process's current status and location to
905 // the user.
906 StateType event_state = SBProcess::GetStateFromEvent (event);
907 if (event_state == eStateInvalid)
908 return;
909
910 SBProcess process (SBProcess::GetProcessFromEvent (event));
911 assert (process.IsValid());
912
913 switch (event_state)
914 {
915 case eStateInvalid:
916 case eStateUnloaded:
Greg Claytonb766a732011-02-04 01:58:07 +0000917 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000918 case eStateAttaching:
919 case eStateLaunching:
920 case eStateStepping:
921 case eStateDetached:
922 {
923 char message[1024];
Daniel Malead01b2952012-11-29 21:49:15 +0000924 int message_len = ::snprintf (message, sizeof(message), "Process %" PRIu64 " %s\n", process.GetProcessID(),
Greg Clayton66111032010-06-23 01:19:29 +0000925 m_debugger.StateAsCString (event_state));
Caroline Tice969ed3d2011-05-02 20:41:46 +0000926 m_io_channel_ap->OutWrite(message, message_len, ASYNC);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000927 }
928 break;
929
930 case eStateRunning:
931 // Don't be chatty when we run...
932 break;
933
934 case eStateExited:
Caroline Ticebd13b8d2010-09-29 18:35:42 +0000935 {
936 SBCommandReturnObject result;
937 m_debugger.GetCommandInterpreter().HandleCommand("process status", result, false);
Caroline Tice969ed3d2011-05-02 20:41:46 +0000938 m_io_channel_ap->ErrWrite (result.GetError(), result.GetErrorSize(), ASYNC);
939 m_io_channel_ap->OutWrite (result.GetOutput(), result.GetOutputSize(), ASYNC);
Caroline Ticebd13b8d2010-09-29 18:35:42 +0000940 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000941 break;
942
943 case eStateStopped:
944 case eStateCrashed:
945 case eStateSuspended:
946 // Make sure the program hasn't been auto-restarted:
947 if (SBProcess::GetRestartedFromEvent (event))
948 {
949 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
950 char message[1024];
Daniel Malead01b2952012-11-29 21:49:15 +0000951 int message_len = ::snprintf (message, sizeof(message), "Process %" PRIu64 " stopped and was programmatically restarted.\n",
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000952 process.GetProcessID());
Caroline Tice969ed3d2011-05-02 20:41:46 +0000953 m_io_channel_ap->OutWrite(message, message_len, ASYNC);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000954 }
955 else
956 {
Jim Ingham8499e1a2012-05-08 23:06:07 +0000957 if (GetDebugger().GetSelectedTarget() == process.GetTarget())
958 {
959 SBCommandReturnObject result;
960 UpdateSelectedThread ();
961 m_debugger.GetCommandInterpreter().HandleCommand("process status", result, false);
962 m_io_channel_ap->ErrWrite (result.GetError(), result.GetErrorSize(), ASYNC);
963 m_io_channel_ap->OutWrite (result.GetOutput(), result.GetOutputSize(), ASYNC);
964 }
965 else
966 {
967 SBStream out_stream;
968 uint32_t target_idx = GetDebugger().GetIndexOfTarget(process.GetTarget());
969 if (target_idx != UINT32_MAX)
970 out_stream.Printf ("Target %d: (", target_idx);
971 else
972 out_stream.Printf ("Target <unknown index>: (");
973 process.GetTarget().GetDescription (out_stream, eDescriptionLevelBrief);
974 out_stream.Printf (") stopped.\n");
975 m_io_channel_ap->OutWrite (out_stream.GetData(), out_stream.GetSize(), ASYNC);
976 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000977 }
978 break;
979 }
980 }
981}
982
Jim Ingham4f465cf2012-10-10 18:32:14 +0000983void
984Driver::HandleThreadEvent (const SBEvent &event)
985{
986 // At present the only thread event we handle is the Frame Changed event, and all we do for that is just
987 // reprint the thread status for that thread.
988 using namespace lldb;
989 const uint32_t event_type = event.GetType();
Jim Inghamc3faa192012-12-11 02:31:48 +0000990 if (event_type == SBThread::eBroadcastBitStackChanged
991 || event_type == SBThread::eBroadcastBitThreadSelected)
Jim Ingham4f465cf2012-10-10 18:32:14 +0000992 {
993 SBThread thread = SBThread::GetThreadFromEvent (event);
994 if (thread.IsValid())
995 {
996 SBStream out_stream;
997 thread.GetStatus(out_stream);
998 m_io_channel_ap->OutWrite (out_stream.GetData (), out_stream.GetSize (), ASYNC);
999 }
1000 }
1001}
1002
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001003// This function handles events broadcast by the IOChannel (HasInput, UserInterrupt, or ThreadShouldExit).
1004
1005bool
1006Driver::HandleIOEvent (const SBEvent &event)
1007{
1008 bool quit = false;
1009
1010 const uint32_t event_type = event.GetType();
1011
1012 if (event_type & IOChannel::eBroadcastBitHasUserInput)
1013 {
1014 // We got some input (i.e. a command string) from the user; pass it off to the command interpreter for
1015 // handling.
1016
1017 const char *command_string = SBEvent::GetCStringFromEvent(event);
1018 if (command_string == NULL)
Greg Claytonc982c762010-07-09 20:39:50 +00001019 command_string = "";
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001020 SBCommandReturnObject result;
Jim Ingham85e8b812011-02-19 02:53:09 +00001021
Caroline Ticeb5059ac2011-05-16 19:20:50 +00001022 // We don't want the result to bypass the OutWrite function in IOChannel, as this can result in odd
1023 // output orderings and problems with the prompt.
Jim Ingham85e8b812011-02-19 02:53:09 +00001024 m_debugger.GetCommandInterpreter().HandleCommand (command_string, result, true);
1025
Enrico Granatacd4d24d2012-10-16 20:57:12 +00001026 const bool only_if_no_immediate = true;
1027
Enrico Granata430e5402012-10-16 21:11:14 +00001028 const size_t output_size = result.GetOutputSize();
Enrico Granatacd4d24d2012-10-16 20:57:12 +00001029
1030 if (output_size > 0)
1031 m_io_channel_ap->OutWrite (result.GetOutput(only_if_no_immediate), output_size, NO_ASYNC);
1032
Enrico Granata430e5402012-10-16 21:11:14 +00001033 const size_t error_size = result.GetErrorSize();
Enrico Granatacd4d24d2012-10-16 20:57:12 +00001034
1035 if (error_size > 0)
1036 m_io_channel_ap->OutWrite (result.GetError(only_if_no_immediate), error_size, NO_ASYNC);
Caroline Ticeb5059ac2011-05-16 19:20:50 +00001037
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001038 // We are done getting and running our command, we can now clear the
1039 // m_waiting_for_command so we can get another one.
1040 m_waiting_for_command = false;
1041
1042 // If our editline input reader is active, it means another input reader
1043 // got pushed onto the input reader and caused us to become deactivated.
1044 // When the input reader above us gets popped, we will get re-activated
1045 // and our prompt will refresh in our callback
1046 if (m_editline_reader.IsActive())
1047 {
1048 ReadyForCommand ();
1049 }
1050 }
1051 else if (event_type & IOChannel::eBroadcastBitUserInterrupt)
1052 {
1053 // This is here to handle control-c interrupts from the user. It has not yet really been implemented.
1054 // TO BE DONE: PROPERLY HANDLE CONTROL-C FROM USER
1055 //m_io_channel_ap->CancelInput();
1056 // Anything else? Send Interrupt to process?
1057 }
1058 else if ((event_type & IOChannel::eBroadcastBitThreadShouldExit) ||
1059 (event_type & IOChannel::eBroadcastBitThreadDidExit))
1060 {
1061 // If the IOChannel thread is trying to go away, then it is definitely
1062 // time to end the debugging session.
1063 quit = true;
1064 }
1065
1066 return quit;
1067}
1068
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001069void
1070Driver::MasterThreadBytesReceived (void *baton, const void *src, size_t src_len)
1071{
1072 Driver *driver = (Driver*)baton;
1073 driver->GetFromMaster ((const char *)src, src_len);
1074}
1075
1076void
1077Driver::GetFromMaster (const char *src, size_t src_len)
1078{
1079 // Echo the characters back to the Debugger's stdout, that way if you
1080 // type characters while a command is running, you'll see what you've typed.
Greg Clayton66111032010-06-23 01:19:29 +00001081 FILE *out_fh = m_debugger.GetOutputFileHandle();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001082 if (out_fh)
1083 ::fwrite (src, 1, src_len, out_fh);
1084}
1085
1086size_t
1087Driver::EditLineInputReaderCallback
1088(
1089 void *baton,
1090 SBInputReader *reader,
1091 InputReaderAction notification,
1092 const char *bytes,
1093 size_t bytes_len
1094)
1095{
1096 Driver *driver = (Driver *)baton;
1097
1098 switch (notification)
1099 {
1100 case eInputReaderActivate:
1101 break;
1102
1103 case eInputReaderReactivate:
1104 driver->ReadyForCommand();
1105 break;
1106
1107 case eInputReaderDeactivate:
1108 break;
Caroline Tice969ed3d2011-05-02 20:41:46 +00001109
1110 case eInputReaderAsynchronousOutputWritten:
1111 if (driver->m_io_channel_ap.get() != NULL)
1112 driver->m_io_channel_ap->RefreshPrompt();
1113 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001114
Caroline Ticeefed6132010-11-19 20:47:54 +00001115 case eInputReaderInterrupt:
1116 if (driver->m_io_channel_ap.get() != NULL)
1117 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001118 SBProcess process(driver->GetDebugger().GetSelectedTarget().GetProcess());
Jim Inghamd242f1c2012-06-01 01:07:02 +00001119 if (!driver->m_io_channel_ap->EditLineHasCharacters()
Jim Inghamcfc09352012-07-27 23:57:19 +00001120 && process.IsValid()
1121 && (process.GetState() == lldb::eStateRunning || process.GetState() == lldb::eStateAttaching))
Jim Inghamd242f1c2012-06-01 01:07:02 +00001122 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001123 process.SendAsyncInterrupt ();
Jim Inghamd242f1c2012-06-01 01:07:02 +00001124 }
1125 else
1126 {
1127 driver->m_io_channel_ap->OutWrite ("^C\n", 3, NO_ASYNC);
1128 // I wish I could erase the entire input line, but there's no public API for that.
1129 driver->m_io_channel_ap->EraseCharsBeforeCursor();
1130 driver->m_io_channel_ap->RefreshPrompt();
1131 }
Caroline Ticeefed6132010-11-19 20:47:54 +00001132 }
1133 break;
1134
1135 case eInputReaderEndOfFile:
1136 if (driver->m_io_channel_ap.get() != NULL)
1137 {
Caroline Tice969ed3d2011-05-02 20:41:46 +00001138 driver->m_io_channel_ap->OutWrite ("^D\n", 3, NO_ASYNC);
Caroline Ticeefed6132010-11-19 20:47:54 +00001139 driver->m_io_channel_ap->RefreshPrompt ();
1140 }
1141 write (driver->m_editline_pty.GetMasterFileDescriptor(), "quit\n", 5);
1142 break;
1143
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001144 case eInputReaderGotToken:
1145 write (driver->m_editline_pty.GetMasterFileDescriptor(), bytes, bytes_len);
1146 break;
1147
1148 case eInputReaderDone:
1149 break;
1150 }
1151 return bytes_len;
1152}
1153
1154void
1155Driver::MainLoop ()
1156{
1157 char error_str[1024];
1158 if (m_editline_pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, error_str, sizeof(error_str)) == false)
1159 {
1160 ::fprintf (stderr, "error: failed to open driver pseudo terminal : %s", error_str);
1161 exit(1);
1162 }
1163 else
1164 {
1165 const char *driver_slave_name = m_editline_pty.GetSlaveName (error_str, sizeof(error_str));
1166 if (driver_slave_name == NULL)
1167 {
1168 ::fprintf (stderr, "error: failed to get slave name for driver pseudo terminal : %s", error_str);
1169 exit(2);
1170 }
1171 else
1172 {
1173 m_editline_slave_fh = ::fopen (driver_slave_name, "r+");
1174 if (m_editline_slave_fh == NULL)
1175 {
1176 SBError error;
1177 error.SetErrorToErrno();
1178 ::fprintf (stderr, "error: failed to get open slave for driver pseudo terminal : %s",
1179 error.GetCString());
1180 exit(3);
1181 }
1182
1183 ::setbuf (m_editline_slave_fh, NULL);
1184 }
1185 }
1186
Caroline Tice969ed3d2011-05-02 20:41:46 +00001187 lldb_utility::PseudoTerminal editline_output_pty;
1188 FILE *editline_output_slave_fh = NULL;
1189
1190 if (editline_output_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str, sizeof (error_str)) == false)
1191 {
1192 ::fprintf (stderr, "error: failed to open output pseudo terminal : %s", error_str);
1193 exit(1);
1194 }
1195 else
1196 {
1197 const char *output_slave_name = editline_output_pty.GetSlaveName (error_str, sizeof(error_str));
1198 if (output_slave_name == NULL)
1199 {
1200 ::fprintf (stderr, "error: failed to get slave name for output pseudo terminal : %s", error_str);
1201 exit(2);
1202 }
1203 else
1204 {
1205 editline_output_slave_fh = ::fopen (output_slave_name, "r+");
1206 if (editline_output_slave_fh == NULL)
1207 {
1208 SBError error;
1209 error.SetErrorToErrno();
1210 ::fprintf (stderr, "error: failed to get open slave for output pseudo terminal : %s",
1211 error.GetCString());
1212 exit(3);
1213 }
1214 ::setbuf (editline_output_slave_fh, NULL);
1215 }
1216 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001217
1218 // struct termios stdin_termios;
1219
1220 if (::tcgetattr(STDIN_FILENO, &g_old_stdin_termios) == 0)
Greg Claytonf571b892012-02-02 19:28:31 +00001221 {
1222 g_old_stdin_termios_is_valid = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001223 atexit (reset_stdin_termios);
Greg Claytonf571b892012-02-02 19:28:31 +00001224 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001225
1226 ::setbuf (stdin, NULL);
1227 ::setbuf (stdout, NULL);
1228
Greg Clayton66111032010-06-23 01:19:29 +00001229 m_debugger.SetErrorFileHandle (stderr, false);
1230 m_debugger.SetOutputFileHandle (stdout, false);
1231 m_debugger.SetInputFileHandle (stdin, true);
Jim Inghame40e4212010-08-30 19:44:40 +00001232
1233 m_debugger.SetUseExternalEditor(m_option_data.m_use_external_editor);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001234
1235 // You have to drain anything that comes to the master side of the PTY. master_out_comm is
1236 // for that purpose. The reason you need to do this is a curious reason... editline will echo
1237 // characters to the PTY when it gets characters while el_gets is not running, and then when
1238 // you call el_gets (or el_getc) it will try to reset the terminal back to raw mode which blocks
1239 // if there are unconsumed characters in the out buffer.
1240 // However, you don't need to do anything with the characters, since editline will dump these
1241 // unconsumed characters after printing the prompt again in el_gets.
1242
Greg Claytond46c87a2010-12-04 02:39:47 +00001243 SBCommunication master_out_comm("driver.editline");
1244 master_out_comm.SetCloseOnEOF (false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001245 master_out_comm.AdoptFileDesriptor(m_editline_pty.GetMasterFileDescriptor(), false);
1246 master_out_comm.SetReadThreadBytesReceivedCallback(Driver::MasterThreadBytesReceived, this);
1247
1248 if (master_out_comm.ReadThreadStart () == false)
1249 {
1250 ::fprintf (stderr, "error: failed to start master out read thread");
1251 exit(5);
1252 }
1253
Greg Clayton66111032010-06-23 01:19:29 +00001254 SBCommandInterpreter sb_interpreter = m_debugger.GetCommandInterpreter();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001255
Caroline Tice969ed3d2011-05-02 20:41:46 +00001256 m_io_channel_ap.reset (new IOChannel(m_editline_slave_fh, editline_output_slave_fh, stdout, stderr, this));
1257
1258 SBCommunication out_comm_2("driver.editline_output");
1259 out_comm_2.SetCloseOnEOF (false);
1260 out_comm_2.AdoptFileDesriptor (editline_output_pty.GetMasterFileDescriptor(), false);
1261 out_comm_2.SetReadThreadBytesReceivedCallback (IOChannel::LibeditOutputBytesReceived, m_io_channel_ap.get());
1262
1263 if (out_comm_2.ReadThreadStart () == false)
1264 {
1265 ::fprintf (stderr, "error: failed to start libedit output read thread");
1266 exit (5);
1267 }
1268
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001269
1270 struct winsize window_size;
1271 if (isatty (STDIN_FILENO)
1272 && ::ioctl (STDIN_FILENO, TIOCGWINSZ, &window_size) == 0)
1273 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001274 if (window_size.ws_col > 0)
Greg Claytona7015092010-09-18 01:14:36 +00001275 m_debugger.SetTerminalWidth (window_size.ws_col);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001276 }
1277
1278 // Since input can be redirected by the debugger, we must insert our editline
1279 // input reader in the queue so we know when our reader should be active
1280 // and so we can receive bytes only when we are supposed to.
Greg Clayton66111032010-06-23 01:19:29 +00001281 SBError err (m_editline_reader.Initialize (m_debugger,
1282 Driver::EditLineInputReaderCallback, // callback
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001283 this, // baton
1284 eInputReaderGranularityByte, // token_size
1285 NULL, // end token - NULL means never done
1286 NULL, // prompt - taken care of elsewhere
1287 false)); // echo input - don't need Debugger
1288 // to do this, we handle it elsewhere
1289
1290 if (err.Fail())
1291 {
1292 ::fprintf (stderr, "error: %s", err.GetCString());
1293 exit (6);
1294 }
1295
Greg Clayton66111032010-06-23 01:19:29 +00001296 m_debugger.PushInputReader (m_editline_reader);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001297
Greg Clayton66111032010-06-23 01:19:29 +00001298 SBListener listener(m_debugger.GetListener());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001299 if (listener.IsValid())
1300 {
1301
Jim Ingham4f465cf2012-10-10 18:32:14 +00001302 listener.StartListeningForEventClass(m_debugger,
1303 SBTarget::GetBroadcasterClassName(),
1304 SBTarget::eBroadcastBitBreakpointChanged);
1305 listener.StartListeningForEventClass(m_debugger,
1306 SBThread::GetBroadcasterClassName(),
Jim Inghamc3faa192012-12-11 02:31:48 +00001307 SBThread::eBroadcastBitStackChanged |
1308 SBThread::eBroadcastBitThreadSelected);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001309 listener.StartListeningForEvents (*m_io_channel_ap,
1310 IOChannel::eBroadcastBitHasUserInput |
1311 IOChannel::eBroadcastBitUserInterrupt |
1312 IOChannel::eBroadcastBitThreadShouldExit |
1313 IOChannel::eBroadcastBitThreadDidStart |
1314 IOChannel::eBroadcastBitThreadDidExit);
1315
1316 if (m_io_channel_ap->Start ())
1317 {
1318 bool iochannel_thread_exited = false;
1319
1320 listener.StartListeningForEvents (sb_interpreter.GetBroadcaster(),
Caroline Tice86a73f92011-05-03 20:53:11 +00001321 SBCommandInterpreter::eBroadcastBitQuitCommandReceived |
1322 SBCommandInterpreter::eBroadcastBitAsynchronousOutputData |
1323 SBCommandInterpreter::eBroadcastBitAsynchronousErrorData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001324
1325 // Before we handle any options from the command line, we parse the
1326 // .lldbinit file in the user's home directory.
1327 SBCommandReturnObject result;
1328 sb_interpreter.SourceInitFileInHomeDirectory(result);
1329 if (GetDebugMode())
1330 {
Greg Clayton66111032010-06-23 01:19:29 +00001331 result.PutError (m_debugger.GetErrorFileHandle());
1332 result.PutOutput (m_debugger.GetOutputFileHandle());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001333 }
1334
1335 // Now we handle options we got from the command line
1336 char command_string[PATH_MAX * 2];
1337 const size_t num_source_command_files = GetNumSourceCommandFiles();
Enrico Granataaa0c8ff2012-12-13 20:20:11 +00001338 const bool dump_stream_only_if_no_immediate = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001339 if (num_source_command_files > 0)
1340 {
1341 for (size_t i=0; i < num_source_command_files; ++i)
1342 {
1343 const char *command_file = GetSourceCommandFileAtIndex(i);
Johnny Chen85ffddc2010-07-28 21:16:11 +00001344 ::snprintf (command_string, sizeof(command_string), "command source '%s'", command_file);
Greg Clayton66111032010-06-23 01:19:29 +00001345 m_debugger.GetCommandInterpreter().HandleCommand (command_string, result, false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001346 if (GetDebugMode())
1347 {
Greg Clayton66111032010-06-23 01:19:29 +00001348 result.PutError (m_debugger.GetErrorFileHandle());
1349 result.PutOutput (m_debugger.GetOutputFileHandle());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001350 }
Enrico Granataaa0c8ff2012-12-13 20:20:11 +00001351
1352 // if the command sourcing generated an error - dump the result object
Enrico Granatadc3f4f92012-12-14 00:52:54 +00001353 if (result.Succeeded() == false)
Enrico Granataaa0c8ff2012-12-13 20:20:11 +00001354 {
1355 const size_t output_size = result.GetOutputSize();
1356 if (output_size > 0)
1357 m_io_channel_ap->OutWrite (result.GetOutput(dump_stream_only_if_no_immediate), output_size, NO_ASYNC);
Enrico Granatadc3f4f92012-12-14 00:52:54 +00001358 const size_t error_size = result.GetErrorSize();
1359 if (error_size > 0)
1360 m_io_channel_ap->OutWrite (result.GetError(dump_stream_only_if_no_immediate), error_size, NO_ASYNC);
Enrico Granataaa0c8ff2012-12-13 20:20:11 +00001361 }
1362
1363 result.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001364 }
1365 }
1366
Johnny Cheneb46f782012-08-15 22:10:42 +00001367 // Was there a core file specified?
1368 std::string core_file_spec("");
1369 if (!m_option_data.m_core_file.empty())
1370 core_file_spec.append("--core ").append(m_option_data.m_core_file);
1371
Greg Clayton8d846da2010-12-08 22:23:24 +00001372 const size_t num_args = m_option_data.m_args.size();
1373 if (num_args > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374 {
1375 char arch_name[64];
Greg Clayton66111032010-06-23 01:19:29 +00001376 if (m_debugger.GetDefaultArchitecture (arch_name, sizeof (arch_name)))
Greg Clayton8d846da2010-12-08 22:23:24 +00001377 ::snprintf (command_string,
1378 sizeof (command_string),
Johnny Cheneb46f782012-08-15 22:10:42 +00001379 "target create --arch=%s %s \"%s\"",
Greg Clayton8d846da2010-12-08 22:23:24 +00001380 arch_name,
Johnny Cheneb46f782012-08-15 22:10:42 +00001381 core_file_spec.c_str(),
Greg Clayton8d846da2010-12-08 22:23:24 +00001382 m_option_data.m_args[0].c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001383 else
Greg Clayton8d846da2010-12-08 22:23:24 +00001384 ::snprintf (command_string,
1385 sizeof(command_string),
Johnny Cheneb46f782012-08-15 22:10:42 +00001386 "target create %s \"%s\"",
1387 core_file_spec.c_str(),
Greg Clayton8d846da2010-12-08 22:23:24 +00001388 m_option_data.m_args[0].c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001389
Greg Clayton66111032010-06-23 01:19:29 +00001390 m_debugger.HandleCommand (command_string);
Greg Clayton8d846da2010-12-08 22:23:24 +00001391
1392 if (num_args > 1)
1393 {
Greg Clayton1d885962011-11-08 02:43:13 +00001394 m_debugger.HandleCommand ("settings clear target.run-args");
Greg Clayton8d846da2010-12-08 22:23:24 +00001395 char arg_cstr[1024];
1396 for (size_t arg_idx = 1; arg_idx < num_args; ++arg_idx)
1397 {
Jim Inghame64f0dc2011-09-13 23:25:31 +00001398 ::snprintf (arg_cstr,
1399 sizeof(arg_cstr),
Greg Clayton1d885962011-11-08 02:43:13 +00001400 "settings append target.run-args \"%s\"",
Jim Inghame64f0dc2011-09-13 23:25:31 +00001401 m_option_data.m_args[arg_idx].c_str());
Greg Clayton8d846da2010-12-08 22:23:24 +00001402 m_debugger.HandleCommand (arg_cstr);
1403 }
1404 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001405 }
Johnny Cheneb46f782012-08-15 22:10:42 +00001406 else if (!core_file_spec.empty())
1407 {
1408 ::snprintf (command_string,
1409 sizeof(command_string),
1410 "target create %s",
1411 core_file_spec.c_str());
1412 m_debugger.HandleCommand (command_string);;
1413 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001414
1415 // Now that all option parsing is done, we try and parse the .lldbinit
1416 // file in the current working directory
1417 sb_interpreter.SourceInitFileInCurrentWorkingDirectory (result);
1418 if (GetDebugMode())
1419 {
Greg Clayton66111032010-06-23 01:19:29 +00001420 result.PutError(m_debugger.GetErrorFileHandle());
1421 result.PutOutput(m_debugger.GetOutputFileHandle());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001422 }
1423
1424 SBEvent event;
1425
1426 // Make sure the IO channel is started up before we try to tell it we
1427 // are ready for input
1428 listener.WaitForEventForBroadcasterWithType (UINT32_MAX,
1429 *m_io_channel_ap,
1430 IOChannel::eBroadcastBitThreadDidStart,
1431 event);
Jim Inghame64f0dc2011-09-13 23:25:31 +00001432 // If we were asked to attach, then do that here:
1433 // I'm going to use the command string rather than directly
1434 // calling the API's because then I don't have to recode the
1435 // event handling here.
1436 if (!m_option_data.m_process_name.empty()
1437 || m_option_data.m_process_pid != LLDB_INVALID_PROCESS_ID)
1438 {
1439 std::string command_str("process attach ");
1440 if (m_option_data.m_process_pid != LLDB_INVALID_PROCESS_ID)
1441 {
1442 command_str.append("-p ");
1443 char pid_buffer[32];
Daniel Malead01b2952012-11-29 21:49:15 +00001444 ::snprintf (pid_buffer, sizeof(pid_buffer), "%" PRIu64, m_option_data.m_process_pid);
Jim Inghame64f0dc2011-09-13 23:25:31 +00001445 command_str.append(pid_buffer);
1446 }
1447 else
1448 {
1449 command_str.append("-n \"");
1450 command_str.append(m_option_data.m_process_name);
1451 command_str.push_back('\"');
1452 if (m_option_data.m_wait_for)
1453 command_str.append(" -w");
1454 }
1455
1456 if (m_debugger.GetOutputFileHandle())
1457 ::fprintf (m_debugger.GetOutputFileHandle(),
1458 "Attaching to process with:\n %s\n",
1459 command_str.c_str());
1460
1461 // Force the attach to be synchronous:
1462 bool orig_async = m_debugger.GetAsync();
1463 m_debugger.SetAsync(true);
1464 m_debugger.HandleCommand(command_str.c_str());
1465 m_debugger.SetAsync(orig_async);
1466 }
1467
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001468 ReadyForCommand ();
1469
Greg Claytona9f7b792012-02-29 04:21:24 +00001470 while (!GetIsDone())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001471 {
1472 listener.WaitForEvent (UINT32_MAX, event);
1473 if (event.IsValid())
1474 {
1475 if (event.GetBroadcaster().IsValid())
1476 {
1477 uint32_t event_type = event.GetType();
1478 if (event.BroadcasterMatchesRef (*m_io_channel_ap))
1479 {
1480 if ((event_type & IOChannel::eBroadcastBitThreadShouldExit) ||
1481 (event_type & IOChannel::eBroadcastBitThreadDidExit))
1482 {
Greg Claytona9f7b792012-02-29 04:21:24 +00001483 SetIsDone();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001484 if (event_type & IOChannel::eBroadcastBitThreadDidExit)
1485 iochannel_thread_exited = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001486 }
1487 else
Greg Claytona9f7b792012-02-29 04:21:24 +00001488 {
1489 if (HandleIOEvent (event))
1490 SetIsDone();
1491 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001492 }
Jim Inghame6bc6cb2012-02-08 05:23:15 +00001493 else if (SBProcess::EventIsProcessEvent (event))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001494 {
1495 HandleProcessEvent (event);
1496 }
Jim Inghame6bc6cb2012-02-08 05:23:15 +00001497 else if (SBBreakpoint::EventIsBreakpointEvent (event))
1498 {
1499 HandleBreakpointEvent (event);
1500 }
Jim Ingham4f465cf2012-10-10 18:32:14 +00001501 else if (SBThread::EventIsThreadEvent (event))
1502 {
1503 HandleThreadEvent (event);
1504 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001505 else if (event.BroadcasterMatchesRef (sb_interpreter.GetBroadcaster()))
1506 {
Greg Claytona9f7b792012-02-29 04:21:24 +00001507 // TODO: deprecate the eBroadcastBitQuitCommandReceived event
1508 // now that we have SBCommandInterpreter::SetCommandOverrideCallback()
1509 // that can take over a command
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001510 if (event_type & SBCommandInterpreter::eBroadcastBitQuitCommandReceived)
Greg Clayton74d41932012-01-31 04:56:17 +00001511 {
Greg Claytona9f7b792012-02-29 04:21:24 +00001512 SetIsDone();
Greg Clayton74d41932012-01-31 04:56:17 +00001513 }
Caroline Tice86a73f92011-05-03 20:53:11 +00001514 else if (event_type & SBCommandInterpreter::eBroadcastBitAsynchronousErrorData)
1515 {
1516 const char *data = SBEvent::GetCStringFromEvent (event);
1517 m_io_channel_ap->ErrWrite (data, strlen(data), ASYNC);
1518 }
1519 else if (event_type & SBCommandInterpreter::eBroadcastBitAsynchronousOutputData)
1520 {
1521 const char *data = SBEvent::GetCStringFromEvent (event);
1522 m_io_channel_ap->OutWrite (data, strlen(data), ASYNC);
1523 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001524 }
1525 }
1526 }
1527 }
1528
Greg Claytonf571b892012-02-02 19:28:31 +00001529 editline_output_pty.CloseMasterFileDescriptor();
1530 master_out_comm.Disconnect();
1531 out_comm_2.Disconnect();
1532 reset_stdin_termios();
1533 fclose (stdin);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001534
1535 CloseIOChannelFile ();
1536
1537 if (!iochannel_thread_exited)
1538 {
Greg Claytonb1320972010-07-14 00:18:15 +00001539 event.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001540 listener.GetNextEventForBroadcasterWithType (*m_io_channel_ap,
1541 IOChannel::eBroadcastBitThreadDidExit,
1542 event);
1543 if (!event.IsValid())
1544 {
1545 // Send end EOF to the driver file descriptor
1546 m_io_channel_ap->Stop();
1547 }
1548 }
1549
Jim Ingham12e9a202011-09-15 21:30:02 +00001550 SBDebugger::Destroy (m_debugger);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001551 }
1552 }
1553}
1554
1555
1556void
1557Driver::ReadyForCommand ()
1558{
1559 if (m_waiting_for_command == false)
1560 {
1561 m_waiting_for_command = true;
1562 BroadcastEventByType (Driver::eBroadcastBitReadyForInput, true);
1563 }
1564}
1565
1566
Caroline Ticedd759852010-09-09 17:45:09 +00001567void
1568sigwinch_handler (int signo)
1569{
1570 struct winsize window_size;
1571 if (isatty (STDIN_FILENO)
1572 && ::ioctl (STDIN_FILENO, TIOCGWINSZ, &window_size) == 0)
1573 {
Jim Ingham57190ba2012-04-26 21:39:32 +00001574 if ((window_size.ws_col > 0) && g_driver != NULL)
Caroline Ticedd759852010-09-09 17:45:09 +00001575 {
Jim Ingham57190ba2012-04-26 21:39:32 +00001576 g_driver->GetDebugger().SetTerminalWidth (window_size.ws_col);
Caroline Ticedd759852010-09-09 17:45:09 +00001577 }
1578 }
1579}
1580
Caroline Ticeefed6132010-11-19 20:47:54 +00001581void
1582sigint_handler (int signo)
1583{
1584 static bool g_interrupt_sent = false;
1585 if (g_driver)
1586 {
1587 if (!g_interrupt_sent)
1588 {
1589 g_interrupt_sent = true;
1590 g_driver->GetDebugger().DispatchInputInterrupt();
1591 g_interrupt_sent = false;
1592 return;
1593 }
1594 }
1595
1596 exit (signo);
1597}
1598
Jim Inghamc5917d92012-11-30 20:23:19 +00001599void
1600sigtstp_handler (int signo)
1601{
1602 g_driver->GetDebugger().SaveInputTerminalState();
1603 signal (signo, SIG_DFL);
1604 kill (getpid(), signo);
1605 signal (signo, sigtstp_handler);
1606}
1607
1608void
1609sigcont_handler (int signo)
1610{
1611 g_driver->GetDebugger().RestoreInputTerminalState();
1612 signal (signo, SIG_DFL);
1613 kill (getpid(), signo);
1614 signal (signo, sigcont_handler);
1615}
1616
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001617int
Jim Inghama462f5c2011-01-27 20:15:39 +00001618main (int argc, char const *argv[], const char *envp[])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001619{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001620 SBDebugger::Initialize();
1621
Greg Clayton2ccf8cf2010-11-07 21:02:03 +00001622 SBHostOS::ThreadCreated ("<lldb.driver.main-thread>");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001623
Greg Clayton3fcbed62010-10-19 03:25:40 +00001624 signal (SIGPIPE, SIG_IGN);
Caroline Ticedd759852010-09-09 17:45:09 +00001625 signal (SIGWINCH, sigwinch_handler);
Caroline Ticeefed6132010-11-19 20:47:54 +00001626 signal (SIGINT, sigint_handler);
Jim Inghamc5917d92012-11-30 20:23:19 +00001627 signal (SIGTSTP, sigtstp_handler);
1628 signal (SIGCONT, sigcont_handler);
Caroline Ticedd759852010-09-09 17:45:09 +00001629
Greg Clayton66111032010-06-23 01:19:29 +00001630 // Create a scope for driver so that the driver object will destroy itself
1631 // before SBDebugger::Terminate() is called.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001632 {
Greg Clayton66111032010-06-23 01:19:29 +00001633 Driver driver;
1634
1635 bool exit = false;
1636 SBError error (driver.ParseArgs (argc, argv, stdout, exit));
1637 if (error.Fail())
1638 {
1639 const char *error_cstr = error.GetCString ();
1640 if (error_cstr)
1641 ::fprintf (stderr, "error: %s\n", error_cstr);
1642 }
1643 else if (!exit)
1644 {
1645 driver.MainLoop ();
1646 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001647 }
1648
1649 SBDebugger::Terminate();
1650 return 0;
1651}