blob: b3b1081b5c56a79409f2e8b639793d020ccd87da [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 *) "";
43
Chris Lattner24943d22010-06-08 16:52:24 +000044// In the Driver::MainLoop, we change the terminal settings. This function is
45// added as an atexit handler to make sure we clean them up.
46static void
47reset_stdin_termios ()
48{
49 ::tcsetattr (STDIN_FILENO, TCSANOW, &g_old_stdin_termios);
50}
51
52static lldb::OptionDefinition g_options[] =
53{
Caroline Tice4d6675c2010-10-01 19:59:14 +000054 { LLDB_OPT_SET_1, true, "help", 'h', no_argument, NULL, NULL, eArgTypeNone,
Chris Lattner24943d22010-06-08 16:52:24 +000055 "Prints out the usage information for the LLDB debugger." },
56
Caroline Tice4d6675c2010-10-01 19:59:14 +000057 { LLDB_OPT_SET_2, true, "version", 'v', no_argument, NULL, NULL, eArgTypeNone,
Chris Lattner24943d22010-06-08 16:52:24 +000058 "Prints out the current version number of the LLDB debugger." },
59
Caroline Tice4d6675c2010-10-01 19:59:14 +000060 { LLDB_OPT_SET_3, true, "arch", 'a', required_argument, NULL, NULL, eArgTypeArchitecture,
Chris Lattner24943d22010-06-08 16:52:24 +000061 "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." },
62
Caroline Tice4d6675c2010-10-01 19:59:14 +000063 { LLDB_OPT_SET_3 | LLDB_OPT_SET_4, false, "script-language",'l', required_argument, NULL, NULL, eArgTypeScriptLang,
Chris Lattner24943d22010-06-08 16:52:24 +000064 "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." },
65
Caroline Tice4d6675c2010-10-01 19:59:14 +000066 { LLDB_OPT_SET_3 | LLDB_OPT_SET_4, false, "debug", 'd', no_argument, NULL, NULL, eArgTypeNone,
Chris Lattner24943d22010-06-08 16:52:24 +000067 "Tells the debugger to print out extra information for debugging itself." },
68
Caroline Tice4d6675c2010-10-01 19:59:14 +000069 { LLDB_OPT_SET_3 | LLDB_OPT_SET_4, false, "source", 's', required_argument, NULL, NULL, eArgTypeFilename,
Chris Lattner24943d22010-06-08 16:52:24 +000070 "Tells the debugger to read in and execute the file <file>, which should contain lldb commands." },
71
Caroline Tice4d6675c2010-10-01 19:59:14 +000072 { LLDB_OPT_SET_3, true, "file", 'f', required_argument, NULL, NULL, eArgTypeFilename,
Jim Ingham34e9a982010-06-15 18:47:14 +000073 "Tells the debugger to use the file <filename> as the program to be debugged." },
74
Caroline Tice4d6675c2010-10-01 19:59:14 +000075 { LLDB_OPT_SET_ALL, false, "editor", 'e', no_argument, NULL, NULL, eArgTypeNone,
Jim Ingham74989e82010-08-30 19:44:40 +000076 "Tells the debugger to open source files using the host's \"external editor\" mechanism." },
77
Greg Clayton887aa282010-10-11 01:05:37 +000078 { LLDB_OPT_SET_ALL, false, "no-lldbinit", 'n', no_argument, NULL, NULL, eArgTypeNone,
79 "Do not automatically parse any '.lldbinit' files." },
80
Caroline Tice4d6675c2010-10-01 19:59:14 +000081// { LLDB_OPT_SET_4, true, "crash-log", 'c', required_argument, NULL, NULL, eArgTypeFilename,
Greg Clayton12bec712010-06-28 21:30:43 +000082// "Load executable images from a crash log for symbolication." },
Chris Lattner24943d22010-06-08 16:52:24 +000083
Caroline Tice4d6675c2010-10-01 19:59:14 +000084 { 0, false, NULL, 0, 0, NULL, NULL, eArgTypeNone, NULL }
Chris Lattner24943d22010-06-08 16:52:24 +000085};
86
87
88Driver::Driver () :
89 SBBroadcaster ("Driver"),
Greg Clayton63094e02010-06-23 01:19:29 +000090 m_debugger (SBDebugger::Create()),
Chris Lattner24943d22010-06-08 16:52:24 +000091 m_editline_pty (),
92 m_editline_slave_fh (NULL),
93 m_editline_reader (),
94 m_io_channel_ap (),
95 m_option_data (),
96 m_waiting_for_command (false)
97{
Caroline Ticeb8314fe2010-09-09 17:45:09 +000098 g_debugger_name = (char *) m_debugger.GetInstanceName();
99 if (g_debugger_name == NULL)
100 g_debugger_name = (char *) "";
Chris Lattner24943d22010-06-08 16:52:24 +0000101}
102
103Driver::~Driver ()
104{
105}
106
107void
108Driver::CloseIOChannelFile ()
109{
110 // Write and End of File sequence to the file descriptor to ensure any
111 // read functions can exit.
112 char eof_str[] = "\x04";
113 ::write (m_editline_pty.GetMasterFileDescriptor(), eof_str, strlen(eof_str));
114
115 m_editline_pty.CloseMasterFileDescriptor();
116
117 if (m_editline_slave_fh)
118 {
119 ::fclose (m_editline_slave_fh);
120 m_editline_slave_fh = NULL;
121 }
122}
123
Greg Clayton54e7afa2010-07-09 20:39:50 +0000124// This function takes INDENT, which tells how many spaces to output at the front
125// of each line; TEXT, which is the text that is to be output. It outputs the
126// text, on multiple lines if necessary, to RESULT, with INDENT spaces at the
127// front of each line. It breaks lines on spaces, tabs or newlines, shortening
128// the line if necessary to not break in the middle of a word. It assumes that
129// each output line should contain a maximum of OUTPUT_MAX_COLUMNS characters.
Chris Lattner24943d22010-06-08 16:52:24 +0000130
131void
Greg Clayton54e7afa2010-07-09 20:39:50 +0000132OutputFormattedUsageText (FILE *out, int indent, const char *text, int output_max_columns)
Chris Lattner24943d22010-06-08 16:52:24 +0000133{
134 int len = strlen (text);
135 std::string text_string (text);
Chris Lattner24943d22010-06-08 16:52:24 +0000136
137 // Force indentation to be reasonable.
138 if (indent >= output_max_columns)
139 indent = 0;
140
141 // Will it all fit on one line?
142
143 if (len + indent < output_max_columns)
144 // Output as a single line
Greg Clayton54e7afa2010-07-09 20:39:50 +0000145 fprintf (out, "%*s%s\n", indent, "", text);
Chris Lattner24943d22010-06-08 16:52:24 +0000146 else
147 {
148 // We need to break it up into multiple lines.
149 int text_width = output_max_columns - indent - 1;
150 int start = 0;
151 int end = start;
152 int final_end = len;
153 int sub_len;
154
155 while (end < final_end)
156 {
157 // Dont start the 'text' on a space, since we're already outputting the indentation.
158 while ((start < final_end) && (text[start] == ' '))
159 start++;
160
161 end = start + text_width;
162 if (end > final_end)
163 end = final_end;
164 else
165 {
166 // If we're not at the end of the text, make sure we break the line on white space.
167 while (end > start
168 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
169 end--;
170 }
171 sub_len = end - start;
172 std::string substring = text_string.substr (start, sub_len);
Greg Clayton54e7afa2010-07-09 20:39:50 +0000173 fprintf (out, "%*s%s\n", indent, "", substring.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000174 start = end + 1;
175 }
176 }
177}
178
Caroline Tice4d6675c2010-10-01 19:59:14 +0000179void
180GetArgumentName (const CommandArgumentType arg_type, std::string &arg_name)
181{
182 //Fudge this function here, since we can't call the "real" version in lldb_private::CommandObject...
183
184 switch (arg_type)
185 {
186 // Make cases for all the arg_types used in Driver.cpp
187
188 case eArgTypeNone:
189 arg_name = "";
190 break;
191
192 case eArgTypeArchitecture:
193 arg_name = "architecture";
194 break;
195
196 case eArgTypeScriptLang:
197 arg_name = "script-language";
198 break;
199
200 case eArgTypeFilename:
201 arg_name = "filename";
202 break;
203 }
204 return;
205}
206
207
Chris Lattner24943d22010-06-08 16:52:24 +0000208void
209ShowUsage (FILE *out, lldb::OptionDefinition *option_table, Driver::OptionData data)
210{
211 uint32_t screen_width = 80;
212 uint32_t indent_level = 0;
213 const char *name = "lldb";
Jim Ingham34e9a982010-06-15 18:47:14 +0000214
Chris Lattner24943d22010-06-08 16:52:24 +0000215 fprintf (out, "\nUsage:\n\n");
216
217 indent_level += 2;
218
219
220 // First, show each usage level set of options, e.g. <cmd> [options-for-level-0]
221 // <cmd> [options-for-level-1]
222 // etc.
223
Chris Lattner24943d22010-06-08 16:52:24 +0000224 uint32_t num_options;
Jim Ingham34e9a982010-06-15 18:47:14 +0000225 uint32_t num_option_sets = 0;
226
227 for (num_options = 0; option_table[num_options].long_option != NULL; ++num_options)
Chris Lattner24943d22010-06-08 16:52:24 +0000228 {
Jim Ingham34e9a982010-06-15 18:47:14 +0000229 uint32_t this_usage_mask = option_table[num_options].usage_mask;
230 if (this_usage_mask == LLDB_OPT_SET_ALL)
Chris Lattner24943d22010-06-08 16:52:24 +0000231 {
Jim Ingham34e9a982010-06-15 18:47:14 +0000232 if (num_option_sets == 0)
233 num_option_sets = 1;
Chris Lattner24943d22010-06-08 16:52:24 +0000234 }
235 else
236 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000237 for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++)
Jim Ingham34e9a982010-06-15 18:47:14 +0000238 {
239 if (this_usage_mask & 1 << j)
240 {
241 if (num_option_sets <= j)
242 num_option_sets = j + 1;
243 }
244 }
245 }
246 }
247
248 for (uint32_t opt_set = 0; opt_set < num_option_sets; opt_set++)
249 {
250 uint32_t opt_set_mask;
251
252 opt_set_mask = 1 << opt_set;
253
254 if (opt_set > 0)
255 fprintf (out, "\n");
Greg Clayton54e7afa2010-07-09 20:39:50 +0000256 fprintf (out, "%*s%s", indent_level, "", name);
Jim Ingham34e9a982010-06-15 18:47:14 +0000257
258 for (uint32_t i = 0; i < num_options; ++i)
259 {
260 if (option_table[i].usage_mask & opt_set_mask)
261 {
Caroline Tice4d6675c2010-10-01 19:59:14 +0000262 CommandArgumentType arg_type = option_table[i].argument_type;
263 std::string arg_name;
264 GetArgumentName (arg_type, arg_name);
Jim Ingham34e9a982010-06-15 18:47:14 +0000265 if (option_table[i].required)
266 {
267 if (option_table[i].option_has_arg == required_argument)
Caroline Tice4d6675c2010-10-01 19:59:14 +0000268 fprintf (out, " -%c <%s>", option_table[i].short_option, arg_name.c_str());
Jim Ingham34e9a982010-06-15 18:47:14 +0000269 else if (option_table[i].option_has_arg == optional_argument)
Caroline Tice4d6675c2010-10-01 19:59:14 +0000270 fprintf (out, " -%c [<%s>]", option_table[i].short_option, arg_name.c_str());
Jim Ingham34e9a982010-06-15 18:47:14 +0000271 else
272 fprintf (out, " -%c", option_table[i].short_option);
273 }
274 else
275 {
276 if (option_table[i].option_has_arg == required_argument)
Caroline Tice4d6675c2010-10-01 19:59:14 +0000277 fprintf (out, " [-%c <%s>]", option_table[i].short_option, arg_name.c_str());
Jim Ingham34e9a982010-06-15 18:47:14 +0000278 else if (option_table[i].option_has_arg == optional_argument)
Caroline Tice4d6675c2010-10-01 19:59:14 +0000279 fprintf (out, " [-%c [<%s>]]", option_table[i].short_option, arg_name.c_str());
Jim Ingham34e9a982010-06-15 18:47:14 +0000280 else
281 fprintf (out, " [-%c]", option_table[i].short_option);
282 }
283 }
Chris Lattner24943d22010-06-08 16:52:24 +0000284 }
285 }
286
287 fprintf (out, "\n\n");
288
289 // Now print out all the detailed information about the various options: long form, short form and help text:
290 // -- long_name <argument>
291 // - short <argument>
292 // help text
293
294 // This variable is used to keep track of which options' info we've printed out, because some options can be in
295 // more than one usage level, but we only want to print the long form of its information once.
296
297 Driver::OptionData::OptionSet options_seen;
298 Driver::OptionData::OptionSet::iterator pos;
299
300 indent_level += 5;
301
Jim Ingham34e9a982010-06-15 18:47:14 +0000302 for (uint32_t i = 0; i < num_options; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +0000303 {
304 // Only print this option if we haven't already seen it.
305 pos = options_seen.find (option_table[i].short_option);
306 if (pos == options_seen.end())
307 {
Caroline Tice4d6675c2010-10-01 19:59:14 +0000308 CommandArgumentType arg_type = option_table[i].argument_type;
309 std::string arg_name;
310 GetArgumentName (arg_type, arg_name);
311
Chris Lattner24943d22010-06-08 16:52:24 +0000312 options_seen.insert (option_table[i].short_option);
Greg Clayton54e7afa2010-07-09 20:39:50 +0000313 fprintf (out, "%*s-%c ", indent_level, "", option_table[i].short_option);
Caroline Tice4d6675c2010-10-01 19:59:14 +0000314 if (arg_type != eArgTypeNone)
315 fprintf (out, "<%s>", arg_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000316 fprintf (out, "\n");
Greg Clayton54e7afa2010-07-09 20:39:50 +0000317 fprintf (out, "%*s--%s ", indent_level, "", option_table[i].long_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");
321 indent_level += 5;
Greg Clayton54e7afa2010-07-09 20:39:50 +0000322 OutputFormattedUsageText (out, indent_level, option_table[i].usage_text, screen_width);
Chris Lattner24943d22010-06-08 16:52:24 +0000323 indent_level -= 5;
324 fprintf (out, "\n");
325 }
326 }
327
328 indent_level -= 5;
329
Greg Clayton54e7afa2010-07-09 20:39:50 +0000330 fprintf (out, "\n%*s('%s <filename>' also works, to specify the file to be debugged.)\n\n",
331 indent_level, "", name);
Chris Lattner24943d22010-06-08 16:52:24 +0000332}
333
334void
Greg Clayton54e7afa2010-07-09 20:39:50 +0000335BuildGetOptTable (lldb::OptionDefinition *expanded_option_table, struct option **getopt_table, uint32_t num_options)
Chris Lattner24943d22010-06-08 16:52:24 +0000336{
337 if (num_options == 0)
338 return;
339
340 uint32_t i;
341 uint32_t j;
342 std::bitset<256> option_seen;
343
344 for (i = 0, j = 0; i < num_options; ++i)
Greg Clayton54e7afa2010-07-09 20:39:50 +0000345 {
Chris Lattner24943d22010-06-08 16:52:24 +0000346 char short_opt = expanded_option_table[i].short_option;
Greg Clayton54e7afa2010-07-09 20:39:50 +0000347
Chris Lattner24943d22010-06-08 16:52:24 +0000348 if (option_seen.test(short_opt) == false)
Greg Clayton54e7afa2010-07-09 20:39:50 +0000349 {
Chris Lattner24943d22010-06-08 16:52:24 +0000350 (*getopt_table)[j].name = expanded_option_table[i].long_option;
351 (*getopt_table)[j].has_arg = expanded_option_table[i].option_has_arg;
352 (*getopt_table)[j].flag = NULL;
353 (*getopt_table)[j].val = expanded_option_table[i].short_option;
354 option_seen.set(short_opt);
355 ++j;
Greg Clayton54e7afa2010-07-09 20:39:50 +0000356 }
357 }
Chris Lattner24943d22010-06-08 16:52:24 +0000358
359 (*getopt_table)[j].name = NULL;
360 (*getopt_table)[j].has_arg = 0;
361 (*getopt_table)[j].flag = NULL;
362 (*getopt_table)[j].val = 0;
363
364}
365
Greg Clayton63094e02010-06-23 01:19:29 +0000366Driver::OptionData::OptionData () :
367 m_filename(),
368 m_script_lang (lldb::eScriptLanguageDefault),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000369 m_crash_log (),
Greg Clayton63094e02010-06-23 01:19:29 +0000370 m_source_command_files (),
371 m_debug_mode (false),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000372 m_print_version (false),
Greg Clayton63094e02010-06-23 01:19:29 +0000373 m_print_help (false),
Jim Ingham74989e82010-08-30 19:44:40 +0000374 m_seen_options(),
375 m_use_external_editor(false)
Chris Lattner24943d22010-06-08 16:52:24 +0000376{
Greg Clayton63094e02010-06-23 01:19:29 +0000377}
378
379Driver::OptionData::~OptionData ()
380{
381}
382
383void
384Driver::OptionData::Clear ()
385{
386 m_filename.clear ();
387 m_script_lang = lldb::eScriptLanguageDefault;
388 m_source_command_files.clear ();
389 m_debug_mode = false;
390 m_print_help = false;
391 m_print_version = false;
Jim Ingham74989e82010-08-30 19:44:40 +0000392 m_use_external_editor = false;
Greg Clayton63094e02010-06-23 01:19:29 +0000393}
394
395void
396Driver::ResetOptionValues ()
397{
398 m_option_data.Clear ();
399}
400
401const char *
402Driver::GetFilename() const
403{
404 if (m_option_data.m_filename.empty())
405 return NULL;
406 return m_option_data.m_filename.c_str();
407}
408
409const char *
410Driver::GetCrashLogFilename() const
411{
412 if (m_option_data.m_crash_log.empty())
413 return NULL;
414 return m_option_data.m_crash_log.c_str();
415}
416
417lldb::ScriptLanguage
418Driver::GetScriptLanguage() const
419{
420 return m_option_data.m_script_lang;
421}
422
423size_t
424Driver::GetNumSourceCommandFiles () const
425{
426 return m_option_data.m_source_command_files.size();
427}
428
429const char *
430Driver::GetSourceCommandFileAtIndex (uint32_t idx) const
431{
432 if (idx < m_option_data.m_source_command_files.size())
433 return m_option_data.m_source_command_files[idx].c_str();
434 return NULL;
435}
436
437bool
438Driver::GetDebugMode() const
439{
440 return m_option_data.m_debug_mode;
441}
442
443
444// Check the arguments that were passed to this program to make sure they are valid and to get their
445// argument values (if any). Return a boolean value indicating whether or not to start up the full
446// debugger (i.e. the Command Interpreter) or not. Return FALSE if the arguments were invalid OR
447// if the user only wanted help or version information.
448
449SBError
450Driver::ParseArgs (int argc, const char *argv[], FILE *out_fh, bool &exit)
451{
452 ResetOptionValues ();
453
454 SBCommandReturnObject result;
455
Chris Lattner24943d22010-06-08 16:52:24 +0000456 SBError error;
457 std::string option_string;
458 struct option *long_options = NULL;
Greg Clayton54e7afa2010-07-09 20:39:50 +0000459 uint32_t num_options;
Chris Lattner24943d22010-06-08 16:52:24 +0000460
Greg Clayton54e7afa2010-07-09 20:39:50 +0000461 for (num_options = 0; g_options[num_options].long_option != NULL; ++num_options)
462 /* Do Nothing. */;
Chris Lattner24943d22010-06-08 16:52:24 +0000463
464 if (num_options == 0)
465 {
466 if (argc > 1)
467 error.SetErrorStringWithFormat ("invalid number of options");
468 return error;
469 }
470
471 long_options = (struct option *) malloc ((num_options + 1) * sizeof (struct option));
472
473 BuildGetOptTable (g_options, &long_options, num_options);
474
475 if (long_options == NULL)
476 {
477 error.SetErrorStringWithFormat ("invalid long options");
478 return error;
479 }
480
481 // Build the option_string argument for call to getopt_long.
482
483 for (int i = 0; long_options[i].name != NULL; ++i)
484 {
485 if (long_options[i].flag == NULL)
486 {
487 option_string.push_back ((char) long_options[i].val);
488 switch (long_options[i].has_arg)
489 {
490 default:
491 case no_argument:
492 break;
493 case required_argument:
494 option_string.push_back (':');
495 break;
496 case optional_argument:
497 option_string.append ("::");
498 break;
499 }
500 }
501 }
502
503 // Prepare for & make calls to getopt_long.
Eli Friedmanef2bc872010-06-13 19:18:49 +0000504#if __GLIBC__
505 optind = 0;
506#else
Chris Lattner24943d22010-06-08 16:52:24 +0000507 optreset = 1;
508 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +0000509#endif
Chris Lattner24943d22010-06-08 16:52:24 +0000510 int val;
511 while (1)
512 {
513 int long_options_index = -1;
Greg Clayton54e7afa2010-07-09 20:39:50 +0000514 val = ::getopt_long (argc, const_cast<char **>(argv), option_string.c_str(), long_options, &long_options_index);
Chris Lattner24943d22010-06-08 16:52:24 +0000515
516 if (val == -1)
517 break;
518 else if (val == '?')
519 {
Greg Clayton63094e02010-06-23 01:19:29 +0000520 m_option_data.m_print_help = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000521 error.SetErrorStringWithFormat ("unknown or ambiguous option");
522 break;
523 }
524 else if (val == 0)
525 continue;
526 else
527 {
Greg Clayton63094e02010-06-23 01:19:29 +0000528 m_option_data.m_seen_options.insert ((char) val);
Chris Lattner24943d22010-06-08 16:52:24 +0000529 if (long_options_index == -1)
530 {
531 for (int i = 0;
532 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val;
533 ++i)
534 {
535 if (long_options[i].val == val)
536 {
537 long_options_index = i;
538 break;
539 }
540 }
541 }
542
543 if (long_options_index >= 0)
544 {
Greg Clayton63094e02010-06-23 01:19:29 +0000545 const char short_option = (char) g_options[long_options_index].short_option;
546
547 switch (short_option)
548 {
549 case 'h':
550 m_option_data.m_print_help = true;
551 break;
552
553 case 'v':
554 m_option_data.m_print_version = true;
555 break;
556
557 case 'c':
558 m_option_data.m_crash_log = optarg;
559 break;
Greg Clayton887aa282010-10-11 01:05:37 +0000560
Jim Ingham74989e82010-08-30 19:44:40 +0000561 case 'e':
562 m_option_data.m_use_external_editor = true;
563 break;
Greg Clayton887aa282010-10-11 01:05:37 +0000564
565 case 'n':
566 m_debugger.SkipLLDBInitFiles (true);
567 break;
568
Greg Clayton63094e02010-06-23 01:19:29 +0000569 case 'f':
570 {
571 SBFileSpec file(optarg);
572 if (file.Exists())
573 m_option_data.m_filename = optarg;
Caroline Ticeeddffe92010-09-10 04:48:55 +0000574 else if (file.ResolveExecutableLocation())
575 {
576 char path[PATH_MAX];
577 int path_len;
578 file.GetPath (path, path_len);
579 m_option_data.m_filename = path;
580 }
Greg Clayton63094e02010-06-23 01:19:29 +0000581 else
582 error.SetErrorStringWithFormat("file specified in --file (-f) option doesn't exist: '%s'", optarg);
583 }
584 break;
585
586 case 'a':
587 if (!m_debugger.SetDefaultArchitecture (optarg))
588 error.SetErrorStringWithFormat("invalid architecture in the -a or --arch option: '%s'", optarg);
589 break;
590
591 case 'l':
592 m_option_data.m_script_lang = m_debugger.GetScriptingLanguage (optarg);
593 break;
594
595 case 'd':
596 m_option_data.m_debug_mode = true;
597 break;
598
599 case 's':
600 {
601 SBFileSpec file(optarg);
602 if (file.Exists())
603 m_option_data.m_source_command_files.push_back (optarg);
Caroline Ticeeddffe92010-09-10 04:48:55 +0000604 else if (file.ResolveExecutableLocation())
605 {
606 char final_path[PATH_MAX];
607 size_t path_len;
608 file.GetPath (final_path, path_len);
609 std::string path_str (final_path);
610 m_option_data.m_source_command_files.push_back (path_str);
611 }
Greg Clayton63094e02010-06-23 01:19:29 +0000612 else
613 error.SetErrorStringWithFormat("file specified in --source (-s) option doesn't exist: '%s'", optarg);
614 }
615 break;
616
617 default:
618 m_option_data.m_print_help = true;
619 error.SetErrorStringWithFormat ("unrecognized option %c", short_option);
620 break;
621 }
Chris Lattner24943d22010-06-08 16:52:24 +0000622 }
623 else
624 {
625 error.SetErrorStringWithFormat ("invalid option with value %i", val);
626 }
627 if (error.Fail())
Greg Clayton63094e02010-06-23 01:19:29 +0000628 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000629 }
630 }
Jim Ingham34e9a982010-06-15 18:47:14 +0000631
632 // If there is a trailing argument, it is the filename.
633 if (optind == argc - 1)
634 {
635 if (m_option_data.m_filename.empty())
Chris Lattner24943d22010-06-08 16:52:24 +0000636 {
Jim Ingham34e9a982010-06-15 18:47:14 +0000637 m_option_data.m_filename = argv[optind];
Chris Lattner24943d22010-06-08 16:52:24 +0000638 }
Jim Ingham34e9a982010-06-15 18:47:14 +0000639 else
640 {
Greg Clayton63094e02010-06-23 01:19:29 +0000641 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 +0000642 }
643
Chris Lattner24943d22010-06-08 16:52:24 +0000644 }
Jim Ingham34e9a982010-06-15 18:47:14 +0000645 else if (optind < argc - 1)
646 {
647 // Trailing extra arguments...
Greg Clayton63094e02010-06-23 01:19:29 +0000648 error.SetErrorStringWithFormat ("error: trailing extra arguments - only one the filename is allowed.");
Jim Ingham34e9a982010-06-15 18:47:14 +0000649 }
650
Greg Clayton63094e02010-06-23 01:19:29 +0000651 if (error.Fail() || m_option_data.m_print_help)
Chris Lattner24943d22010-06-08 16:52:24 +0000652 {
653 ShowUsage (out_fh, g_options, m_option_data);
Chris Lattner24943d22010-06-08 16:52:24 +0000654 }
655 else if (m_option_data.m_print_version)
656 {
Greg Clayton63094e02010-06-23 01:19:29 +0000657 ::fprintf (out_fh, "%s\n", m_debugger.GetVersionString());
658 exit = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000659 }
660 else if (! m_option_data.m_crash_log.empty())
661 {
662 // Handle crash log stuff here.
663 }
664 else
665 {
666 // All other combinations are valid; do nothing more here.
667 }
668
Greg Clayton63094e02010-06-23 01:19:29 +0000669 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000670}
671
Caroline Tice757500e2010-09-29 18:35:42 +0000672size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000673Driver::GetProcessSTDOUT ()
674{
675 // The process has stuff waiting for stdout; get it and write it out to the appropriate place.
676 char stdio_buffer[1024];
677 size_t len;
Caroline Tice757500e2010-09-29 18:35:42 +0000678 size_t total_bytes = 0;
Jim Inghamc8332952010-08-26 21:32:51 +0000679 while ((len = m_debugger.GetSelectedTarget().GetProcess().GetSTDOUT (stdio_buffer, sizeof (stdio_buffer))) > 0)
Caroline Tice757500e2010-09-29 18:35:42 +0000680 {
Chris Lattner24943d22010-06-08 16:52:24 +0000681 m_io_channel_ap->OutWrite (stdio_buffer, len);
Caroline Tice757500e2010-09-29 18:35:42 +0000682 total_bytes += len;
683 }
684 return total_bytes;
Chris Lattner24943d22010-06-08 16:52:24 +0000685}
686
Caroline Tice757500e2010-09-29 18:35:42 +0000687size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000688Driver::GetProcessSTDERR ()
689{
690 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
691 char stdio_buffer[1024];
692 size_t len;
Caroline Tice757500e2010-09-29 18:35:42 +0000693 size_t total_bytes = 0;
Jim Inghamc8332952010-08-26 21:32:51 +0000694 while ((len = m_debugger.GetSelectedTarget().GetProcess().GetSTDERR (stdio_buffer, sizeof (stdio_buffer))) > 0)
Caroline Tice757500e2010-09-29 18:35:42 +0000695 {
Chris Lattner24943d22010-06-08 16:52:24 +0000696 m_io_channel_ap->ErrWrite (stdio_buffer, len);
Caroline Tice757500e2010-09-29 18:35:42 +0000697 total_bytes += len;
698 }
699 return total_bytes;
Chris Lattner24943d22010-06-08 16:52:24 +0000700}
701
702void
Jim Inghamc8332952010-08-26 21:32:51 +0000703Driver::UpdateSelectedThread ()
Chris Lattner24943d22010-06-08 16:52:24 +0000704{
705 using namespace lldb;
Jim Inghamc8332952010-08-26 21:32:51 +0000706 SBProcess process(m_debugger.GetSelectedTarget().GetProcess());
Chris Lattner24943d22010-06-08 16:52:24 +0000707 if (process.IsValid())
708 {
Jim Inghamc8332952010-08-26 21:32:51 +0000709 SBThread curr_thread (process.GetSelectedThread());
Chris Lattner24943d22010-06-08 16:52:24 +0000710 SBThread thread;
711 StopReason curr_thread_stop_reason = eStopReasonInvalid;
712 curr_thread_stop_reason = curr_thread.GetStopReason();
713
714 if (!curr_thread.IsValid() ||
715 curr_thread_stop_reason == eStopReasonInvalid ||
716 curr_thread_stop_reason == eStopReasonNone)
717 {
718 // Prefer a thread that has just completed its plan over another thread as current thread.
719 SBThread plan_thread;
720 SBThread other_thread;
721 const size_t num_threads = process.GetNumThreads();
722 size_t i;
723 for (i = 0; i < num_threads; ++i)
724 {
725 thread = process.GetThreadAtIndex(i);
726 StopReason thread_stop_reason = thread.GetStopReason();
727 switch (thread_stop_reason)
728 {
729 default:
730 case eStopReasonInvalid:
731 case eStopReasonNone:
732 break;
733
734 case eStopReasonTrace:
735 case eStopReasonBreakpoint:
736 case eStopReasonWatchpoint:
737 case eStopReasonSignal:
738 case eStopReasonException:
739 if (!other_thread.IsValid())
740 other_thread = thread;
741 break;
742 case eStopReasonPlanComplete:
743 if (!plan_thread.IsValid())
744 plan_thread = thread;
745 break;
746 }
747 }
748 if (plan_thread.IsValid())
Jim Inghamc8332952010-08-26 21:32:51 +0000749 process.SetSelectedThread (plan_thread);
Chris Lattner24943d22010-06-08 16:52:24 +0000750 else if (other_thread.IsValid())
Jim Inghamc8332952010-08-26 21:32:51 +0000751 process.SetSelectedThread (other_thread);
Chris Lattner24943d22010-06-08 16:52:24 +0000752 else
753 {
754 if (curr_thread.IsValid())
755 thread = curr_thread;
756 else
757 thread = process.GetThreadAtIndex(0);
758
759 if (thread.IsValid())
Jim Inghamc8332952010-08-26 21:32:51 +0000760 process.SetSelectedThread (thread);
Chris Lattner24943d22010-06-08 16:52:24 +0000761 }
762 }
763 }
764}
765
766
767// This function handles events that were broadcast by the process.
768void
769Driver::HandleProcessEvent (const SBEvent &event)
770{
771 using namespace lldb;
772 const uint32_t event_type = event.GetType();
773
774 if (event_type & SBProcess::eBroadcastBitSTDOUT)
775 {
776 // The process has stdout available, get it and write it out to the
777 // appropriate place.
Caroline Tice757500e2010-09-29 18:35:42 +0000778 if (GetProcessSTDOUT ())
779 m_io_channel_ap->RefreshPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000780 }
781 else if (event_type & SBProcess::eBroadcastBitSTDERR)
782 {
783 // The process has stderr available, get it and write it out to the
784 // appropriate place.
Caroline Tice757500e2010-09-29 18:35:42 +0000785 if (GetProcessSTDERR ())
786 m_io_channel_ap->RefreshPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000787 }
788 else if (event_type & SBProcess::eBroadcastBitStateChanged)
789 {
790 // Drain all stout and stderr so we don't see any output come after
791 // we print our prompts
Caroline Tice757500e2010-09-29 18:35:42 +0000792 if (GetProcessSTDOUT ()
793 || GetProcessSTDERR ())
794 m_io_channel_ap->RefreshPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000795
796 // Something changed in the process; get the event and report the process's current status and location to
797 // the user.
798 StateType event_state = SBProcess::GetStateFromEvent (event);
799 if (event_state == eStateInvalid)
800 return;
801
802 SBProcess process (SBProcess::GetProcessFromEvent (event));
803 assert (process.IsValid());
804
805 switch (event_state)
806 {
807 case eStateInvalid:
808 case eStateUnloaded:
809 case eStateAttaching:
810 case eStateLaunching:
811 case eStateStepping:
812 case eStateDetached:
813 {
814 char message[1024];
815 int message_len = ::snprintf (message, sizeof(message), "Process %d %s\n", process.GetProcessID(),
Greg Clayton63094e02010-06-23 01:19:29 +0000816 m_debugger.StateAsCString (event_state));
Chris Lattner24943d22010-06-08 16:52:24 +0000817 m_io_channel_ap->OutWrite(message, message_len);
818 }
819 break;
820
821 case eStateRunning:
822 // Don't be chatty when we run...
823 break;
824
825 case eStateExited:
Caroline Tice757500e2010-09-29 18:35:42 +0000826 {
827 SBCommandReturnObject result;
828 m_debugger.GetCommandInterpreter().HandleCommand("process status", result, false);
829 m_io_channel_ap->ErrWrite (result.GetError(), result.GetErrorSize());
830 m_io_channel_ap->OutWrite (result.GetOutput(), result.GetOutputSize());
831 m_io_channel_ap->RefreshPrompt();
832 }
Chris Lattner24943d22010-06-08 16:52:24 +0000833 break;
834
835 case eStateStopped:
836 case eStateCrashed:
837 case eStateSuspended:
838 // Make sure the program hasn't been auto-restarted:
839 if (SBProcess::GetRestartedFromEvent (event))
840 {
841 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
842 char message[1024];
843 int message_len = ::snprintf (message, sizeof(message), "Process %d stopped and was programmatically restarted.\n",
844 process.GetProcessID());
845 m_io_channel_ap->OutWrite(message, message_len);
Caroline Tice757500e2010-09-29 18:35:42 +0000846 m_io_channel_ap->RefreshPrompt ();
Chris Lattner24943d22010-06-08 16:52:24 +0000847 }
848 else
849 {
Caroline Tice757500e2010-09-29 18:35:42 +0000850 SBCommandReturnObject result;
Jim Inghamc8332952010-08-26 21:32:51 +0000851 UpdateSelectedThread ();
Caroline Tice757500e2010-09-29 18:35:42 +0000852 m_debugger.GetCommandInterpreter().HandleCommand("process status", result, false);
853 m_io_channel_ap->ErrWrite (result.GetError(), result.GetErrorSize());
854 m_io_channel_ap->OutWrite (result.GetOutput(), result.GetOutputSize());
855 m_io_channel_ap->RefreshPrompt ();
Chris Lattner24943d22010-06-08 16:52:24 +0000856 }
857 break;
858 }
859 }
860}
861
862// This function handles events broadcast by the IOChannel (HasInput, UserInterrupt, or ThreadShouldExit).
863
864bool
865Driver::HandleIOEvent (const SBEvent &event)
866{
867 bool quit = false;
868
869 const uint32_t event_type = event.GetType();
870
871 if (event_type & IOChannel::eBroadcastBitHasUserInput)
872 {
873 // We got some input (i.e. a command string) from the user; pass it off to the command interpreter for
874 // handling.
875
876 const char *command_string = SBEvent::GetCStringFromEvent(event);
877 if (command_string == NULL)
Greg Clayton54e7afa2010-07-09 20:39:50 +0000878 command_string = "";
Chris Lattner24943d22010-06-08 16:52:24 +0000879 SBCommandReturnObject result;
Greg Clayton63094e02010-06-23 01:19:29 +0000880 if (m_debugger.GetCommandInterpreter().HandleCommand (command_string, result, true) != lldb::eReturnStatusQuit)
Chris Lattner24943d22010-06-08 16:52:24 +0000881 {
882 m_io_channel_ap->ErrWrite (result.GetError(), result.GetErrorSize());
883 m_io_channel_ap->OutWrite (result.GetOutput(), result.GetOutputSize());
884 }
885 // We are done getting and running our command, we can now clear the
886 // m_waiting_for_command so we can get another one.
887 m_waiting_for_command = false;
888
889 // If our editline input reader is active, it means another input reader
890 // got pushed onto the input reader and caused us to become deactivated.
891 // When the input reader above us gets popped, we will get re-activated
892 // and our prompt will refresh in our callback
893 if (m_editline_reader.IsActive())
894 {
895 ReadyForCommand ();
896 }
897 }
898 else if (event_type & IOChannel::eBroadcastBitUserInterrupt)
899 {
900 // This is here to handle control-c interrupts from the user. It has not yet really been implemented.
901 // TO BE DONE: PROPERLY HANDLE CONTROL-C FROM USER
902 //m_io_channel_ap->CancelInput();
903 // Anything else? Send Interrupt to process?
904 }
905 else if ((event_type & IOChannel::eBroadcastBitThreadShouldExit) ||
906 (event_type & IOChannel::eBroadcastBitThreadDidExit))
907 {
908 // If the IOChannel thread is trying to go away, then it is definitely
909 // time to end the debugging session.
910 quit = true;
911 }
912
913 return quit;
914}
915
916
917//struct CrashImageInfo
918//{
919// std::string path;
920// VMRange text_range;
921// UUID uuid;
922//};
923//
924//void
925//Driver::ParseCrashLog (const char *crash_log)
926//{
927// printf("Parsing crash log: %s\n", crash_log);
928//
929// char image_path[PATH_MAX];
930// std::vector<CrashImageInfo> crash_infos;
931// if (crash_log && crash_log[0])
932// {
933// FileSpec crash_log_file (crash_log);
934// STLStringArray crash_log_lines;
935// if (crash_log_file.ReadFileLines (crash_log_lines))
936// {
937// const size_t num_crash_log_lines = crash_log_lines.size();
938// size_t i;
939// for (i=0; i<num_crash_log_lines; ++i)
940// {
941// const char *line = crash_log_lines[i].c_str();
942// if (strstr (line, "Code Type:"))
943// {
944// char arch_string[256];
945// if (sscanf(line, "%s", arch_string))
946// {
947// if (strcmp(arch_string, "X86-64"))
948// lldb::GetDefaultArchitecture ().SetArch ("x86_64");
949// else if (strcmp(arch_string, "X86"))
950// lldb::GetDefaultArchitecture ().SetArch ("i386");
951// else
952// {
953// ArchSpec arch(arch_string);
954// if (arch.IsValid ())
955// lldb::GetDefaultArchitecture () = arch;
956// else
957// fprintf(stderr, "Unrecognized architecture: %s\n", arch_string);
958// }
959// }
960// }
961// else
962// if (strstr(line, "Path:"))
963// {
964// const char *p = line + strlen("Path:");
965// while (isspace(*p))
966// ++p;
967//
968// m_option_data.m_filename.assign (p);
969// }
970// else
971// if (strstr(line, "Binary Images:"))
972// {
973// while (++i < num_crash_log_lines)
974// {
975// if (crash_log_lines[i].empty())
976// break;
977//
978// line = crash_log_lines[i].c_str();
979// uint64_t text_start_addr;
980// uint64_t text_end_addr;
981// char uuid_cstr[64];
982// int bytes_consumed_before_uuid = 0;
983// int bytes_consumed_after_uuid = 0;
984//
985// int items_parsed = ::sscanf (line,
986// "%llx - %llx %*s %*s %*s %n%s %n",
987// &text_start_addr,
988// &text_end_addr,
989// &bytes_consumed_before_uuid,
990// uuid_cstr,
991// &bytes_consumed_after_uuid);
992//
993// if (items_parsed == 3)
994// {
995//
996// CrashImageInfo info;
997// info.text_range.SetBaseAddress(text_start_addr);
998// info.text_range.SetEndAddress(text_end_addr);
999//
1000// if (uuid_cstr[0] == '<')
1001// {
1002// if (info.uuid.SetfromCString (&uuid_cstr[1]) == 0)
1003// info.uuid.Clear();
1004//
1005// ::strncpy (image_path, line + bytes_consumed_after_uuid, sizeof(image_path));
1006// }
1007// else
1008// {
1009// ::strncpy (image_path, line + bytes_consumed_before_uuid, sizeof(image_path));
1010// }
1011//
1012// info.path = image_path;
1013//
1014// crash_infos.push_back (info);
1015//
1016// info.uuid.GetAsCString(uuid_cstr, sizeof(uuid_cstr));
1017//
1018// printf("0x%16.16llx - 0x%16.16llx <%s> %s\n",
1019// text_start_addr,
1020// text_end_addr,
1021// uuid_cstr,
1022// image_path);
1023// }
1024// }
1025// }
1026// }
1027// }
1028//
1029// if (crash_infos.size())
1030// {
Greg Clayton63094e02010-06-23 01:19:29 +00001031// SBTarget target (m_debugger.CreateTarget (crash_infos.front().path.c_str(),
Chris Lattner24943d22010-06-08 16:52:24 +00001032// lldb::GetDefaultArchitecture().AsCString (),
1033// false));
1034// if (target.IsValid())
1035// {
1036//
1037// }
1038// }
1039// }
1040//}
1041//
1042
1043void
1044Driver::MasterThreadBytesReceived (void *baton, const void *src, size_t src_len)
1045{
1046 Driver *driver = (Driver*)baton;
1047 driver->GetFromMaster ((const char *)src, src_len);
1048}
1049
1050void
1051Driver::GetFromMaster (const char *src, size_t src_len)
1052{
1053 // Echo the characters back to the Debugger's stdout, that way if you
1054 // type characters while a command is running, you'll see what you've typed.
Greg Clayton63094e02010-06-23 01:19:29 +00001055 FILE *out_fh = m_debugger.GetOutputFileHandle();
Chris Lattner24943d22010-06-08 16:52:24 +00001056 if (out_fh)
1057 ::fwrite (src, 1, src_len, out_fh);
1058}
1059
1060size_t
1061Driver::EditLineInputReaderCallback
1062(
1063 void *baton,
1064 SBInputReader *reader,
1065 InputReaderAction notification,
1066 const char *bytes,
1067 size_t bytes_len
1068)
1069{
1070 Driver *driver = (Driver *)baton;
1071
1072 switch (notification)
1073 {
1074 case eInputReaderActivate:
1075 break;
1076
1077 case eInputReaderReactivate:
1078 driver->ReadyForCommand();
1079 break;
1080
1081 case eInputReaderDeactivate:
1082 break;
1083
1084 case eInputReaderGotToken:
1085 write (driver->m_editline_pty.GetMasterFileDescriptor(), bytes, bytes_len);
1086 break;
1087
1088 case eInputReaderDone:
1089 break;
1090 }
1091 return bytes_len;
1092}
1093
1094void
1095Driver::MainLoop ()
1096{
1097 char error_str[1024];
1098 if (m_editline_pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, error_str, sizeof(error_str)) == false)
1099 {
1100 ::fprintf (stderr, "error: failed to open driver pseudo terminal : %s", error_str);
1101 exit(1);
1102 }
1103 else
1104 {
1105 const char *driver_slave_name = m_editline_pty.GetSlaveName (error_str, sizeof(error_str));
1106 if (driver_slave_name == NULL)
1107 {
1108 ::fprintf (stderr, "error: failed to get slave name for driver pseudo terminal : %s", error_str);
1109 exit(2);
1110 }
1111 else
1112 {
1113 m_editline_slave_fh = ::fopen (driver_slave_name, "r+");
1114 if (m_editline_slave_fh == NULL)
1115 {
1116 SBError error;
1117 error.SetErrorToErrno();
1118 ::fprintf (stderr, "error: failed to get open slave for driver pseudo terminal : %s",
1119 error.GetCString());
1120 exit(3);
1121 }
1122
1123 ::setbuf (m_editline_slave_fh, NULL);
1124 }
1125 }
1126
1127
1128 // struct termios stdin_termios;
1129
1130 if (::tcgetattr(STDIN_FILENO, &g_old_stdin_termios) == 0)
1131 atexit (reset_stdin_termios);
1132
1133 ::setbuf (stdin, NULL);
1134 ::setbuf (stdout, NULL);
1135
Greg Clayton63094e02010-06-23 01:19:29 +00001136 m_debugger.SetErrorFileHandle (stderr, false);
1137 m_debugger.SetOutputFileHandle (stdout, false);
1138 m_debugger.SetInputFileHandle (stdin, true);
Jim Ingham74989e82010-08-30 19:44:40 +00001139
1140 m_debugger.SetUseExternalEditor(m_option_data.m_use_external_editor);
Chris Lattner24943d22010-06-08 16:52:24 +00001141
1142 // You have to drain anything that comes to the master side of the PTY. master_out_comm is
1143 // for that purpose. The reason you need to do this is a curious reason... editline will echo
1144 // characters to the PTY when it gets characters while el_gets is not running, and then when
1145 // you call el_gets (or el_getc) it will try to reset the terminal back to raw mode which blocks
1146 // if there are unconsumed characters in the out buffer.
1147 // However, you don't need to do anything with the characters, since editline will dump these
1148 // unconsumed characters after printing the prompt again in el_gets.
1149
1150 SBCommunication master_out_comm("driver.editline");
1151 master_out_comm.AdoptFileDesriptor(m_editline_pty.GetMasterFileDescriptor(), false);
1152 master_out_comm.SetReadThreadBytesReceivedCallback(Driver::MasterThreadBytesReceived, this);
1153
1154 if (master_out_comm.ReadThreadStart () == false)
1155 {
1156 ::fprintf (stderr, "error: failed to start master out read thread");
1157 exit(5);
1158 }
1159
1160// const char *crash_log = GetCrashLogFilename();
1161// if (crash_log)
1162// {
1163// ParseCrashLog (crash_log);
1164// }
1165//
Greg Clayton63094e02010-06-23 01:19:29 +00001166 SBCommandInterpreter sb_interpreter = m_debugger.GetCommandInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001167
1168 m_io_channel_ap.reset (new IOChannel(m_editline_slave_fh, stdout, stderr, this));
1169
1170 struct winsize window_size;
1171 if (isatty (STDIN_FILENO)
1172 && ::ioctl (STDIN_FILENO, TIOCGWINSZ, &window_size) == 0)
1173 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001174 if (window_size.ws_col > 0)
Greg Clayton238c0a12010-09-18 01:14:36 +00001175 m_debugger.SetTerminalWidth (window_size.ws_col);
Chris Lattner24943d22010-06-08 16:52:24 +00001176 }
1177
1178 // Since input can be redirected by the debugger, we must insert our editline
1179 // input reader in the queue so we know when our reader should be active
1180 // and so we can receive bytes only when we are supposed to.
Greg Clayton63094e02010-06-23 01:19:29 +00001181 SBError err (m_editline_reader.Initialize (m_debugger,
1182 Driver::EditLineInputReaderCallback, // callback
Chris Lattner24943d22010-06-08 16:52:24 +00001183 this, // baton
1184 eInputReaderGranularityByte, // token_size
1185 NULL, // end token - NULL means never done
1186 NULL, // prompt - taken care of elsewhere
1187 false)); // echo input - don't need Debugger
1188 // to do this, we handle it elsewhere
1189
1190 if (err.Fail())
1191 {
1192 ::fprintf (stderr, "error: %s", err.GetCString());
1193 exit (6);
1194 }
1195
Greg Clayton63094e02010-06-23 01:19:29 +00001196 m_debugger.PushInputReader (m_editline_reader);
Chris Lattner24943d22010-06-08 16:52:24 +00001197
Greg Clayton63094e02010-06-23 01:19:29 +00001198 SBListener listener(m_debugger.GetListener());
Chris Lattner24943d22010-06-08 16:52:24 +00001199 if (listener.IsValid())
1200 {
1201
1202 listener.StartListeningForEvents (*m_io_channel_ap,
1203 IOChannel::eBroadcastBitHasUserInput |
1204 IOChannel::eBroadcastBitUserInterrupt |
1205 IOChannel::eBroadcastBitThreadShouldExit |
1206 IOChannel::eBroadcastBitThreadDidStart |
1207 IOChannel::eBroadcastBitThreadDidExit);
1208
1209 if (m_io_channel_ap->Start ())
1210 {
1211 bool iochannel_thread_exited = false;
1212
1213 listener.StartListeningForEvents (sb_interpreter.GetBroadcaster(),
1214 SBCommandInterpreter::eBroadcastBitQuitCommandReceived);
1215
1216 // Before we handle any options from the command line, we parse the
1217 // .lldbinit file in the user's home directory.
1218 SBCommandReturnObject result;
1219 sb_interpreter.SourceInitFileInHomeDirectory(result);
1220 if (GetDebugMode())
1221 {
Greg Clayton63094e02010-06-23 01:19:29 +00001222 result.PutError (m_debugger.GetErrorFileHandle());
1223 result.PutOutput (m_debugger.GetOutputFileHandle());
Chris Lattner24943d22010-06-08 16:52:24 +00001224 }
1225
1226 // Now we handle options we got from the command line
1227 char command_string[PATH_MAX * 2];
1228 const size_t num_source_command_files = GetNumSourceCommandFiles();
1229 if (num_source_command_files > 0)
1230 {
1231 for (size_t i=0; i < num_source_command_files; ++i)
1232 {
1233 const char *command_file = GetSourceCommandFileAtIndex(i);
Johnny Chen7c984242010-07-28 21:16:11 +00001234 ::snprintf (command_string, sizeof(command_string), "command source '%s'", command_file);
Greg Clayton63094e02010-06-23 01:19:29 +00001235 m_debugger.GetCommandInterpreter().HandleCommand (command_string, result, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001236 if (GetDebugMode())
1237 {
Greg Clayton63094e02010-06-23 01:19:29 +00001238 result.PutError (m_debugger.GetErrorFileHandle());
1239 result.PutOutput (m_debugger.GetOutputFileHandle());
Chris Lattner24943d22010-06-08 16:52:24 +00001240 }
1241 }
1242 }
1243
1244 if (!m_option_data.m_filename.empty())
1245 {
1246 char arch_name[64];
Greg Clayton63094e02010-06-23 01:19:29 +00001247 if (m_debugger.GetDefaultArchitecture (arch_name, sizeof (arch_name)))
Chris Lattner24943d22010-06-08 16:52:24 +00001248 ::snprintf (command_string, sizeof (command_string), "file --arch=%s '%s'", arch_name,
1249 m_option_data.m_filename.c_str());
1250 else
1251 ::snprintf (command_string, sizeof(command_string), "file '%s'", m_option_data.m_filename.c_str());
1252
Greg Clayton63094e02010-06-23 01:19:29 +00001253 m_debugger.HandleCommand (command_string);
Chris Lattner24943d22010-06-08 16:52:24 +00001254 }
1255
1256 // Now that all option parsing is done, we try and parse the .lldbinit
1257 // file in the current working directory
1258 sb_interpreter.SourceInitFileInCurrentWorkingDirectory (result);
1259 if (GetDebugMode())
1260 {
Greg Clayton63094e02010-06-23 01:19:29 +00001261 result.PutError(m_debugger.GetErrorFileHandle());
1262 result.PutOutput(m_debugger.GetOutputFileHandle());
Chris Lattner24943d22010-06-08 16:52:24 +00001263 }
1264
1265 SBEvent event;
1266
1267 // Make sure the IO channel is started up before we try to tell it we
1268 // are ready for input
1269 listener.WaitForEventForBroadcasterWithType (UINT32_MAX,
1270 *m_io_channel_ap,
1271 IOChannel::eBroadcastBitThreadDidStart,
1272 event);
1273
1274 ReadyForCommand ();
1275
1276 bool done = false;
1277 while (!done)
1278 {
1279 listener.WaitForEvent (UINT32_MAX, event);
1280 if (event.IsValid())
1281 {
1282 if (event.GetBroadcaster().IsValid())
1283 {
1284 uint32_t event_type = event.GetType();
1285 if (event.BroadcasterMatchesRef (*m_io_channel_ap))
1286 {
1287 if ((event_type & IOChannel::eBroadcastBitThreadShouldExit) ||
1288 (event_type & IOChannel::eBroadcastBitThreadDidExit))
1289 {
1290 done = true;
1291 if (event_type & IOChannel::eBroadcastBitThreadDidExit)
1292 iochannel_thread_exited = true;
1293 break;
1294 }
1295 else
1296 done = HandleIOEvent (event);
1297 }
Jim Inghamc8332952010-08-26 21:32:51 +00001298 else if (event.BroadcasterMatchesRef (m_debugger.GetSelectedTarget().GetProcess().GetBroadcaster()))
Chris Lattner24943d22010-06-08 16:52:24 +00001299 {
1300 HandleProcessEvent (event);
1301 }
1302 else if (event.BroadcasterMatchesRef (sb_interpreter.GetBroadcaster()))
1303 {
1304 if (event_type & SBCommandInterpreter::eBroadcastBitQuitCommandReceived)
1305 done = true;
1306 }
1307 }
1308 }
1309 }
1310
1311 reset_stdin_termios ();
1312
1313 CloseIOChannelFile ();
1314
1315 if (!iochannel_thread_exited)
1316 {
Greg Claytonbef15832010-07-14 00:18:15 +00001317 event.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001318 listener.GetNextEventForBroadcasterWithType (*m_io_channel_ap,
1319 IOChannel::eBroadcastBitThreadDidExit,
1320 event);
1321 if (!event.IsValid())
1322 {
1323 // Send end EOF to the driver file descriptor
1324 m_io_channel_ap->Stop();
1325 }
1326 }
1327
Jim Inghamc8332952010-08-26 21:32:51 +00001328 SBProcess process = m_debugger.GetSelectedTarget().GetProcess();
Chris Lattner24943d22010-06-08 16:52:24 +00001329 if (process.IsValid())
1330 process.Destroy();
1331 }
1332 }
1333}
1334
1335
1336void
1337Driver::ReadyForCommand ()
1338{
1339 if (m_waiting_for_command == false)
1340 {
1341 m_waiting_for_command = true;
1342 BroadcastEventByType (Driver::eBroadcastBitReadyForInput, true);
1343 }
1344}
1345
1346
Caroline Ticeb8314fe2010-09-09 17:45:09 +00001347void
1348sigwinch_handler (int signo)
1349{
1350 struct winsize window_size;
1351 if (isatty (STDIN_FILENO)
1352 && ::ioctl (STDIN_FILENO, TIOCGWINSZ, &window_size) == 0)
1353 {
1354 if ((window_size.ws_col > 0) && (strlen (g_debugger_name) > 0))
1355 {
1356 char width_str_buffer[25];
1357 ::sprintf (width_str_buffer, "%d", window_size.ws_col);
1358 SBDebugger::SetInternalVariable ("term-width", width_str_buffer, g_debugger_name);
1359 }
1360 }
1361}
1362
Chris Lattner24943d22010-06-08 16:52:24 +00001363int
1364main (int argc, char const *argv[])
1365{
Chris Lattner24943d22010-06-08 16:52:24 +00001366 SBDebugger::Initialize();
1367
1368 SBHostOS::ThreadCreated ("[main]");
1369
Caroline Ticeb8314fe2010-09-09 17:45:09 +00001370 signal (SIGWINCH, sigwinch_handler);
1371
Greg Clayton63094e02010-06-23 01:19:29 +00001372 // Create a scope for driver so that the driver object will destroy itself
1373 // before SBDebugger::Terminate() is called.
Chris Lattner24943d22010-06-08 16:52:24 +00001374 {
Greg Clayton63094e02010-06-23 01:19:29 +00001375 Driver driver;
1376
1377 bool exit = false;
1378 SBError error (driver.ParseArgs (argc, argv, stdout, exit));
1379 if (error.Fail())
1380 {
1381 const char *error_cstr = error.GetCString ();
1382 if (error_cstr)
1383 ::fprintf (stderr, "error: %s\n", error_cstr);
1384 }
1385 else if (!exit)
1386 {
1387 driver.MainLoop ();
1388 }
Chris Lattner24943d22010-06-08 16:52:24 +00001389 }
1390
1391 SBDebugger::Terminate();
1392 return 0;
1393}