blob: 29b50f05a55de4ce41bad49c5a38f2ef089011c8 [file] [log] [blame]
Chris Lattner24943d22010-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 Friedmanf2f321d2010-06-09 09:50:17 +000017#include <string.h>
18#include <stdlib.h>
19#include <limits.h>
Eli Friedmand6e167d2010-06-09 19:11:30 +000020#include <fcntl.h>
Chris Lattner24943d22010-06-08 16:52:24 +000021
22#include <string>
23
24#include "IOChannel.h"
Eli Friedmanf2f321d2010-06-09 09:50:17 +000025#include "lldb/API/SBCommandInterpreter.h"
26#include "lldb/API/SBCommandReturnObject.h"
27#include "lldb/API/SBCommunication.h"
28#include "lldb/API/SBDebugger.h"
29#include "lldb/API/SBEvent.h"
30#include "lldb/API/SBHostOS.h"
31#include "lldb/API/SBListener.h"
32#include "lldb/API/SBSourceManager.h"
33#include "lldb/API/SBTarget.h"
34#include "lldb/API/SBThread.h"
35#include "lldb/API/SBProcess.h"
Chris Lattner24943d22010-06-08 16:52:24 +000036
37using namespace lldb;
38
39static void reset_stdin_termios ();
40static struct termios g_old_stdin_termios;
41
Caroline Ticeb8314fe2010-09-09 17:45:09 +000042static char *g_debugger_name = (char *) "";
Caroline Ticec4f55fe2010-11-19 20:47:54 +000043static Driver *g_driver = NULL;
Caroline Ticeb8314fe2010-09-09 17:45:09 +000044
Chris Lattner24943d22010-06-08 16:52:24 +000045// In the Driver::MainLoop, we change the terminal settings. This function is
46// added as an atexit handler to make sure we clean them up.
47static void
48reset_stdin_termios ()
49{
50 ::tcsetattr (STDIN_FILENO, TCSANOW, &g_old_stdin_termios);
51}
52
53static lldb::OptionDefinition g_options[] =
54{
Caroline Tice4d6675c2010-10-01 19:59:14 +000055 { LLDB_OPT_SET_1, true, "help", 'h', no_argument, NULL, NULL, eArgTypeNone,
Chris Lattner24943d22010-06-08 16:52:24 +000056 "Prints out the usage information for the LLDB debugger." },
57
Caroline Tice4d6675c2010-10-01 19:59:14 +000058 { LLDB_OPT_SET_2, true, "version", 'v', no_argument, NULL, NULL, eArgTypeNone,
Chris Lattner24943d22010-06-08 16:52:24 +000059 "Prints out the current version number of the LLDB debugger." },
60
Caroline Tice4d6675c2010-10-01 19:59:14 +000061 { LLDB_OPT_SET_3, true, "arch", 'a', required_argument, NULL, NULL, eArgTypeArchitecture,
Chris Lattner24943d22010-06-08 16:52:24 +000062 "Tells the debugger to use the specified architecture when starting and running the program. <architecture> must be one of the architectures for which the program was compiled." },
63
Caroline Tice4d6675c2010-10-01 19:59:14 +000064 { LLDB_OPT_SET_3 | LLDB_OPT_SET_4, false, "script-language",'l', required_argument, NULL, NULL, eArgTypeScriptLang,
Chris Lattner24943d22010-06-08 16:52:24 +000065 "Tells the debugger to use the specified scripting language for user-defined scripts, rather than the default. Valid scripting languages that can be specified include Python, Perl, Ruby and Tcl. Currently only the Python extensions have been implemented." },
66
Caroline Tice4d6675c2010-10-01 19:59:14 +000067 { LLDB_OPT_SET_3 | LLDB_OPT_SET_4, false, "debug", 'd', no_argument, NULL, NULL, eArgTypeNone,
Chris Lattner24943d22010-06-08 16:52:24 +000068 "Tells the debugger to print out extra information for debugging itself." },
69
Caroline Tice4d6675c2010-10-01 19:59:14 +000070 { LLDB_OPT_SET_3 | LLDB_OPT_SET_4, false, "source", 's', required_argument, NULL, NULL, eArgTypeFilename,
Chris Lattner24943d22010-06-08 16:52:24 +000071 "Tells the debugger to read in and execute the file <file>, which should contain lldb commands." },
72
Caroline Tice4d6675c2010-10-01 19:59:14 +000073 { LLDB_OPT_SET_3, true, "file", 'f', required_argument, NULL, NULL, eArgTypeFilename,
Jim Ingham34e9a982010-06-15 18:47:14 +000074 "Tells the debugger to use the file <filename> as the program to be debugged." },
75
Caroline Tice4d6675c2010-10-01 19:59:14 +000076 { LLDB_OPT_SET_ALL, false, "editor", 'e', no_argument, NULL, NULL, eArgTypeNone,
Jim Ingham74989e82010-08-30 19:44:40 +000077 "Tells the debugger to open source files using the host's \"external editor\" mechanism." },
78
Greg Clayton887aa282010-10-11 01:05:37 +000079 { LLDB_OPT_SET_ALL, false, "no-lldbinit", 'n', no_argument, NULL, NULL, eArgTypeNone,
80 "Do not automatically parse any '.lldbinit' files." },
81
Caroline Tice4d6675c2010-10-01 19:59:14 +000082// { LLDB_OPT_SET_4, true, "crash-log", 'c', required_argument, NULL, NULL, eArgTypeFilename,
Greg Clayton12bec712010-06-28 21:30:43 +000083// "Load executable images from a crash log for symbolication." },
Chris Lattner24943d22010-06-08 16:52:24 +000084
Caroline Tice4d6675c2010-10-01 19:59:14 +000085 { 0, false, NULL, 0, 0, NULL, NULL, eArgTypeNone, NULL }
Chris Lattner24943d22010-06-08 16:52:24 +000086};
87
88
89Driver::Driver () :
90 SBBroadcaster ("Driver"),
Greg Clayton63094e02010-06-23 01:19:29 +000091 m_debugger (SBDebugger::Create()),
Chris Lattner24943d22010-06-08 16:52:24 +000092 m_editline_pty (),
93 m_editline_slave_fh (NULL),
94 m_editline_reader (),
95 m_io_channel_ap (),
96 m_option_data (),
97 m_waiting_for_command (false)
98{
Caroline Ticeb8314fe2010-09-09 17:45:09 +000099 g_debugger_name = (char *) m_debugger.GetInstanceName();
100 if (g_debugger_name == NULL)
101 g_debugger_name = (char *) "";
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000102 g_driver = this;
Chris Lattner24943d22010-06-08 16:52:24 +0000103}
104
105Driver::~Driver ()
106{
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000107 g_driver = NULL;
108 g_debugger_name = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000109}
110
111void
112Driver::CloseIOChannelFile ()
113{
114 // Write and End of File sequence to the file descriptor to ensure any
115 // read functions can exit.
116 char eof_str[] = "\x04";
117 ::write (m_editline_pty.GetMasterFileDescriptor(), eof_str, strlen(eof_str));
118
119 m_editline_pty.CloseMasterFileDescriptor();
120
121 if (m_editline_slave_fh)
122 {
123 ::fclose (m_editline_slave_fh);
124 m_editline_slave_fh = NULL;
125 }
126}
127
Greg Clayton54e7afa2010-07-09 20:39:50 +0000128// This function takes INDENT, which tells how many spaces to output at the front
129// of each line; TEXT, which is the text that is to be output. It outputs the
130// text, on multiple lines if necessary, to RESULT, with INDENT spaces at the
131// front of each line. It breaks lines on spaces, tabs or newlines, shortening
132// the line if necessary to not break in the middle of a word. It assumes that
133// each output line should contain a maximum of OUTPUT_MAX_COLUMNS characters.
Chris Lattner24943d22010-06-08 16:52:24 +0000134
135void
Greg Clayton54e7afa2010-07-09 20:39:50 +0000136OutputFormattedUsageText (FILE *out, int indent, const char *text, int output_max_columns)
Chris Lattner24943d22010-06-08 16:52:24 +0000137{
138 int len = strlen (text);
139 std::string text_string (text);
Chris Lattner24943d22010-06-08 16:52:24 +0000140
141 // Force indentation to be reasonable.
142 if (indent >= output_max_columns)
143 indent = 0;
144
145 // Will it all fit on one line?
146
147 if (len + indent < output_max_columns)
148 // Output as a single line
Greg Clayton54e7afa2010-07-09 20:39:50 +0000149 fprintf (out, "%*s%s\n", indent, "", text);
Chris Lattner24943d22010-06-08 16:52:24 +0000150 else
151 {
152 // We need to break it up into multiple lines.
153 int text_width = output_max_columns - indent - 1;
154 int start = 0;
155 int end = start;
156 int final_end = len;
157 int sub_len;
158
159 while (end < final_end)
160 {
161 // Dont start the 'text' on a space, since we're already outputting the indentation.
162 while ((start < final_end) && (text[start] == ' '))
163 start++;
164
165 end = start + text_width;
166 if (end > final_end)
167 end = final_end;
168 else
169 {
170 // If we're not at the end of the text, make sure we break the line on white space.
171 while (end > start
172 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
173 end--;
174 }
175 sub_len = end - start;
176 std::string substring = text_string.substr (start, sub_len);
Greg Clayton54e7afa2010-07-09 20:39:50 +0000177 fprintf (out, "%*s%s\n", indent, "", substring.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000178 start = end + 1;
179 }
180 }
181}
182
Caroline Tice4d6675c2010-10-01 19:59:14 +0000183void
184GetArgumentName (const CommandArgumentType arg_type, std::string &arg_name)
185{
186 //Fudge this function here, since we can't call the "real" version in lldb_private::CommandObject...
187
188 switch (arg_type)
189 {
190 // Make cases for all the arg_types used in Driver.cpp
191
192 case eArgTypeNone:
193 arg_name = "";
194 break;
195
196 case eArgTypeArchitecture:
197 arg_name = "architecture";
198 break;
199
200 case eArgTypeScriptLang:
201 arg_name = "script-language";
202 break;
203
204 case eArgTypeFilename:
205 arg_name = "filename";
206 break;
207 }
208 return;
209}
210
211
Chris Lattner24943d22010-06-08 16:52:24 +0000212void
213ShowUsage (FILE *out, lldb::OptionDefinition *option_table, Driver::OptionData data)
214{
215 uint32_t screen_width = 80;
216 uint32_t indent_level = 0;
217 const char *name = "lldb";
Jim Ingham34e9a982010-06-15 18:47:14 +0000218
Chris Lattner24943d22010-06-08 16:52:24 +0000219 fprintf (out, "\nUsage:\n\n");
220
221 indent_level += 2;
222
223
224 // First, show each usage level set of options, e.g. <cmd> [options-for-level-0]
225 // <cmd> [options-for-level-1]
226 // etc.
227
Chris Lattner24943d22010-06-08 16:52:24 +0000228 uint32_t num_options;
Jim Ingham34e9a982010-06-15 18:47:14 +0000229 uint32_t num_option_sets = 0;
230
231 for (num_options = 0; option_table[num_options].long_option != NULL; ++num_options)
Chris Lattner24943d22010-06-08 16:52:24 +0000232 {
Jim Ingham34e9a982010-06-15 18:47:14 +0000233 uint32_t this_usage_mask = option_table[num_options].usage_mask;
234 if (this_usage_mask == LLDB_OPT_SET_ALL)
Chris Lattner24943d22010-06-08 16:52:24 +0000235 {
Jim Ingham34e9a982010-06-15 18:47:14 +0000236 if (num_option_sets == 0)
237 num_option_sets = 1;
Chris Lattner24943d22010-06-08 16:52:24 +0000238 }
239 else
240 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000241 for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++)
Jim Ingham34e9a982010-06-15 18:47:14 +0000242 {
243 if (this_usage_mask & 1 << j)
244 {
245 if (num_option_sets <= j)
246 num_option_sets = j + 1;
247 }
248 }
249 }
250 }
251
252 for (uint32_t opt_set = 0; opt_set < num_option_sets; opt_set++)
253 {
254 uint32_t opt_set_mask;
255
256 opt_set_mask = 1 << opt_set;
257
258 if (opt_set > 0)
259 fprintf (out, "\n");
Greg Clayton54e7afa2010-07-09 20:39:50 +0000260 fprintf (out, "%*s%s", indent_level, "", name);
Jim Ingham34e9a982010-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 Tice4d6675c2010-10-01 19:59:14 +0000266 CommandArgumentType arg_type = option_table[i].argument_type;
267 std::string arg_name;
268 GetArgumentName (arg_type, arg_name);
Jim Ingham34e9a982010-06-15 18:47:14 +0000269 if (option_table[i].required)
270 {
271 if (option_table[i].option_has_arg == required_argument)
Caroline Tice4d6675c2010-10-01 19:59:14 +0000272 fprintf (out, " -%c <%s>", option_table[i].short_option, arg_name.c_str());
Jim Ingham34e9a982010-06-15 18:47:14 +0000273 else if (option_table[i].option_has_arg == optional_argument)
Caroline Tice4d6675c2010-10-01 19:59:14 +0000274 fprintf (out, " -%c [<%s>]", option_table[i].short_option, arg_name.c_str());
Jim Ingham34e9a982010-06-15 18:47:14 +0000275 else
276 fprintf (out, " -%c", option_table[i].short_option);
277 }
278 else
279 {
280 if (option_table[i].option_has_arg == required_argument)
Caroline Tice4d6675c2010-10-01 19:59:14 +0000281 fprintf (out, " [-%c <%s>]", option_table[i].short_option, arg_name.c_str());
Jim Ingham34e9a982010-06-15 18:47:14 +0000282 else if (option_table[i].option_has_arg == optional_argument)
Caroline Tice4d6675c2010-10-01 19:59:14 +0000283 fprintf (out, " [-%c [<%s>]]", option_table[i].short_option, arg_name.c_str());
Jim Ingham34e9a982010-06-15 18:47:14 +0000284 else
285 fprintf (out, " [-%c]", option_table[i].short_option);
286 }
287 }
Chris Lattner24943d22010-06-08 16:52:24 +0000288 }
289 }
290
291 fprintf (out, "\n\n");
292
293 // Now print out all the detailed information about the various options: long form, short form and help text:
294 // -- long_name <argument>
295 // - short <argument>
296 // help text
297
298 // This variable is used to keep track of which options' info we've printed out, because some options can be in
299 // more than one usage level, but we only want to print the long form of its information once.
300
301 Driver::OptionData::OptionSet options_seen;
302 Driver::OptionData::OptionSet::iterator pos;
303
304 indent_level += 5;
305
Jim Ingham34e9a982010-06-15 18:47:14 +0000306 for (uint32_t i = 0; i < num_options; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +0000307 {
308 // Only print this option if we haven't already seen it.
309 pos = options_seen.find (option_table[i].short_option);
310 if (pos == options_seen.end())
311 {
Caroline Tice4d6675c2010-10-01 19:59:14 +0000312 CommandArgumentType arg_type = option_table[i].argument_type;
313 std::string arg_name;
314 GetArgumentName (arg_type, arg_name);
315
Chris Lattner24943d22010-06-08 16:52:24 +0000316 options_seen.insert (option_table[i].short_option);
Greg Clayton54e7afa2010-07-09 20:39:50 +0000317 fprintf (out, "%*s-%c ", indent_level, "", option_table[i].short_option);
Caroline Tice4d6675c2010-10-01 19:59:14 +0000318 if (arg_type != eArgTypeNone)
319 fprintf (out, "<%s>", arg_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000320 fprintf (out, "\n");
Greg Clayton54e7afa2010-07-09 20:39:50 +0000321 fprintf (out, "%*s--%s ", indent_level, "", option_table[i].long_option);
Caroline Tice4d6675c2010-10-01 19:59:14 +0000322 if (arg_type != eArgTypeNone)
323 fprintf (out, "<%s>", arg_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000324 fprintf (out, "\n");
325 indent_level += 5;
Greg Clayton54e7afa2010-07-09 20:39:50 +0000326 OutputFormattedUsageText (out, indent_level, option_table[i].usage_text, screen_width);
Chris Lattner24943d22010-06-08 16:52:24 +0000327 indent_level -= 5;
328 fprintf (out, "\n");
329 }
330 }
331
332 indent_level -= 5;
333
Greg Clayton54e7afa2010-07-09 20:39:50 +0000334 fprintf (out, "\n%*s('%s <filename>' also works, to specify the file to be debugged.)\n\n",
335 indent_level, "", name);
Chris Lattner24943d22010-06-08 16:52:24 +0000336}
337
338void
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000339BuildGetOptTable (lldb::OptionDefinition *expanded_option_table, std::vector<struct option> &getopt_table,
340 uint32_t num_options)
Chris Lattner24943d22010-06-08 16:52:24 +0000341{
342 if (num_options == 0)
343 return;
344
345 uint32_t i;
346 uint32_t j;
347 std::bitset<256> option_seen;
348
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000349 getopt_table.resize (num_options + 1);
350
Chris Lattner24943d22010-06-08 16:52:24 +0000351 for (i = 0, j = 0; i < num_options; ++i)
Greg Clayton54e7afa2010-07-09 20:39:50 +0000352 {
Chris Lattner24943d22010-06-08 16:52:24 +0000353 char short_opt = expanded_option_table[i].short_option;
Greg Clayton54e7afa2010-07-09 20:39:50 +0000354
Chris Lattner24943d22010-06-08 16:52:24 +0000355 if (option_seen.test(short_opt) == false)
Greg Clayton54e7afa2010-07-09 20:39:50 +0000356 {
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000357 getopt_table[j].name = expanded_option_table[i].long_option;
358 getopt_table[j].has_arg = expanded_option_table[i].option_has_arg;
359 getopt_table[j].flag = NULL;
360 getopt_table[j].val = expanded_option_table[i].short_option;
Chris Lattner24943d22010-06-08 16:52:24 +0000361 option_seen.set(short_opt);
362 ++j;
Greg Clayton54e7afa2010-07-09 20:39:50 +0000363 }
364 }
Chris Lattner24943d22010-06-08 16:52:24 +0000365
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000366 getopt_table[j].name = NULL;
367 getopt_table[j].has_arg = 0;
368 getopt_table[j].flag = NULL;
369 getopt_table[j].val = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000370
371}
372
Greg Clayton63094e02010-06-23 01:19:29 +0000373Driver::OptionData::OptionData () :
374 m_filename(),
375 m_script_lang (lldb::eScriptLanguageDefault),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000376 m_crash_log (),
Greg Clayton63094e02010-06-23 01:19:29 +0000377 m_source_command_files (),
378 m_debug_mode (false),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000379 m_print_version (false),
Greg Clayton63094e02010-06-23 01:19:29 +0000380 m_print_help (false),
Jim Ingham74989e82010-08-30 19:44:40 +0000381 m_seen_options(),
382 m_use_external_editor(false)
Chris Lattner24943d22010-06-08 16:52:24 +0000383{
Greg Clayton63094e02010-06-23 01:19:29 +0000384}
385
386Driver::OptionData::~OptionData ()
387{
388}
389
390void
391Driver::OptionData::Clear ()
392{
393 m_filename.clear ();
394 m_script_lang = lldb::eScriptLanguageDefault;
395 m_source_command_files.clear ();
396 m_debug_mode = false;
397 m_print_help = false;
398 m_print_version = false;
Jim Ingham74989e82010-08-30 19:44:40 +0000399 m_use_external_editor = false;
Greg Clayton63094e02010-06-23 01:19:29 +0000400}
401
402void
403Driver::ResetOptionValues ()
404{
405 m_option_data.Clear ();
406}
407
408const char *
409Driver::GetFilename() const
410{
411 if (m_option_data.m_filename.empty())
412 return NULL;
413 return m_option_data.m_filename.c_str();
414}
415
416const char *
417Driver::GetCrashLogFilename() const
418{
419 if (m_option_data.m_crash_log.empty())
420 return NULL;
421 return m_option_data.m_crash_log.c_str();
422}
423
424lldb::ScriptLanguage
425Driver::GetScriptLanguage() const
426{
427 return m_option_data.m_script_lang;
428}
429
430size_t
431Driver::GetNumSourceCommandFiles () const
432{
433 return m_option_data.m_source_command_files.size();
434}
435
436const char *
437Driver::GetSourceCommandFileAtIndex (uint32_t idx) const
438{
439 if (idx < m_option_data.m_source_command_files.size())
440 return m_option_data.m_source_command_files[idx].c_str();
441 return NULL;
442}
443
444bool
445Driver::GetDebugMode() const
446{
447 return m_option_data.m_debug_mode;
448}
449
450
451// Check the arguments that were passed to this program to make sure they are valid and to get their
452// argument values (if any). Return a boolean value indicating whether or not to start up the full
453// debugger (i.e. the Command Interpreter) or not. Return FALSE if the arguments were invalid OR
454// if the user only wanted help or version information.
455
456SBError
457Driver::ParseArgs (int argc, const char *argv[], FILE *out_fh, bool &exit)
458{
459 ResetOptionValues ();
460
461 SBCommandReturnObject result;
462
Chris Lattner24943d22010-06-08 16:52:24 +0000463 SBError error;
464 std::string option_string;
465 struct option *long_options = NULL;
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000466 std::vector<struct option> long_options_vector;
Greg Clayton54e7afa2010-07-09 20:39:50 +0000467 uint32_t num_options;
Chris Lattner24943d22010-06-08 16:52:24 +0000468
Greg Clayton54e7afa2010-07-09 20:39:50 +0000469 for (num_options = 0; g_options[num_options].long_option != NULL; ++num_options)
470 /* Do Nothing. */;
Chris Lattner24943d22010-06-08 16:52:24 +0000471
472 if (num_options == 0)
473 {
474 if (argc > 1)
475 error.SetErrorStringWithFormat ("invalid number of options");
476 return error;
477 }
478
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000479 BuildGetOptTable (g_options, long_options_vector, num_options);
Chris Lattner24943d22010-06-08 16:52:24 +0000480
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000481 if (long_options_vector.empty())
482 long_options = NULL;
483 else
484 long_options = &long_options_vector.front();
Chris Lattner24943d22010-06-08 16:52:24 +0000485
486 if (long_options == NULL)
487 {
488 error.SetErrorStringWithFormat ("invalid long options");
489 return error;
490 }
491
492 // Build the option_string argument for call to getopt_long.
493
494 for (int i = 0; long_options[i].name != NULL; ++i)
495 {
496 if (long_options[i].flag == NULL)
497 {
498 option_string.push_back ((char) long_options[i].val);
499 switch (long_options[i].has_arg)
500 {
501 default:
502 case no_argument:
503 break;
504 case required_argument:
505 option_string.push_back (':');
506 break;
507 case optional_argument:
508 option_string.append ("::");
509 break;
510 }
511 }
512 }
513
514 // Prepare for & make calls to getopt_long.
Eli Friedmanef2bc872010-06-13 19:18:49 +0000515#if __GLIBC__
516 optind = 0;
517#else
Chris Lattner24943d22010-06-08 16:52:24 +0000518 optreset = 1;
519 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +0000520#endif
Chris Lattner24943d22010-06-08 16:52:24 +0000521 int val;
522 while (1)
523 {
524 int long_options_index = -1;
Greg Clayton54e7afa2010-07-09 20:39:50 +0000525 val = ::getopt_long (argc, const_cast<char **>(argv), option_string.c_str(), long_options, &long_options_index);
Chris Lattner24943d22010-06-08 16:52:24 +0000526
527 if (val == -1)
528 break;
529 else if (val == '?')
530 {
Greg Clayton63094e02010-06-23 01:19:29 +0000531 m_option_data.m_print_help = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000532 error.SetErrorStringWithFormat ("unknown or ambiguous option");
533 break;
534 }
535 else if (val == 0)
536 continue;
537 else
538 {
Greg Clayton63094e02010-06-23 01:19:29 +0000539 m_option_data.m_seen_options.insert ((char) val);
Chris Lattner24943d22010-06-08 16:52:24 +0000540 if (long_options_index == -1)
541 {
542 for (int i = 0;
543 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val;
544 ++i)
545 {
546 if (long_options[i].val == val)
547 {
548 long_options_index = i;
549 break;
550 }
551 }
552 }
553
554 if (long_options_index >= 0)
555 {
Greg Clayton63094e02010-06-23 01:19:29 +0000556 const char short_option = (char) g_options[long_options_index].short_option;
557
558 switch (short_option)
559 {
560 case 'h':
561 m_option_data.m_print_help = true;
562 break;
563
564 case 'v':
565 m_option_data.m_print_version = true;
566 break;
567
568 case 'c':
569 m_option_data.m_crash_log = optarg;
570 break;
Greg Clayton887aa282010-10-11 01:05:37 +0000571
Jim Ingham74989e82010-08-30 19:44:40 +0000572 case 'e':
573 m_option_data.m_use_external_editor = true;
574 break;
Greg Clayton887aa282010-10-11 01:05:37 +0000575
576 case 'n':
577 m_debugger.SkipLLDBInitFiles (true);
578 break;
579
Greg Clayton63094e02010-06-23 01:19:29 +0000580 case 'f':
581 {
582 SBFileSpec file(optarg);
583 if (file.Exists())
584 m_option_data.m_filename = optarg;
Caroline Ticeeddffe92010-09-10 04:48:55 +0000585 else if (file.ResolveExecutableLocation())
586 {
587 char path[PATH_MAX];
588 int path_len;
589 file.GetPath (path, path_len);
590 m_option_data.m_filename = path;
591 }
Greg Clayton63094e02010-06-23 01:19:29 +0000592 else
593 error.SetErrorStringWithFormat("file specified in --file (-f) option doesn't exist: '%s'", optarg);
594 }
595 break;
596
597 case 'a':
598 if (!m_debugger.SetDefaultArchitecture (optarg))
599 error.SetErrorStringWithFormat("invalid architecture in the -a or --arch option: '%s'", optarg);
600 break;
601
602 case 'l':
603 m_option_data.m_script_lang = m_debugger.GetScriptingLanguage (optarg);
604 break;
605
606 case 'd':
607 m_option_data.m_debug_mode = true;
608 break;
609
610 case 's':
611 {
612 SBFileSpec file(optarg);
613 if (file.Exists())
614 m_option_data.m_source_command_files.push_back (optarg);
Caroline Ticeeddffe92010-09-10 04:48:55 +0000615 else if (file.ResolveExecutableLocation())
616 {
617 char final_path[PATH_MAX];
618 size_t path_len;
619 file.GetPath (final_path, path_len);
620 std::string path_str (final_path);
621 m_option_data.m_source_command_files.push_back (path_str);
622 }
Greg Clayton63094e02010-06-23 01:19:29 +0000623 else
624 error.SetErrorStringWithFormat("file specified in --source (-s) option doesn't exist: '%s'", optarg);
625 }
626 break;
627
628 default:
629 m_option_data.m_print_help = true;
630 error.SetErrorStringWithFormat ("unrecognized option %c", short_option);
631 break;
632 }
Chris Lattner24943d22010-06-08 16:52:24 +0000633 }
634 else
635 {
636 error.SetErrorStringWithFormat ("invalid option with value %i", val);
637 }
638 if (error.Fail())
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000639 {
Greg Clayton63094e02010-06-23 01:19:29 +0000640 return error;
Caroline Ticebd5c63e2010-10-12 21:57:09 +0000641 }
Chris Lattner24943d22010-06-08 16:52:24 +0000642 }
643 }
Jim Ingham34e9a982010-06-15 18:47:14 +0000644
645 // If there is a trailing argument, it is the filename.
646 if (optind == argc - 1)
647 {
648 if (m_option_data.m_filename.empty())
Chris Lattner24943d22010-06-08 16:52:24 +0000649 {
Jim Ingham34e9a982010-06-15 18:47:14 +0000650 m_option_data.m_filename = argv[optind];
Chris Lattner24943d22010-06-08 16:52:24 +0000651 }
Jim Ingham34e9a982010-06-15 18:47:14 +0000652 else
653 {
Greg Clayton63094e02010-06-23 01:19:29 +0000654 error.SetErrorStringWithFormat ("error: don't provide a file both on in the -f option and as an argument.");
Jim Ingham34e9a982010-06-15 18:47:14 +0000655 }
656
Chris Lattner24943d22010-06-08 16:52:24 +0000657 }
Jim Ingham34e9a982010-06-15 18:47:14 +0000658 else if (optind < argc - 1)
659 {
660 // Trailing extra arguments...
Greg Clayton63094e02010-06-23 01:19:29 +0000661 error.SetErrorStringWithFormat ("error: trailing extra arguments - only one the filename is allowed.");
Jim Ingham34e9a982010-06-15 18:47:14 +0000662 }
663
Greg Clayton63094e02010-06-23 01:19:29 +0000664 if (error.Fail() || m_option_data.m_print_help)
Chris Lattner24943d22010-06-08 16:52:24 +0000665 {
666 ShowUsage (out_fh, g_options, m_option_data);
Greg Clayton9caa9462010-10-11 01:13:37 +0000667 exit = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000668 }
669 else if (m_option_data.m_print_version)
670 {
Greg Clayton63094e02010-06-23 01:19:29 +0000671 ::fprintf (out_fh, "%s\n", m_debugger.GetVersionString());
672 exit = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000673 }
674 else if (! m_option_data.m_crash_log.empty())
675 {
676 // Handle crash log stuff here.
677 }
678 else
679 {
680 // All other combinations are valid; do nothing more here.
681 }
682
Greg Clayton63094e02010-06-23 01:19:29 +0000683 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000684}
685
Caroline Tice757500e2010-09-29 18:35:42 +0000686size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000687Driver::GetProcessSTDOUT ()
688{
689 // The process has stuff waiting for stdout; get it and write it out to the appropriate place.
690 char stdio_buffer[1024];
691 size_t len;
Caroline Tice757500e2010-09-29 18:35:42 +0000692 size_t total_bytes = 0;
Jim Inghamc8332952010-08-26 21:32:51 +0000693 while ((len = m_debugger.GetSelectedTarget().GetProcess().GetSTDOUT (stdio_buffer, sizeof (stdio_buffer))) > 0)
Caroline Tice757500e2010-09-29 18:35:42 +0000694 {
Chris Lattner24943d22010-06-08 16:52:24 +0000695 m_io_channel_ap->OutWrite (stdio_buffer, len);
Caroline Tice757500e2010-09-29 18:35:42 +0000696 total_bytes += len;
697 }
698 return total_bytes;
Chris Lattner24943d22010-06-08 16:52:24 +0000699}
700
Caroline Tice757500e2010-09-29 18:35:42 +0000701size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000702Driver::GetProcessSTDERR ()
703{
704 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
705 char stdio_buffer[1024];
706 size_t len;
Caroline Tice757500e2010-09-29 18:35:42 +0000707 size_t total_bytes = 0;
Jim Inghamc8332952010-08-26 21:32:51 +0000708 while ((len = m_debugger.GetSelectedTarget().GetProcess().GetSTDERR (stdio_buffer, sizeof (stdio_buffer))) > 0)
Caroline Tice757500e2010-09-29 18:35:42 +0000709 {
Chris Lattner24943d22010-06-08 16:52:24 +0000710 m_io_channel_ap->ErrWrite (stdio_buffer, len);
Caroline Tice757500e2010-09-29 18:35:42 +0000711 total_bytes += len;
712 }
713 return total_bytes;
Chris Lattner24943d22010-06-08 16:52:24 +0000714}
715
716void
Jim Inghamc8332952010-08-26 21:32:51 +0000717Driver::UpdateSelectedThread ()
Chris Lattner24943d22010-06-08 16:52:24 +0000718{
719 using namespace lldb;
Jim Inghamc8332952010-08-26 21:32:51 +0000720 SBProcess process(m_debugger.GetSelectedTarget().GetProcess());
Chris Lattner24943d22010-06-08 16:52:24 +0000721 if (process.IsValid())
722 {
Jim Inghamc8332952010-08-26 21:32:51 +0000723 SBThread curr_thread (process.GetSelectedThread());
Chris Lattner24943d22010-06-08 16:52:24 +0000724 SBThread thread;
725 StopReason curr_thread_stop_reason = eStopReasonInvalid;
726 curr_thread_stop_reason = curr_thread.GetStopReason();
727
728 if (!curr_thread.IsValid() ||
729 curr_thread_stop_reason == eStopReasonInvalid ||
730 curr_thread_stop_reason == eStopReasonNone)
731 {
732 // Prefer a thread that has just completed its plan over another thread as current thread.
733 SBThread plan_thread;
734 SBThread other_thread;
735 const size_t num_threads = process.GetNumThreads();
736 size_t i;
737 for (i = 0; i < num_threads; ++i)
738 {
739 thread = process.GetThreadAtIndex(i);
740 StopReason thread_stop_reason = thread.GetStopReason();
741 switch (thread_stop_reason)
742 {
743 default:
744 case eStopReasonInvalid:
745 case eStopReasonNone:
746 break;
747
748 case eStopReasonTrace:
749 case eStopReasonBreakpoint:
750 case eStopReasonWatchpoint:
751 case eStopReasonSignal:
752 case eStopReasonException:
753 if (!other_thread.IsValid())
754 other_thread = thread;
755 break;
756 case eStopReasonPlanComplete:
757 if (!plan_thread.IsValid())
758 plan_thread = thread;
759 break;
760 }
761 }
762 if (plan_thread.IsValid())
Jim Inghamc8332952010-08-26 21:32:51 +0000763 process.SetSelectedThread (plan_thread);
Chris Lattner24943d22010-06-08 16:52:24 +0000764 else if (other_thread.IsValid())
Jim Inghamc8332952010-08-26 21:32:51 +0000765 process.SetSelectedThread (other_thread);
Chris Lattner24943d22010-06-08 16:52:24 +0000766 else
767 {
768 if (curr_thread.IsValid())
769 thread = curr_thread;
770 else
771 thread = process.GetThreadAtIndex(0);
772
773 if (thread.IsValid())
Jim Inghamc8332952010-08-26 21:32:51 +0000774 process.SetSelectedThread (thread);
Chris Lattner24943d22010-06-08 16:52:24 +0000775 }
776 }
777 }
778}
779
780
781// This function handles events that were broadcast by the process.
782void
783Driver::HandleProcessEvent (const SBEvent &event)
784{
785 using namespace lldb;
786 const uint32_t event_type = event.GetType();
787
788 if (event_type & SBProcess::eBroadcastBitSTDOUT)
789 {
790 // The process has stdout available, get it and write it out to the
791 // appropriate place.
Caroline Tice757500e2010-09-29 18:35:42 +0000792 if (GetProcessSTDOUT ())
793 m_io_channel_ap->RefreshPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000794 }
795 else if (event_type & SBProcess::eBroadcastBitSTDERR)
796 {
797 // The process has stderr available, get it and write it out to the
798 // appropriate place.
Caroline Tice757500e2010-09-29 18:35:42 +0000799 if (GetProcessSTDERR ())
800 m_io_channel_ap->RefreshPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000801 }
802 else if (event_type & SBProcess::eBroadcastBitStateChanged)
803 {
804 // Drain all stout and stderr so we don't see any output come after
805 // we print our prompts
Caroline Tice757500e2010-09-29 18:35:42 +0000806 if (GetProcessSTDOUT ()
807 || GetProcessSTDERR ())
808 m_io_channel_ap->RefreshPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000809
810 // Something changed in the process; get the event and report the process's current status and location to
811 // the user.
812 StateType event_state = SBProcess::GetStateFromEvent (event);
813 if (event_state == eStateInvalid)
814 return;
815
816 SBProcess process (SBProcess::GetProcessFromEvent (event));
817 assert (process.IsValid());
818
819 switch (event_state)
820 {
821 case eStateInvalid:
822 case eStateUnloaded:
823 case eStateAttaching:
824 case eStateLaunching:
825 case eStateStepping:
826 case eStateDetached:
827 {
828 char message[1024];
829 int message_len = ::snprintf (message, sizeof(message), "Process %d %s\n", process.GetProcessID(),
Greg Clayton63094e02010-06-23 01:19:29 +0000830 m_debugger.StateAsCString (event_state));
Chris Lattner24943d22010-06-08 16:52:24 +0000831 m_io_channel_ap->OutWrite(message, message_len);
832 }
833 break;
834
835 case eStateRunning:
836 // Don't be chatty when we run...
837 break;
838
839 case eStateExited:
Caroline Tice757500e2010-09-29 18:35:42 +0000840 {
841 SBCommandReturnObject result;
842 m_debugger.GetCommandInterpreter().HandleCommand("process status", result, false);
843 m_io_channel_ap->ErrWrite (result.GetError(), result.GetErrorSize());
844 m_io_channel_ap->OutWrite (result.GetOutput(), result.GetOutputSize());
845 m_io_channel_ap->RefreshPrompt();
846 }
Chris Lattner24943d22010-06-08 16:52:24 +0000847 break;
848
849 case eStateStopped:
850 case eStateCrashed:
851 case eStateSuspended:
852 // Make sure the program hasn't been auto-restarted:
853 if (SBProcess::GetRestartedFromEvent (event))
854 {
855 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
856 char message[1024];
857 int message_len = ::snprintf (message, sizeof(message), "Process %d stopped and was programmatically restarted.\n",
858 process.GetProcessID());
859 m_io_channel_ap->OutWrite(message, message_len);
Caroline Tice757500e2010-09-29 18:35:42 +0000860 m_io_channel_ap->RefreshPrompt ();
Chris Lattner24943d22010-06-08 16:52:24 +0000861 }
862 else
863 {
Caroline Tice757500e2010-09-29 18:35:42 +0000864 SBCommandReturnObject result;
Jim Inghamc8332952010-08-26 21:32:51 +0000865 UpdateSelectedThread ();
Caroline Tice757500e2010-09-29 18:35:42 +0000866 m_debugger.GetCommandInterpreter().HandleCommand("process status", result, false);
867 m_io_channel_ap->ErrWrite (result.GetError(), result.GetErrorSize());
868 m_io_channel_ap->OutWrite (result.GetOutput(), result.GetOutputSize());
869 m_io_channel_ap->RefreshPrompt ();
Chris Lattner24943d22010-06-08 16:52:24 +0000870 }
871 break;
872 }
873 }
874}
875
876// This function handles events broadcast by the IOChannel (HasInput, UserInterrupt, or ThreadShouldExit).
877
878bool
879Driver::HandleIOEvent (const SBEvent &event)
880{
881 bool quit = false;
882
883 const uint32_t event_type = event.GetType();
884
885 if (event_type & IOChannel::eBroadcastBitHasUserInput)
886 {
887 // We got some input (i.e. a command string) from the user; pass it off to the command interpreter for
888 // handling.
889
890 const char *command_string = SBEvent::GetCStringFromEvent(event);
891 if (command_string == NULL)
Greg Clayton54e7afa2010-07-09 20:39:50 +0000892 command_string = "";
Chris Lattner24943d22010-06-08 16:52:24 +0000893 SBCommandReturnObject result;
Greg Clayton63094e02010-06-23 01:19:29 +0000894 if (m_debugger.GetCommandInterpreter().HandleCommand (command_string, result, true) != lldb::eReturnStatusQuit)
Chris Lattner24943d22010-06-08 16:52:24 +0000895 {
896 m_io_channel_ap->ErrWrite (result.GetError(), result.GetErrorSize());
897 m_io_channel_ap->OutWrite (result.GetOutput(), result.GetOutputSize());
898 }
899 // We are done getting and running our command, we can now clear the
900 // m_waiting_for_command so we can get another one.
901 m_waiting_for_command = false;
902
903 // If our editline input reader is active, it means another input reader
904 // got pushed onto the input reader and caused us to become deactivated.
905 // When the input reader above us gets popped, we will get re-activated
906 // and our prompt will refresh in our callback
907 if (m_editline_reader.IsActive())
908 {
909 ReadyForCommand ();
910 }
911 }
912 else if (event_type & IOChannel::eBroadcastBitUserInterrupt)
913 {
914 // This is here to handle control-c interrupts from the user. It has not yet really been implemented.
915 // TO BE DONE: PROPERLY HANDLE CONTROL-C FROM USER
916 //m_io_channel_ap->CancelInput();
917 // Anything else? Send Interrupt to process?
918 }
919 else if ((event_type & IOChannel::eBroadcastBitThreadShouldExit) ||
920 (event_type & IOChannel::eBroadcastBitThreadDidExit))
921 {
922 // If the IOChannel thread is trying to go away, then it is definitely
923 // time to end the debugging session.
924 quit = true;
925 }
926
927 return quit;
928}
929
930
931//struct CrashImageInfo
932//{
933// std::string path;
934// VMRange text_range;
935// UUID uuid;
936//};
937//
938//void
939//Driver::ParseCrashLog (const char *crash_log)
940//{
941// printf("Parsing crash log: %s\n", crash_log);
942//
943// char image_path[PATH_MAX];
944// std::vector<CrashImageInfo> crash_infos;
945// if (crash_log && crash_log[0])
946// {
947// FileSpec crash_log_file (crash_log);
948// STLStringArray crash_log_lines;
949// if (crash_log_file.ReadFileLines (crash_log_lines))
950// {
951// const size_t num_crash_log_lines = crash_log_lines.size();
952// size_t i;
953// for (i=0; i<num_crash_log_lines; ++i)
954// {
955// const char *line = crash_log_lines[i].c_str();
956// if (strstr (line, "Code Type:"))
957// {
958// char arch_string[256];
959// if (sscanf(line, "%s", arch_string))
960// {
961// if (strcmp(arch_string, "X86-64"))
962// lldb::GetDefaultArchitecture ().SetArch ("x86_64");
963// else if (strcmp(arch_string, "X86"))
964// lldb::GetDefaultArchitecture ().SetArch ("i386");
965// else
966// {
967// ArchSpec arch(arch_string);
968// if (arch.IsValid ())
969// lldb::GetDefaultArchitecture () = arch;
970// else
971// fprintf(stderr, "Unrecognized architecture: %s\n", arch_string);
972// }
973// }
974// }
975// else
976// if (strstr(line, "Path:"))
977// {
978// const char *p = line + strlen("Path:");
979// while (isspace(*p))
980// ++p;
981//
982// m_option_data.m_filename.assign (p);
983// }
984// else
985// if (strstr(line, "Binary Images:"))
986// {
987// while (++i < num_crash_log_lines)
988// {
989// if (crash_log_lines[i].empty())
990// break;
991//
992// line = crash_log_lines[i].c_str();
993// uint64_t text_start_addr;
994// uint64_t text_end_addr;
995// char uuid_cstr[64];
996// int bytes_consumed_before_uuid = 0;
997// int bytes_consumed_after_uuid = 0;
998//
999// int items_parsed = ::sscanf (line,
1000// "%llx - %llx %*s %*s %*s %n%s %n",
1001// &text_start_addr,
1002// &text_end_addr,
1003// &bytes_consumed_before_uuid,
1004// uuid_cstr,
1005// &bytes_consumed_after_uuid);
1006//
1007// if (items_parsed == 3)
1008// {
1009//
1010// CrashImageInfo info;
1011// info.text_range.SetBaseAddress(text_start_addr);
1012// info.text_range.SetEndAddress(text_end_addr);
1013//
1014// if (uuid_cstr[0] == '<')
1015// {
1016// if (info.uuid.SetfromCString (&uuid_cstr[1]) == 0)
1017// info.uuid.Clear();
1018//
1019// ::strncpy (image_path, line + bytes_consumed_after_uuid, sizeof(image_path));
1020// }
1021// else
1022// {
1023// ::strncpy (image_path, line + bytes_consumed_before_uuid, sizeof(image_path));
1024// }
1025//
1026// info.path = image_path;
1027//
1028// crash_infos.push_back (info);
1029//
1030// info.uuid.GetAsCString(uuid_cstr, sizeof(uuid_cstr));
1031//
1032// printf("0x%16.16llx - 0x%16.16llx <%s> %s\n",
1033// text_start_addr,
1034// text_end_addr,
1035// uuid_cstr,
1036// image_path);
1037// }
1038// }
1039// }
1040// }
1041// }
1042//
1043// if (crash_infos.size())
1044// {
Greg Clayton63094e02010-06-23 01:19:29 +00001045// SBTarget target (m_debugger.CreateTarget (crash_infos.front().path.c_str(),
Chris Lattner24943d22010-06-08 16:52:24 +00001046// lldb::GetDefaultArchitecture().AsCString (),
1047// false));
1048// if (target.IsValid())
1049// {
1050//
1051// }
1052// }
1053// }
1054//}
1055//
1056
1057void
1058Driver::MasterThreadBytesReceived (void *baton, const void *src, size_t src_len)
1059{
1060 Driver *driver = (Driver*)baton;
1061 driver->GetFromMaster ((const char *)src, src_len);
1062}
1063
1064void
1065Driver::GetFromMaster (const char *src, size_t src_len)
1066{
1067 // Echo the characters back to the Debugger's stdout, that way if you
1068 // type characters while a command is running, you'll see what you've typed.
Greg Clayton63094e02010-06-23 01:19:29 +00001069 FILE *out_fh = m_debugger.GetOutputFileHandle();
Chris Lattner24943d22010-06-08 16:52:24 +00001070 if (out_fh)
1071 ::fwrite (src, 1, src_len, out_fh);
1072}
1073
1074size_t
1075Driver::EditLineInputReaderCallback
1076(
1077 void *baton,
1078 SBInputReader *reader,
1079 InputReaderAction notification,
1080 const char *bytes,
1081 size_t bytes_len
1082)
1083{
1084 Driver *driver = (Driver *)baton;
1085
1086 switch (notification)
1087 {
1088 case eInputReaderActivate:
1089 break;
1090
1091 case eInputReaderReactivate:
1092 driver->ReadyForCommand();
1093 break;
1094
1095 case eInputReaderDeactivate:
1096 break;
1097
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001098 case eInputReaderInterrupt:
1099 if (driver->m_io_channel_ap.get() != NULL)
1100 {
1101 driver->m_io_channel_ap->OutWrite ("^C\n", 3);
1102 driver->m_io_channel_ap->RefreshPrompt();
1103 }
1104 break;
1105
1106 case eInputReaderEndOfFile:
1107 if (driver->m_io_channel_ap.get() != NULL)
1108 {
1109 driver->m_io_channel_ap->OutWrite ("^D\n", 3);
1110 driver->m_io_channel_ap->RefreshPrompt ();
1111 }
1112 write (driver->m_editline_pty.GetMasterFileDescriptor(), "quit\n", 5);
1113 break;
1114
Chris Lattner24943d22010-06-08 16:52:24 +00001115 case eInputReaderGotToken:
1116 write (driver->m_editline_pty.GetMasterFileDescriptor(), bytes, bytes_len);
1117 break;
1118
1119 case eInputReaderDone:
1120 break;
1121 }
1122 return bytes_len;
1123}
1124
1125void
1126Driver::MainLoop ()
1127{
1128 char error_str[1024];
1129 if (m_editline_pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, error_str, sizeof(error_str)) == false)
1130 {
1131 ::fprintf (stderr, "error: failed to open driver pseudo terminal : %s", error_str);
1132 exit(1);
1133 }
1134 else
1135 {
1136 const char *driver_slave_name = m_editline_pty.GetSlaveName (error_str, sizeof(error_str));
1137 if (driver_slave_name == NULL)
1138 {
1139 ::fprintf (stderr, "error: failed to get slave name for driver pseudo terminal : %s", error_str);
1140 exit(2);
1141 }
1142 else
1143 {
1144 m_editline_slave_fh = ::fopen (driver_slave_name, "r+");
1145 if (m_editline_slave_fh == NULL)
1146 {
1147 SBError error;
1148 error.SetErrorToErrno();
1149 ::fprintf (stderr, "error: failed to get open slave for driver pseudo terminal : %s",
1150 error.GetCString());
1151 exit(3);
1152 }
1153
1154 ::setbuf (m_editline_slave_fh, NULL);
1155 }
1156 }
1157
1158
1159 // struct termios stdin_termios;
1160
1161 if (::tcgetattr(STDIN_FILENO, &g_old_stdin_termios) == 0)
1162 atexit (reset_stdin_termios);
1163
1164 ::setbuf (stdin, NULL);
1165 ::setbuf (stdout, NULL);
1166
Greg Clayton63094e02010-06-23 01:19:29 +00001167 m_debugger.SetErrorFileHandle (stderr, false);
1168 m_debugger.SetOutputFileHandle (stdout, false);
1169 m_debugger.SetInputFileHandle (stdin, true);
Jim Ingham74989e82010-08-30 19:44:40 +00001170
1171 m_debugger.SetUseExternalEditor(m_option_data.m_use_external_editor);
Chris Lattner24943d22010-06-08 16:52:24 +00001172
1173 // You have to drain anything that comes to the master side of the PTY. master_out_comm is
1174 // for that purpose. The reason you need to do this is a curious reason... editline will echo
1175 // characters to the PTY when it gets characters while el_gets is not running, and then when
1176 // you call el_gets (or el_getc) it will try to reset the terminal back to raw mode which blocks
1177 // if there are unconsumed characters in the out buffer.
1178 // However, you don't need to do anything with the characters, since editline will dump these
1179 // unconsumed characters after printing the prompt again in el_gets.
1180
1181 SBCommunication master_out_comm("driver.editline");
1182 master_out_comm.AdoptFileDesriptor(m_editline_pty.GetMasterFileDescriptor(), false);
1183 master_out_comm.SetReadThreadBytesReceivedCallback(Driver::MasterThreadBytesReceived, this);
1184
1185 if (master_out_comm.ReadThreadStart () == false)
1186 {
1187 ::fprintf (stderr, "error: failed to start master out read thread");
1188 exit(5);
1189 }
1190
1191// const char *crash_log = GetCrashLogFilename();
1192// if (crash_log)
1193// {
1194// ParseCrashLog (crash_log);
1195// }
1196//
Greg Clayton63094e02010-06-23 01:19:29 +00001197 SBCommandInterpreter sb_interpreter = m_debugger.GetCommandInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001198
1199 m_io_channel_ap.reset (new IOChannel(m_editline_slave_fh, stdout, stderr, this));
1200
1201 struct winsize window_size;
1202 if (isatty (STDIN_FILENO)
1203 && ::ioctl (STDIN_FILENO, TIOCGWINSZ, &window_size) == 0)
1204 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001205 if (window_size.ws_col > 0)
Greg Clayton238c0a12010-09-18 01:14:36 +00001206 m_debugger.SetTerminalWidth (window_size.ws_col);
Chris Lattner24943d22010-06-08 16:52:24 +00001207 }
1208
1209 // Since input can be redirected by the debugger, we must insert our editline
1210 // input reader in the queue so we know when our reader should be active
1211 // and so we can receive bytes only when we are supposed to.
Greg Clayton63094e02010-06-23 01:19:29 +00001212 SBError err (m_editline_reader.Initialize (m_debugger,
1213 Driver::EditLineInputReaderCallback, // callback
Chris Lattner24943d22010-06-08 16:52:24 +00001214 this, // baton
1215 eInputReaderGranularityByte, // token_size
1216 NULL, // end token - NULL means never done
1217 NULL, // prompt - taken care of elsewhere
1218 false)); // echo input - don't need Debugger
1219 // to do this, we handle it elsewhere
1220
1221 if (err.Fail())
1222 {
1223 ::fprintf (stderr, "error: %s", err.GetCString());
1224 exit (6);
1225 }
1226
Greg Clayton63094e02010-06-23 01:19:29 +00001227 m_debugger.PushInputReader (m_editline_reader);
Chris Lattner24943d22010-06-08 16:52:24 +00001228
Greg Clayton63094e02010-06-23 01:19:29 +00001229 SBListener listener(m_debugger.GetListener());
Chris Lattner24943d22010-06-08 16:52:24 +00001230 if (listener.IsValid())
1231 {
1232
1233 listener.StartListeningForEvents (*m_io_channel_ap,
1234 IOChannel::eBroadcastBitHasUserInput |
1235 IOChannel::eBroadcastBitUserInterrupt |
1236 IOChannel::eBroadcastBitThreadShouldExit |
1237 IOChannel::eBroadcastBitThreadDidStart |
1238 IOChannel::eBroadcastBitThreadDidExit);
1239
1240 if (m_io_channel_ap->Start ())
1241 {
1242 bool iochannel_thread_exited = false;
1243
1244 listener.StartListeningForEvents (sb_interpreter.GetBroadcaster(),
1245 SBCommandInterpreter::eBroadcastBitQuitCommandReceived);
1246
1247 // Before we handle any options from the command line, we parse the
1248 // .lldbinit file in the user's home directory.
1249 SBCommandReturnObject result;
1250 sb_interpreter.SourceInitFileInHomeDirectory(result);
1251 if (GetDebugMode())
1252 {
Greg Clayton63094e02010-06-23 01:19:29 +00001253 result.PutError (m_debugger.GetErrorFileHandle());
1254 result.PutOutput (m_debugger.GetOutputFileHandle());
Chris Lattner24943d22010-06-08 16:52:24 +00001255 }
1256
1257 // Now we handle options we got from the command line
1258 char command_string[PATH_MAX * 2];
1259 const size_t num_source_command_files = GetNumSourceCommandFiles();
1260 if (num_source_command_files > 0)
1261 {
1262 for (size_t i=0; i < num_source_command_files; ++i)
1263 {
1264 const char *command_file = GetSourceCommandFileAtIndex(i);
Johnny Chen7c984242010-07-28 21:16:11 +00001265 ::snprintf (command_string, sizeof(command_string), "command source '%s'", command_file);
Greg Clayton63094e02010-06-23 01:19:29 +00001266 m_debugger.GetCommandInterpreter().HandleCommand (command_string, result, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001267 if (GetDebugMode())
1268 {
Greg Clayton63094e02010-06-23 01:19:29 +00001269 result.PutError (m_debugger.GetErrorFileHandle());
1270 result.PutOutput (m_debugger.GetOutputFileHandle());
Chris Lattner24943d22010-06-08 16:52:24 +00001271 }
1272 }
1273 }
1274
1275 if (!m_option_data.m_filename.empty())
1276 {
1277 char arch_name[64];
Greg Clayton63094e02010-06-23 01:19:29 +00001278 if (m_debugger.GetDefaultArchitecture (arch_name, sizeof (arch_name)))
Chris Lattner24943d22010-06-08 16:52:24 +00001279 ::snprintf (command_string, sizeof (command_string), "file --arch=%s '%s'", arch_name,
1280 m_option_data.m_filename.c_str());
1281 else
1282 ::snprintf (command_string, sizeof(command_string), "file '%s'", m_option_data.m_filename.c_str());
1283
Greg Clayton63094e02010-06-23 01:19:29 +00001284 m_debugger.HandleCommand (command_string);
Chris Lattner24943d22010-06-08 16:52:24 +00001285 }
1286
1287 // Now that all option parsing is done, we try and parse the .lldbinit
1288 // file in the current working directory
1289 sb_interpreter.SourceInitFileInCurrentWorkingDirectory (result);
1290 if (GetDebugMode())
1291 {
Greg Clayton63094e02010-06-23 01:19:29 +00001292 result.PutError(m_debugger.GetErrorFileHandle());
1293 result.PutOutput(m_debugger.GetOutputFileHandle());
Chris Lattner24943d22010-06-08 16:52:24 +00001294 }
1295
1296 SBEvent event;
1297
1298 // Make sure the IO channel is started up before we try to tell it we
1299 // are ready for input
1300 listener.WaitForEventForBroadcasterWithType (UINT32_MAX,
1301 *m_io_channel_ap,
1302 IOChannel::eBroadcastBitThreadDidStart,
1303 event);
1304
1305 ReadyForCommand ();
1306
1307 bool done = false;
1308 while (!done)
1309 {
1310 listener.WaitForEvent (UINT32_MAX, event);
1311 if (event.IsValid())
1312 {
1313 if (event.GetBroadcaster().IsValid())
1314 {
1315 uint32_t event_type = event.GetType();
1316 if (event.BroadcasterMatchesRef (*m_io_channel_ap))
1317 {
1318 if ((event_type & IOChannel::eBroadcastBitThreadShouldExit) ||
1319 (event_type & IOChannel::eBroadcastBitThreadDidExit))
1320 {
1321 done = true;
1322 if (event_type & IOChannel::eBroadcastBitThreadDidExit)
1323 iochannel_thread_exited = true;
1324 break;
1325 }
1326 else
1327 done = HandleIOEvent (event);
1328 }
Jim Inghamc8332952010-08-26 21:32:51 +00001329 else if (event.BroadcasterMatchesRef (m_debugger.GetSelectedTarget().GetProcess().GetBroadcaster()))
Chris Lattner24943d22010-06-08 16:52:24 +00001330 {
1331 HandleProcessEvent (event);
1332 }
1333 else if (event.BroadcasterMatchesRef (sb_interpreter.GetBroadcaster()))
1334 {
1335 if (event_type & SBCommandInterpreter::eBroadcastBitQuitCommandReceived)
1336 done = true;
1337 }
1338 }
1339 }
1340 }
1341
1342 reset_stdin_termios ();
1343
1344 CloseIOChannelFile ();
1345
1346 if (!iochannel_thread_exited)
1347 {
Greg Claytonbef15832010-07-14 00:18:15 +00001348 event.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001349 listener.GetNextEventForBroadcasterWithType (*m_io_channel_ap,
1350 IOChannel::eBroadcastBitThreadDidExit,
1351 event);
1352 if (!event.IsValid())
1353 {
1354 // Send end EOF to the driver file descriptor
1355 m_io_channel_ap->Stop();
1356 }
1357 }
1358
Jim Inghamc8332952010-08-26 21:32:51 +00001359 SBProcess process = m_debugger.GetSelectedTarget().GetProcess();
Chris Lattner24943d22010-06-08 16:52:24 +00001360 if (process.IsValid())
1361 process.Destroy();
1362 }
1363 }
1364}
1365
1366
1367void
1368Driver::ReadyForCommand ()
1369{
1370 if (m_waiting_for_command == false)
1371 {
1372 m_waiting_for_command = true;
1373 BroadcastEventByType (Driver::eBroadcastBitReadyForInput, true);
1374 }
1375}
1376
1377
Caroline Ticeb8314fe2010-09-09 17:45:09 +00001378void
1379sigwinch_handler (int signo)
1380{
1381 struct winsize window_size;
1382 if (isatty (STDIN_FILENO)
1383 && ::ioctl (STDIN_FILENO, TIOCGWINSZ, &window_size) == 0)
1384 {
1385 if ((window_size.ws_col > 0) && (strlen (g_debugger_name) > 0))
1386 {
1387 char width_str_buffer[25];
1388 ::sprintf (width_str_buffer, "%d", window_size.ws_col);
1389 SBDebugger::SetInternalVariable ("term-width", width_str_buffer, g_debugger_name);
1390 }
1391 }
1392}
1393
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001394void
1395sigint_handler (int signo)
1396{
1397 static bool g_interrupt_sent = false;
1398 if (g_driver)
1399 {
1400 if (!g_interrupt_sent)
1401 {
1402 g_interrupt_sent = true;
1403 g_driver->GetDebugger().DispatchInputInterrupt();
1404 g_interrupt_sent = false;
1405 return;
1406 }
1407 }
1408
1409 exit (signo);
1410}
1411
Chris Lattner24943d22010-06-08 16:52:24 +00001412int
1413main (int argc, char const *argv[])
1414{
Chris Lattner24943d22010-06-08 16:52:24 +00001415 SBDebugger::Initialize();
1416
Greg Clayton95e33b72010-11-07 21:02:03 +00001417 SBHostOS::ThreadCreated ("<lldb.driver.main-thread>");
Chris Lattner24943d22010-06-08 16:52:24 +00001418
Greg Clayton36f63a92010-10-19 03:25:40 +00001419 signal (SIGPIPE, SIG_IGN);
Caroline Ticeb8314fe2010-09-09 17:45:09 +00001420 signal (SIGWINCH, sigwinch_handler);
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001421 signal (SIGINT, sigint_handler);
Caroline Ticeb8314fe2010-09-09 17:45:09 +00001422
Greg Clayton63094e02010-06-23 01:19:29 +00001423 // Create a scope for driver so that the driver object will destroy itself
1424 // before SBDebugger::Terminate() is called.
Chris Lattner24943d22010-06-08 16:52:24 +00001425 {
Greg Clayton63094e02010-06-23 01:19:29 +00001426 Driver driver;
1427
1428 bool exit = false;
1429 SBError error (driver.ParseArgs (argc, argv, stdout, exit));
1430 if (error.Fail())
1431 {
1432 const char *error_cstr = error.GetCString ();
1433 if (error_cstr)
1434 ::fprintf (stderr, "error: %s\n", error_cstr);
1435 }
1436 else if (!exit)
1437 {
1438 driver.MainLoop ();
1439 }
Chris Lattner24943d22010-06-08 16:52:24 +00001440 }
1441
1442 SBDebugger::Terminate();
1443 return 0;
1444}