blob: 13f7fc6fe3d6a3eeecc1ee2289c82aa1871926f2 [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);
Greg Clayton9caa9462010-10-11 01:13:37 +0000654 exit = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000655 }
656 else if (m_option_data.m_print_version)
657 {
Greg Clayton63094e02010-06-23 01:19:29 +0000658 ::fprintf (out_fh, "%s\n", m_debugger.GetVersionString());
659 exit = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000660 }
661 else if (! m_option_data.m_crash_log.empty())
662 {
663 // Handle crash log stuff here.
664 }
665 else
666 {
667 // All other combinations are valid; do nothing more here.
668 }
669
Greg Clayton63094e02010-06-23 01:19:29 +0000670 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000671}
672
Caroline Tice757500e2010-09-29 18:35:42 +0000673size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000674Driver::GetProcessSTDOUT ()
675{
676 // The process has stuff waiting for stdout; get it and write it out to the appropriate place.
677 char stdio_buffer[1024];
678 size_t len;
Caroline Tice757500e2010-09-29 18:35:42 +0000679 size_t total_bytes = 0;
Jim Inghamc8332952010-08-26 21:32:51 +0000680 while ((len = m_debugger.GetSelectedTarget().GetProcess().GetSTDOUT (stdio_buffer, sizeof (stdio_buffer))) > 0)
Caroline Tice757500e2010-09-29 18:35:42 +0000681 {
Chris Lattner24943d22010-06-08 16:52:24 +0000682 m_io_channel_ap->OutWrite (stdio_buffer, len);
Caroline Tice757500e2010-09-29 18:35:42 +0000683 total_bytes += len;
684 }
685 return total_bytes;
Chris Lattner24943d22010-06-08 16:52:24 +0000686}
687
Caroline Tice757500e2010-09-29 18:35:42 +0000688size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000689Driver::GetProcessSTDERR ()
690{
691 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
692 char stdio_buffer[1024];
693 size_t len;
Caroline Tice757500e2010-09-29 18:35:42 +0000694 size_t total_bytes = 0;
Jim Inghamc8332952010-08-26 21:32:51 +0000695 while ((len = m_debugger.GetSelectedTarget().GetProcess().GetSTDERR (stdio_buffer, sizeof (stdio_buffer))) > 0)
Caroline Tice757500e2010-09-29 18:35:42 +0000696 {
Chris Lattner24943d22010-06-08 16:52:24 +0000697 m_io_channel_ap->ErrWrite (stdio_buffer, len);
Caroline Tice757500e2010-09-29 18:35:42 +0000698 total_bytes += len;
699 }
700 return total_bytes;
Chris Lattner24943d22010-06-08 16:52:24 +0000701}
702
703void
Jim Inghamc8332952010-08-26 21:32:51 +0000704Driver::UpdateSelectedThread ()
Chris Lattner24943d22010-06-08 16:52:24 +0000705{
706 using namespace lldb;
Jim Inghamc8332952010-08-26 21:32:51 +0000707 SBProcess process(m_debugger.GetSelectedTarget().GetProcess());
Chris Lattner24943d22010-06-08 16:52:24 +0000708 if (process.IsValid())
709 {
Jim Inghamc8332952010-08-26 21:32:51 +0000710 SBThread curr_thread (process.GetSelectedThread());
Chris Lattner24943d22010-06-08 16:52:24 +0000711 SBThread thread;
712 StopReason curr_thread_stop_reason = eStopReasonInvalid;
713 curr_thread_stop_reason = curr_thread.GetStopReason();
714
715 if (!curr_thread.IsValid() ||
716 curr_thread_stop_reason == eStopReasonInvalid ||
717 curr_thread_stop_reason == eStopReasonNone)
718 {
719 // Prefer a thread that has just completed its plan over another thread as current thread.
720 SBThread plan_thread;
721 SBThread other_thread;
722 const size_t num_threads = process.GetNumThreads();
723 size_t i;
724 for (i = 0; i < num_threads; ++i)
725 {
726 thread = process.GetThreadAtIndex(i);
727 StopReason thread_stop_reason = thread.GetStopReason();
728 switch (thread_stop_reason)
729 {
730 default:
731 case eStopReasonInvalid:
732 case eStopReasonNone:
733 break;
734
735 case eStopReasonTrace:
736 case eStopReasonBreakpoint:
737 case eStopReasonWatchpoint:
738 case eStopReasonSignal:
739 case eStopReasonException:
740 if (!other_thread.IsValid())
741 other_thread = thread;
742 break;
743 case eStopReasonPlanComplete:
744 if (!plan_thread.IsValid())
745 plan_thread = thread;
746 break;
747 }
748 }
749 if (plan_thread.IsValid())
Jim Inghamc8332952010-08-26 21:32:51 +0000750 process.SetSelectedThread (plan_thread);
Chris Lattner24943d22010-06-08 16:52:24 +0000751 else if (other_thread.IsValid())
Jim Inghamc8332952010-08-26 21:32:51 +0000752 process.SetSelectedThread (other_thread);
Chris Lattner24943d22010-06-08 16:52:24 +0000753 else
754 {
755 if (curr_thread.IsValid())
756 thread = curr_thread;
757 else
758 thread = process.GetThreadAtIndex(0);
759
760 if (thread.IsValid())
Jim Inghamc8332952010-08-26 21:32:51 +0000761 process.SetSelectedThread (thread);
Chris Lattner24943d22010-06-08 16:52:24 +0000762 }
763 }
764 }
765}
766
767
768// This function handles events that were broadcast by the process.
769void
770Driver::HandleProcessEvent (const SBEvent &event)
771{
772 using namespace lldb;
773 const uint32_t event_type = event.GetType();
774
775 if (event_type & SBProcess::eBroadcastBitSTDOUT)
776 {
777 // The process has stdout available, get it and write it out to the
778 // appropriate place.
Caroline Tice757500e2010-09-29 18:35:42 +0000779 if (GetProcessSTDOUT ())
780 m_io_channel_ap->RefreshPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000781 }
782 else if (event_type & SBProcess::eBroadcastBitSTDERR)
783 {
784 // The process has stderr available, get it and write it out to the
785 // appropriate place.
Caroline Tice757500e2010-09-29 18:35:42 +0000786 if (GetProcessSTDERR ())
787 m_io_channel_ap->RefreshPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000788 }
789 else if (event_type & SBProcess::eBroadcastBitStateChanged)
790 {
791 // Drain all stout and stderr so we don't see any output come after
792 // we print our prompts
Caroline Tice757500e2010-09-29 18:35:42 +0000793 if (GetProcessSTDOUT ()
794 || GetProcessSTDERR ())
795 m_io_channel_ap->RefreshPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +0000796
797 // Something changed in the process; get the event and report the process's current status and location to
798 // the user.
799 StateType event_state = SBProcess::GetStateFromEvent (event);
800 if (event_state == eStateInvalid)
801 return;
802
803 SBProcess process (SBProcess::GetProcessFromEvent (event));
804 assert (process.IsValid());
805
806 switch (event_state)
807 {
808 case eStateInvalid:
809 case eStateUnloaded:
810 case eStateAttaching:
811 case eStateLaunching:
812 case eStateStepping:
813 case eStateDetached:
814 {
815 char message[1024];
816 int message_len = ::snprintf (message, sizeof(message), "Process %d %s\n", process.GetProcessID(),
Greg Clayton63094e02010-06-23 01:19:29 +0000817 m_debugger.StateAsCString (event_state));
Chris Lattner24943d22010-06-08 16:52:24 +0000818 m_io_channel_ap->OutWrite(message, message_len);
819 }
820 break;
821
822 case eStateRunning:
823 // Don't be chatty when we run...
824 break;
825
826 case eStateExited:
Caroline Tice757500e2010-09-29 18:35:42 +0000827 {
828 SBCommandReturnObject result;
829 m_debugger.GetCommandInterpreter().HandleCommand("process status", result, false);
830 m_io_channel_ap->ErrWrite (result.GetError(), result.GetErrorSize());
831 m_io_channel_ap->OutWrite (result.GetOutput(), result.GetOutputSize());
832 m_io_channel_ap->RefreshPrompt();
833 }
Chris Lattner24943d22010-06-08 16:52:24 +0000834 break;
835
836 case eStateStopped:
837 case eStateCrashed:
838 case eStateSuspended:
839 // Make sure the program hasn't been auto-restarted:
840 if (SBProcess::GetRestartedFromEvent (event))
841 {
842 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
843 char message[1024];
844 int message_len = ::snprintf (message, sizeof(message), "Process %d stopped and was programmatically restarted.\n",
845 process.GetProcessID());
846 m_io_channel_ap->OutWrite(message, message_len);
Caroline Tice757500e2010-09-29 18:35:42 +0000847 m_io_channel_ap->RefreshPrompt ();
Chris Lattner24943d22010-06-08 16:52:24 +0000848 }
849 else
850 {
Caroline Tice757500e2010-09-29 18:35:42 +0000851 SBCommandReturnObject result;
Jim Inghamc8332952010-08-26 21:32:51 +0000852 UpdateSelectedThread ();
Caroline Tice757500e2010-09-29 18:35:42 +0000853 m_debugger.GetCommandInterpreter().HandleCommand("process status", result, false);
854 m_io_channel_ap->ErrWrite (result.GetError(), result.GetErrorSize());
855 m_io_channel_ap->OutWrite (result.GetOutput(), result.GetOutputSize());
856 m_io_channel_ap->RefreshPrompt ();
Chris Lattner24943d22010-06-08 16:52:24 +0000857 }
858 break;
859 }
860 }
861}
862
863// This function handles events broadcast by the IOChannel (HasInput, UserInterrupt, or ThreadShouldExit).
864
865bool
866Driver::HandleIOEvent (const SBEvent &event)
867{
868 bool quit = false;
869
870 const uint32_t event_type = event.GetType();
871
872 if (event_type & IOChannel::eBroadcastBitHasUserInput)
873 {
874 // We got some input (i.e. a command string) from the user; pass it off to the command interpreter for
875 // handling.
876
877 const char *command_string = SBEvent::GetCStringFromEvent(event);
878 if (command_string == NULL)
Greg Clayton54e7afa2010-07-09 20:39:50 +0000879 command_string = "";
Chris Lattner24943d22010-06-08 16:52:24 +0000880 SBCommandReturnObject result;
Greg Clayton63094e02010-06-23 01:19:29 +0000881 if (m_debugger.GetCommandInterpreter().HandleCommand (command_string, result, true) != lldb::eReturnStatusQuit)
Chris Lattner24943d22010-06-08 16:52:24 +0000882 {
883 m_io_channel_ap->ErrWrite (result.GetError(), result.GetErrorSize());
884 m_io_channel_ap->OutWrite (result.GetOutput(), result.GetOutputSize());
885 }
886 // We are done getting and running our command, we can now clear the
887 // m_waiting_for_command so we can get another one.
888 m_waiting_for_command = false;
889
890 // If our editline input reader is active, it means another input reader
891 // got pushed onto the input reader and caused us to become deactivated.
892 // When the input reader above us gets popped, we will get re-activated
893 // and our prompt will refresh in our callback
894 if (m_editline_reader.IsActive())
895 {
896 ReadyForCommand ();
897 }
898 }
899 else if (event_type & IOChannel::eBroadcastBitUserInterrupt)
900 {
901 // This is here to handle control-c interrupts from the user. It has not yet really been implemented.
902 // TO BE DONE: PROPERLY HANDLE CONTROL-C FROM USER
903 //m_io_channel_ap->CancelInput();
904 // Anything else? Send Interrupt to process?
905 }
906 else if ((event_type & IOChannel::eBroadcastBitThreadShouldExit) ||
907 (event_type & IOChannel::eBroadcastBitThreadDidExit))
908 {
909 // If the IOChannel thread is trying to go away, then it is definitely
910 // time to end the debugging session.
911 quit = true;
912 }
913
914 return quit;
915}
916
917
918//struct CrashImageInfo
919//{
920// std::string path;
921// VMRange text_range;
922// UUID uuid;
923//};
924//
925//void
926//Driver::ParseCrashLog (const char *crash_log)
927//{
928// printf("Parsing crash log: %s\n", crash_log);
929//
930// char image_path[PATH_MAX];
931// std::vector<CrashImageInfo> crash_infos;
932// if (crash_log && crash_log[0])
933// {
934// FileSpec crash_log_file (crash_log);
935// STLStringArray crash_log_lines;
936// if (crash_log_file.ReadFileLines (crash_log_lines))
937// {
938// const size_t num_crash_log_lines = crash_log_lines.size();
939// size_t i;
940// for (i=0; i<num_crash_log_lines; ++i)
941// {
942// const char *line = crash_log_lines[i].c_str();
943// if (strstr (line, "Code Type:"))
944// {
945// char arch_string[256];
946// if (sscanf(line, "%s", arch_string))
947// {
948// if (strcmp(arch_string, "X86-64"))
949// lldb::GetDefaultArchitecture ().SetArch ("x86_64");
950// else if (strcmp(arch_string, "X86"))
951// lldb::GetDefaultArchitecture ().SetArch ("i386");
952// else
953// {
954// ArchSpec arch(arch_string);
955// if (arch.IsValid ())
956// lldb::GetDefaultArchitecture () = arch;
957// else
958// fprintf(stderr, "Unrecognized architecture: %s\n", arch_string);
959// }
960// }
961// }
962// else
963// if (strstr(line, "Path:"))
964// {
965// const char *p = line + strlen("Path:");
966// while (isspace(*p))
967// ++p;
968//
969// m_option_data.m_filename.assign (p);
970// }
971// else
972// if (strstr(line, "Binary Images:"))
973// {
974// while (++i < num_crash_log_lines)
975// {
976// if (crash_log_lines[i].empty())
977// break;
978//
979// line = crash_log_lines[i].c_str();
980// uint64_t text_start_addr;
981// uint64_t text_end_addr;
982// char uuid_cstr[64];
983// int bytes_consumed_before_uuid = 0;
984// int bytes_consumed_after_uuid = 0;
985//
986// int items_parsed = ::sscanf (line,
987// "%llx - %llx %*s %*s %*s %n%s %n",
988// &text_start_addr,
989// &text_end_addr,
990// &bytes_consumed_before_uuid,
991// uuid_cstr,
992// &bytes_consumed_after_uuid);
993//
994// if (items_parsed == 3)
995// {
996//
997// CrashImageInfo info;
998// info.text_range.SetBaseAddress(text_start_addr);
999// info.text_range.SetEndAddress(text_end_addr);
1000//
1001// if (uuid_cstr[0] == '<')
1002// {
1003// if (info.uuid.SetfromCString (&uuid_cstr[1]) == 0)
1004// info.uuid.Clear();
1005//
1006// ::strncpy (image_path, line + bytes_consumed_after_uuid, sizeof(image_path));
1007// }
1008// else
1009// {
1010// ::strncpy (image_path, line + bytes_consumed_before_uuid, sizeof(image_path));
1011// }
1012//
1013// info.path = image_path;
1014//
1015// crash_infos.push_back (info);
1016//
1017// info.uuid.GetAsCString(uuid_cstr, sizeof(uuid_cstr));
1018//
1019// printf("0x%16.16llx - 0x%16.16llx <%s> %s\n",
1020// text_start_addr,
1021// text_end_addr,
1022// uuid_cstr,
1023// image_path);
1024// }
1025// }
1026// }
1027// }
1028// }
1029//
1030// if (crash_infos.size())
1031// {
Greg Clayton63094e02010-06-23 01:19:29 +00001032// SBTarget target (m_debugger.CreateTarget (crash_infos.front().path.c_str(),
Chris Lattner24943d22010-06-08 16:52:24 +00001033// lldb::GetDefaultArchitecture().AsCString (),
1034// false));
1035// if (target.IsValid())
1036// {
1037//
1038// }
1039// }
1040// }
1041//}
1042//
1043
1044void
1045Driver::MasterThreadBytesReceived (void *baton, const void *src, size_t src_len)
1046{
1047 Driver *driver = (Driver*)baton;
1048 driver->GetFromMaster ((const char *)src, src_len);
1049}
1050
1051void
1052Driver::GetFromMaster (const char *src, size_t src_len)
1053{
1054 // Echo the characters back to the Debugger's stdout, that way if you
1055 // type characters while a command is running, you'll see what you've typed.
Greg Clayton63094e02010-06-23 01:19:29 +00001056 FILE *out_fh = m_debugger.GetOutputFileHandle();
Chris Lattner24943d22010-06-08 16:52:24 +00001057 if (out_fh)
1058 ::fwrite (src, 1, src_len, out_fh);
1059}
1060
1061size_t
1062Driver::EditLineInputReaderCallback
1063(
1064 void *baton,
1065 SBInputReader *reader,
1066 InputReaderAction notification,
1067 const char *bytes,
1068 size_t bytes_len
1069)
1070{
1071 Driver *driver = (Driver *)baton;
1072
1073 switch (notification)
1074 {
1075 case eInputReaderActivate:
1076 break;
1077
1078 case eInputReaderReactivate:
1079 driver->ReadyForCommand();
1080 break;
1081
1082 case eInputReaderDeactivate:
1083 break;
1084
1085 case eInputReaderGotToken:
1086 write (driver->m_editline_pty.GetMasterFileDescriptor(), bytes, bytes_len);
1087 break;
1088
1089 case eInputReaderDone:
1090 break;
1091 }
1092 return bytes_len;
1093}
1094
1095void
1096Driver::MainLoop ()
1097{
1098 char error_str[1024];
1099 if (m_editline_pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, error_str, sizeof(error_str)) == false)
1100 {
1101 ::fprintf (stderr, "error: failed to open driver pseudo terminal : %s", error_str);
1102 exit(1);
1103 }
1104 else
1105 {
1106 const char *driver_slave_name = m_editline_pty.GetSlaveName (error_str, sizeof(error_str));
1107 if (driver_slave_name == NULL)
1108 {
1109 ::fprintf (stderr, "error: failed to get slave name for driver pseudo terminal : %s", error_str);
1110 exit(2);
1111 }
1112 else
1113 {
1114 m_editline_slave_fh = ::fopen (driver_slave_name, "r+");
1115 if (m_editline_slave_fh == NULL)
1116 {
1117 SBError error;
1118 error.SetErrorToErrno();
1119 ::fprintf (stderr, "error: failed to get open slave for driver pseudo terminal : %s",
1120 error.GetCString());
1121 exit(3);
1122 }
1123
1124 ::setbuf (m_editline_slave_fh, NULL);
1125 }
1126 }
1127
1128
1129 // struct termios stdin_termios;
1130
1131 if (::tcgetattr(STDIN_FILENO, &g_old_stdin_termios) == 0)
1132 atexit (reset_stdin_termios);
1133
1134 ::setbuf (stdin, NULL);
1135 ::setbuf (stdout, NULL);
1136
Greg Clayton63094e02010-06-23 01:19:29 +00001137 m_debugger.SetErrorFileHandle (stderr, false);
1138 m_debugger.SetOutputFileHandle (stdout, false);
1139 m_debugger.SetInputFileHandle (stdin, true);
Jim Ingham74989e82010-08-30 19:44:40 +00001140
1141 m_debugger.SetUseExternalEditor(m_option_data.m_use_external_editor);
Chris Lattner24943d22010-06-08 16:52:24 +00001142
1143 // You have to drain anything that comes to the master side of the PTY. master_out_comm is
1144 // for that purpose. The reason you need to do this is a curious reason... editline will echo
1145 // characters to the PTY when it gets characters while el_gets is not running, and then when
1146 // you call el_gets (or el_getc) it will try to reset the terminal back to raw mode which blocks
1147 // if there are unconsumed characters in the out buffer.
1148 // However, you don't need to do anything with the characters, since editline will dump these
1149 // unconsumed characters after printing the prompt again in el_gets.
1150
1151 SBCommunication master_out_comm("driver.editline");
1152 master_out_comm.AdoptFileDesriptor(m_editline_pty.GetMasterFileDescriptor(), false);
1153 master_out_comm.SetReadThreadBytesReceivedCallback(Driver::MasterThreadBytesReceived, this);
1154
1155 if (master_out_comm.ReadThreadStart () == false)
1156 {
1157 ::fprintf (stderr, "error: failed to start master out read thread");
1158 exit(5);
1159 }
1160
1161// const char *crash_log = GetCrashLogFilename();
1162// if (crash_log)
1163// {
1164// ParseCrashLog (crash_log);
1165// }
1166//
Greg Clayton63094e02010-06-23 01:19:29 +00001167 SBCommandInterpreter sb_interpreter = m_debugger.GetCommandInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001168
1169 m_io_channel_ap.reset (new IOChannel(m_editline_slave_fh, stdout, stderr, this));
1170
1171 struct winsize window_size;
1172 if (isatty (STDIN_FILENO)
1173 && ::ioctl (STDIN_FILENO, TIOCGWINSZ, &window_size) == 0)
1174 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001175 if (window_size.ws_col > 0)
Greg Clayton238c0a12010-09-18 01:14:36 +00001176 m_debugger.SetTerminalWidth (window_size.ws_col);
Chris Lattner24943d22010-06-08 16:52:24 +00001177 }
1178
1179 // Since input can be redirected by the debugger, we must insert our editline
1180 // input reader in the queue so we know when our reader should be active
1181 // and so we can receive bytes only when we are supposed to.
Greg Clayton63094e02010-06-23 01:19:29 +00001182 SBError err (m_editline_reader.Initialize (m_debugger,
1183 Driver::EditLineInputReaderCallback, // callback
Chris Lattner24943d22010-06-08 16:52:24 +00001184 this, // baton
1185 eInputReaderGranularityByte, // token_size
1186 NULL, // end token - NULL means never done
1187 NULL, // prompt - taken care of elsewhere
1188 false)); // echo input - don't need Debugger
1189 // to do this, we handle it elsewhere
1190
1191 if (err.Fail())
1192 {
1193 ::fprintf (stderr, "error: %s", err.GetCString());
1194 exit (6);
1195 }
1196
Greg Clayton63094e02010-06-23 01:19:29 +00001197 m_debugger.PushInputReader (m_editline_reader);
Chris Lattner24943d22010-06-08 16:52:24 +00001198
Greg Clayton63094e02010-06-23 01:19:29 +00001199 SBListener listener(m_debugger.GetListener());
Chris Lattner24943d22010-06-08 16:52:24 +00001200 if (listener.IsValid())
1201 {
1202
1203 listener.StartListeningForEvents (*m_io_channel_ap,
1204 IOChannel::eBroadcastBitHasUserInput |
1205 IOChannel::eBroadcastBitUserInterrupt |
1206 IOChannel::eBroadcastBitThreadShouldExit |
1207 IOChannel::eBroadcastBitThreadDidStart |
1208 IOChannel::eBroadcastBitThreadDidExit);
1209
1210 if (m_io_channel_ap->Start ())
1211 {
1212 bool iochannel_thread_exited = false;
1213
1214 listener.StartListeningForEvents (sb_interpreter.GetBroadcaster(),
1215 SBCommandInterpreter::eBroadcastBitQuitCommandReceived);
1216
1217 // Before we handle any options from the command line, we parse the
1218 // .lldbinit file in the user's home directory.
1219 SBCommandReturnObject result;
1220 sb_interpreter.SourceInitFileInHomeDirectory(result);
1221 if (GetDebugMode())
1222 {
Greg Clayton63094e02010-06-23 01:19:29 +00001223 result.PutError (m_debugger.GetErrorFileHandle());
1224 result.PutOutput (m_debugger.GetOutputFileHandle());
Chris Lattner24943d22010-06-08 16:52:24 +00001225 }
1226
1227 // Now we handle options we got from the command line
1228 char command_string[PATH_MAX * 2];
1229 const size_t num_source_command_files = GetNumSourceCommandFiles();
1230 if (num_source_command_files > 0)
1231 {
1232 for (size_t i=0; i < num_source_command_files; ++i)
1233 {
1234 const char *command_file = GetSourceCommandFileAtIndex(i);
Johnny Chen7c984242010-07-28 21:16:11 +00001235 ::snprintf (command_string, sizeof(command_string), "command source '%s'", command_file);
Greg Clayton63094e02010-06-23 01:19:29 +00001236 m_debugger.GetCommandInterpreter().HandleCommand (command_string, result, false);
Chris Lattner24943d22010-06-08 16:52:24 +00001237 if (GetDebugMode())
1238 {
Greg Clayton63094e02010-06-23 01:19:29 +00001239 result.PutError (m_debugger.GetErrorFileHandle());
1240 result.PutOutput (m_debugger.GetOutputFileHandle());
Chris Lattner24943d22010-06-08 16:52:24 +00001241 }
1242 }
1243 }
1244
1245 if (!m_option_data.m_filename.empty())
1246 {
1247 char arch_name[64];
Greg Clayton63094e02010-06-23 01:19:29 +00001248 if (m_debugger.GetDefaultArchitecture (arch_name, sizeof (arch_name)))
Chris Lattner24943d22010-06-08 16:52:24 +00001249 ::snprintf (command_string, sizeof (command_string), "file --arch=%s '%s'", arch_name,
1250 m_option_data.m_filename.c_str());
1251 else
1252 ::snprintf (command_string, sizeof(command_string), "file '%s'", m_option_data.m_filename.c_str());
1253
Greg Clayton63094e02010-06-23 01:19:29 +00001254 m_debugger.HandleCommand (command_string);
Chris Lattner24943d22010-06-08 16:52:24 +00001255 }
1256
1257 // Now that all option parsing is done, we try and parse the .lldbinit
1258 // file in the current working directory
1259 sb_interpreter.SourceInitFileInCurrentWorkingDirectory (result);
1260 if (GetDebugMode())
1261 {
Greg Clayton63094e02010-06-23 01:19:29 +00001262 result.PutError(m_debugger.GetErrorFileHandle());
1263 result.PutOutput(m_debugger.GetOutputFileHandle());
Chris Lattner24943d22010-06-08 16:52:24 +00001264 }
1265
1266 SBEvent event;
1267
1268 // Make sure the IO channel is started up before we try to tell it we
1269 // are ready for input
1270 listener.WaitForEventForBroadcasterWithType (UINT32_MAX,
1271 *m_io_channel_ap,
1272 IOChannel::eBroadcastBitThreadDidStart,
1273 event);
1274
1275 ReadyForCommand ();
1276
1277 bool done = false;
1278 while (!done)
1279 {
1280 listener.WaitForEvent (UINT32_MAX, event);
1281 if (event.IsValid())
1282 {
1283 if (event.GetBroadcaster().IsValid())
1284 {
1285 uint32_t event_type = event.GetType();
1286 if (event.BroadcasterMatchesRef (*m_io_channel_ap))
1287 {
1288 if ((event_type & IOChannel::eBroadcastBitThreadShouldExit) ||
1289 (event_type & IOChannel::eBroadcastBitThreadDidExit))
1290 {
1291 done = true;
1292 if (event_type & IOChannel::eBroadcastBitThreadDidExit)
1293 iochannel_thread_exited = true;
1294 break;
1295 }
1296 else
1297 done = HandleIOEvent (event);
1298 }
Jim Inghamc8332952010-08-26 21:32:51 +00001299 else if (event.BroadcasterMatchesRef (m_debugger.GetSelectedTarget().GetProcess().GetBroadcaster()))
Chris Lattner24943d22010-06-08 16:52:24 +00001300 {
1301 HandleProcessEvent (event);
1302 }
1303 else if (event.BroadcasterMatchesRef (sb_interpreter.GetBroadcaster()))
1304 {
1305 if (event_type & SBCommandInterpreter::eBroadcastBitQuitCommandReceived)
1306 done = true;
1307 }
1308 }
1309 }
1310 }
1311
1312 reset_stdin_termios ();
1313
1314 CloseIOChannelFile ();
1315
1316 if (!iochannel_thread_exited)
1317 {
Greg Claytonbef15832010-07-14 00:18:15 +00001318 event.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001319 listener.GetNextEventForBroadcasterWithType (*m_io_channel_ap,
1320 IOChannel::eBroadcastBitThreadDidExit,
1321 event);
1322 if (!event.IsValid())
1323 {
1324 // Send end EOF to the driver file descriptor
1325 m_io_channel_ap->Stop();
1326 }
1327 }
1328
Jim Inghamc8332952010-08-26 21:32:51 +00001329 SBProcess process = m_debugger.GetSelectedTarget().GetProcess();
Chris Lattner24943d22010-06-08 16:52:24 +00001330 if (process.IsValid())
1331 process.Destroy();
1332 }
1333 }
1334}
1335
1336
1337void
1338Driver::ReadyForCommand ()
1339{
1340 if (m_waiting_for_command == false)
1341 {
1342 m_waiting_for_command = true;
1343 BroadcastEventByType (Driver::eBroadcastBitReadyForInput, true);
1344 }
1345}
1346
1347
Caroline Ticeb8314fe2010-09-09 17:45:09 +00001348void
1349sigwinch_handler (int signo)
1350{
1351 struct winsize window_size;
1352 if (isatty (STDIN_FILENO)
1353 && ::ioctl (STDIN_FILENO, TIOCGWINSZ, &window_size) == 0)
1354 {
1355 if ((window_size.ws_col > 0) && (strlen (g_debugger_name) > 0))
1356 {
1357 char width_str_buffer[25];
1358 ::sprintf (width_str_buffer, "%d", window_size.ws_col);
1359 SBDebugger::SetInternalVariable ("term-width", width_str_buffer, g_debugger_name);
1360 }
1361 }
1362}
1363
Chris Lattner24943d22010-06-08 16:52:24 +00001364int
1365main (int argc, char const *argv[])
1366{
Chris Lattner24943d22010-06-08 16:52:24 +00001367 SBDebugger::Initialize();
1368
1369 SBHostOS::ThreadCreated ("[main]");
1370
Caroline Ticeb8314fe2010-09-09 17:45:09 +00001371 signal (SIGWINCH, sigwinch_handler);
1372
Greg Clayton63094e02010-06-23 01:19:29 +00001373 // Create a scope for driver so that the driver object will destroy itself
1374 // before SBDebugger::Terminate() is called.
Chris Lattner24943d22010-06-08 16:52:24 +00001375 {
Greg Clayton63094e02010-06-23 01:19:29 +00001376 Driver driver;
1377
1378 bool exit = false;
1379 SBError error (driver.ParseArgs (argc, argv, stdout, exit));
1380 if (error.Fail())
1381 {
1382 const char *error_cstr = error.GetCString ();
1383 if (error_cstr)
1384 ::fprintf (stderr, "error: %s\n", error_cstr);
1385 }
1386 else if (!exit)
1387 {
1388 driver.MainLoop ();
1389 }
Chris Lattner24943d22010-06-08 16:52:24 +00001390 }
1391
1392 SBDebugger::Terminate();
1393 return 0;
1394}