1 //===-- 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> 17 #include <string.h> 18 #include <stdlib.h> 19 #include <limits.h> 20 #include <fcntl.h> 21 #include <inttypes.h> 22 23 #include <string> 24 25 #include "IOChannel.h" 26 #include "lldb/API/SBBreakpoint.h" 27 #include "lldb/API/SBCommandInterpreter.h" 28 #include "lldb/API/SBCommandReturnObject.h" 29 #include "lldb/API/SBCommunication.h" 30 #include "lldb/API/SBDebugger.h" 31 #include "lldb/API/SBEvent.h" 32 #include "lldb/API/SBHostOS.h" 33 #include "lldb/API/SBListener.h" 34 #include "lldb/API/SBStream.h" 35 #include "lldb/API/SBTarget.h" 36 #include "lldb/API/SBThread.h" 37 #include "lldb/API/SBProcess.h" 38 39 using namespace lldb; 40 41 static void reset_stdin_termios (); 42 static bool g_old_stdin_termios_is_valid = false; 43 static struct termios g_old_stdin_termios; 44 45 static char *g_debugger_name = (char *) ""; 46 static Driver *g_driver = NULL; 47 48 // In the Driver::MainLoop, we change the terminal settings. This function is 49 // added as an atexit handler to make sure we clean them up. 50 static void 51 reset_stdin_termios () 52 { 53 if (g_old_stdin_termios_is_valid) 54 { 55 g_old_stdin_termios_is_valid = false; 56 ::tcsetattr (STDIN_FILENO, TCSANOW, &g_old_stdin_termios); 57 } 58 } 59 60 typedef struct 61 { 62 uint32_t usage_mask; // Used to mark options that can be used together. If (1 << n & usage_mask) != 0 63 // then this option belongs to option set n. 64 bool required; // This option is required (in the current usage level) 65 const char * long_option; // Full name for this option. 66 int short_option; // Single character for this option. 67 int option_has_arg; // no_argument, required_argument or optional_argument 68 uint32_t completion_type; // Cookie the option class can use to do define the argument completion. 69 lldb::CommandArgumentType argument_type; // Type of argument this option takes 70 const char * usage_text; // Full text explaining what this options does and what (if any) argument to 71 // pass it. 72 } OptionDefinition; 73 74 #define LLDB_3_TO_5 LLDB_OPT_SET_3|LLDB_OPT_SET_4|LLDB_OPT_SET_5 75 #define LLDB_4_TO_5 LLDB_OPT_SET_4|LLDB_OPT_SET_5 76 77 static OptionDefinition g_options[] = 78 { 79 { LLDB_OPT_SET_1, true , "help" , 'h', no_argument , 0, eArgTypeNone, 80 "Prints out the usage information for the LLDB debugger." }, 81 { LLDB_OPT_SET_2, true , "version" , 'v', no_argument , 0, eArgTypeNone, 82 "Prints out the current version number of the LLDB debugger." }, 83 { LLDB_OPT_SET_3, true , "arch" , 'a', required_argument, 0, eArgTypeArchitecture, 84 "Tells the debugger to use the specified architecture when starting and running the program. <architecture> must " 85 "be one of the architectures for which the program was compiled." }, 86 { LLDB_OPT_SET_3, true , "file" , 'f', required_argument, 0, eArgTypeFilename, 87 "Tells the debugger to use the file <filename> as the program to be debugged." }, 88 { LLDB_OPT_SET_3, false, "core" , 'c', required_argument, 0, eArgTypeFilename, 89 "Tells the debugger to use the fullpath to <path> as the core file." }, 90 { LLDB_OPT_SET_4, true , "attach-name" , 'n', required_argument, 0, eArgTypeProcessName, 91 "Tells the debugger to attach to a process with the given name." }, 92 { LLDB_OPT_SET_4, true , "wait-for" , 'w', no_argument , 0, eArgTypeNone, 93 "Tells the debugger to wait for a process with the given pid or name to launch before attaching." }, 94 { LLDB_OPT_SET_5, true , "attach-pid" , 'p', required_argument, 0, eArgTypePid, 95 "Tells the debugger to attach to a process with the given pid." }, 96 { LLDB_3_TO_5, false, "script-language", 'l', required_argument, 0, eArgTypeScriptLang, 97 "Tells the debugger to use the specified scripting language for user-defined scripts, rather than the default. " 98 "Valid scripting languages that can be specified include Python, Perl, Ruby and Tcl. Currently only the Python " 99 "extensions have been implemented." }, 100 { LLDB_3_TO_5, false, "debug" , 'd', no_argument , 0, eArgTypeNone, 101 "Tells the debugger to print out extra information for debugging itself." }, 102 { LLDB_3_TO_5, false, "source" , 's', required_argument, 0, eArgTypeFilename, 103 "Tells the debugger to read in and execute the file <file>, which should contain lldb commands." }, 104 { LLDB_3_TO_5, false, "editor" , 'e', no_argument , 0, eArgTypeNone, 105 "Tells the debugger to open source files using the host's \"external editor\" mechanism." }, 106 { LLDB_3_TO_5, false, "no-lldbinit" , 'x', no_argument , 0, eArgTypeNone, 107 "Do not automatically parse any '.lldbinit' files." }, 108 { 0, false, NULL , 0 , 0 , 0, eArgTypeNone, NULL } 109 }; 110 111 static const uint32_t last_option_set_with_args = 2; 112 113 Driver::Driver () : 114 SBBroadcaster ("Driver"), 115 m_debugger (SBDebugger::Create(false)), 116 m_editline_pty (), 117 m_editline_slave_fh (NULL), 118 m_editline_reader (), 119 m_io_channel_ap (), 120 m_option_data (), 121 m_waiting_for_command (false) 122 { 123 // We want to be able to handle CTRL+D in the terminal to have it terminate 124 // certain input 125 m_debugger.SetCloseInputOnEOF (false); 126 g_debugger_name = (char *) m_debugger.GetInstanceName(); 127 if (g_debugger_name == NULL) 128 g_debugger_name = (char *) ""; 129 g_driver = this; 130 } 131 132 Driver::~Driver () 133 { 134 g_driver = NULL; 135 g_debugger_name = NULL; 136 } 137 138 void 139 Driver::CloseIOChannelFile () 140 { 141 // Write an End of File sequence to the file descriptor to ensure any 142 // read functions can exit. 143 char eof_str[] = "\x04"; 144 ::write (m_editline_pty.GetMasterFileDescriptor(), eof_str, strlen(eof_str)); 145 146 m_editline_pty.CloseMasterFileDescriptor(); 147 148 if (m_editline_slave_fh) 149 { 150 ::fclose (m_editline_slave_fh); 151 m_editline_slave_fh = NULL; 152 } 153 } 154 155 // This function takes INDENT, which tells how many spaces to output at the front 156 // of each line; TEXT, which is the text that is to be output. It outputs the 157 // text, on multiple lines if necessary, to RESULT, with INDENT spaces at the 158 // front of each line. It breaks lines on spaces, tabs or newlines, shortening 159 // the line if necessary to not break in the middle of a word. It assumes that 160 // each output line should contain a maximum of OUTPUT_MAX_COLUMNS characters. 161 162 void 163 OutputFormattedUsageText (FILE *out, int indent, const char *text, int output_max_columns) 164 { 165 int len = strlen (text); 166 std::string text_string (text); 167 168 // Force indentation to be reasonable. 169 if (indent >= output_max_columns) 170 indent = 0; 171 172 // Will it all fit on one line? 173 174 if (len + indent < output_max_columns) 175 // Output as a single line 176 fprintf (out, "%*s%s\n", indent, "", text); 177 else 178 { 179 // We need to break it up into multiple lines. 180 int text_width = output_max_columns - indent - 1; 181 int start = 0; 182 int end = start; 183 int final_end = len; 184 int sub_len; 185 186 while (end < final_end) 187 { 188 // Dont start the 'text' on a space, since we're already outputting the indentation. 189 while ((start < final_end) && (text[start] == ' ')) 190 start++; 191 192 end = start + text_width; 193 if (end > final_end) 194 end = final_end; 195 else 196 { 197 // If we're not at the end of the text, make sure we break the line on white space. 198 while (end > start 199 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n') 200 end--; 201 } 202 sub_len = end - start; 203 std::string substring = text_string.substr (start, sub_len); 204 fprintf (out, "%*s%s\n", indent, "", substring.c_str()); 205 start = end + 1; 206 } 207 } 208 } 209 210 void 211 ShowUsage (FILE *out, OptionDefinition *option_table, Driver::OptionData data) 212 { 213 uint32_t screen_width = 80; 214 uint32_t indent_level = 0; 215 const char *name = "lldb"; 216 217 fprintf (out, "\nUsage:\n\n"); 218 219 indent_level += 2; 220 221 222 // First, show each usage level set of options, e.g. <cmd> [options-for-level-0] 223 // <cmd> [options-for-level-1] 224 // etc. 225 226 uint32_t num_options; 227 uint32_t num_option_sets = 0; 228 229 for (num_options = 0; option_table[num_options].long_option != NULL; ++num_options) 230 { 231 uint32_t this_usage_mask = option_table[num_options].usage_mask; 232 if (this_usage_mask == LLDB_OPT_SET_ALL) 233 { 234 if (num_option_sets == 0) 235 num_option_sets = 1; 236 } 237 else 238 { 239 for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++) 240 { 241 if (this_usage_mask & 1 << j) 242 { 243 if (num_option_sets <= j) 244 num_option_sets = j + 1; 245 } 246 } 247 } 248 } 249 250 for (uint32_t opt_set = 0; opt_set < num_option_sets; opt_set++) 251 { 252 uint32_t opt_set_mask; 253 254 opt_set_mask = 1 << opt_set; 255 256 if (opt_set > 0) 257 fprintf (out, "\n"); 258 fprintf (out, "%*s%s", indent_level, "", name); 259 bool is_help_line = false; 260 261 for (uint32_t i = 0; i < num_options; ++i) 262 { 263 if (option_table[i].usage_mask & opt_set_mask) 264 { 265 CommandArgumentType arg_type = option_table[i].argument_type; 266 const char *arg_name = SBCommandInterpreter::GetArgumentTypeAsCString (arg_type); 267 // This is a bit of a hack, but there's no way to say certain options don't have arguments yet... 268 // so we do it by hand here. 269 if (option_table[i].short_option == 'h') 270 is_help_line = true; 271 272 if (option_table[i].required) 273 { 274 if (option_table[i].option_has_arg == required_argument) 275 fprintf (out, " -%c <%s>", option_table[i].short_option, arg_name); 276 else if (option_table[i].option_has_arg == optional_argument) 277 fprintf (out, " -%c [<%s>]", option_table[i].short_option, arg_name); 278 else 279 fprintf (out, " -%c", option_table[i].short_option); 280 } 281 else 282 { 283 if (option_table[i].option_has_arg == required_argument) 284 fprintf (out, " [-%c <%s>]", option_table[i].short_option, arg_name); 285 else if (option_table[i].option_has_arg == optional_argument) 286 fprintf (out, " [-%c [<%s>]]", option_table[i].short_option, arg_name); 287 else 288 fprintf (out, " [-%c]", option_table[i].short_option); 289 } 290 } 291 } 292 if (!is_help_line && (opt_set <= last_option_set_with_args)) 293 fprintf (out, " [[--] <PROGRAM-ARG-1> [<PROGRAM_ARG-2> ...]]"); 294 } 295 296 fprintf (out, "\n\n"); 297 298 // Now print out all the detailed information about the various options: long form, short form and help text: 299 // -- long_name <argument> 300 // - short <argument> 301 // help text 302 303 // This variable is used to keep track of which options' info we've printed out, because some options can be in 304 // more than one usage level, but we only want to print the long form of its information once. 305 306 Driver::OptionData::OptionSet options_seen; 307 Driver::OptionData::OptionSet::iterator pos; 308 309 indent_level += 5; 310 311 for (uint32_t i = 0; i < num_options; ++i) 312 { 313 // Only print this option if we haven't already seen it. 314 pos = options_seen.find (option_table[i].short_option); 315 if (pos == options_seen.end()) 316 { 317 CommandArgumentType arg_type = option_table[i].argument_type; 318 const char *arg_name = SBCommandInterpreter::GetArgumentTypeAsCString (arg_type); 319 320 options_seen.insert (option_table[i].short_option); 321 fprintf (out, "%*s-%c ", indent_level, "", option_table[i].short_option); 322 if (arg_type != eArgTypeNone) 323 fprintf (out, "<%s>", arg_name); 324 fprintf (out, "\n"); 325 fprintf (out, "%*s--%s ", indent_level, "", option_table[i].long_option); 326 if (arg_type != eArgTypeNone) 327 fprintf (out, "<%s>", arg_name); 328 fprintf (out, "\n"); 329 indent_level += 5; 330 OutputFormattedUsageText (out, indent_level, option_table[i].usage_text, screen_width); 331 indent_level -= 5; 332 fprintf (out, "\n"); 333 } 334 } 335 336 indent_level -= 5; 337 338 fprintf (out, "\n%*s(If you don't provide -f then the first argument will be the file to be debugged" 339 "\n%*s so '%s -- <filename> [<ARG1> [<ARG2>]]' also works." 340 "\n%*s Remember to end the options with \"--\" if any of your arguments have a \"-\" in them.)\n\n", 341 indent_level, "", 342 indent_level, "", 343 name, 344 indent_level, ""); 345 } 346 347 void 348 BuildGetOptTable (OptionDefinition *expanded_option_table, std::vector<struct option> &getopt_table, 349 uint32_t num_options) 350 { 351 if (num_options == 0) 352 return; 353 354 uint32_t i; 355 uint32_t j; 356 std::bitset<256> option_seen; 357 358 getopt_table.resize (num_options + 1); 359 360 for (i = 0, j = 0; i < num_options; ++i) 361 { 362 char short_opt = expanded_option_table[i].short_option; 363 364 if (option_seen.test(short_opt) == false) 365 { 366 getopt_table[j].name = expanded_option_table[i].long_option; 367 getopt_table[j].has_arg = expanded_option_table[i].option_has_arg; 368 getopt_table[j].flag = NULL; 369 getopt_table[j].val = expanded_option_table[i].short_option; 370 option_seen.set(short_opt); 371 ++j; 372 } 373 } 374 375 getopt_table[j].name = NULL; 376 getopt_table[j].has_arg = 0; 377 getopt_table[j].flag = NULL; 378 getopt_table[j].val = 0; 379 380 } 381 382 Driver::OptionData::OptionData () : 383 m_args(), 384 m_script_lang (lldb::eScriptLanguageDefault), 385 m_core_file (), 386 m_crash_log (), 387 m_source_command_files (), 388 m_debug_mode (false), 389 m_print_version (false), 390 m_print_help (false), 391 m_wait_for(false), 392 m_process_name(), 393 m_process_pid(LLDB_INVALID_PROCESS_ID), 394 m_use_external_editor(false), 395 m_seen_options() 396 { 397 } 398 399 Driver::OptionData::~OptionData () 400 { 401 } 402 403 void 404 Driver::OptionData::Clear () 405 { 406 m_args.clear (); 407 m_script_lang = lldb::eScriptLanguageDefault; 408 m_source_command_files.clear (); 409 m_debug_mode = false; 410 m_print_help = false; 411 m_print_version = false; 412 m_use_external_editor = false; 413 m_wait_for = false; 414 m_process_name.erase(); 415 m_process_pid = LLDB_INVALID_PROCESS_ID; 416 } 417 418 void 419 Driver::ResetOptionValues () 420 { 421 m_option_data.Clear (); 422 } 423 424 const char * 425 Driver::GetFilename() const 426 { 427 if (m_option_data.m_args.empty()) 428 return NULL; 429 return m_option_data.m_args.front().c_str(); 430 } 431 432 const char * 433 Driver::GetCrashLogFilename() const 434 { 435 if (m_option_data.m_crash_log.empty()) 436 return NULL; 437 return m_option_data.m_crash_log.c_str(); 438 } 439 440 lldb::ScriptLanguage 441 Driver::GetScriptLanguage() const 442 { 443 return m_option_data.m_script_lang; 444 } 445 446 size_t 447 Driver::GetNumSourceCommandFiles () const 448 { 449 return m_option_data.m_source_command_files.size(); 450 } 451 452 const char * 453 Driver::GetSourceCommandFileAtIndex (uint32_t idx) const 454 { 455 if (idx < m_option_data.m_source_command_files.size()) 456 return m_option_data.m_source_command_files[idx].c_str(); 457 return NULL; 458 } 459 460 bool 461 Driver::GetDebugMode() const 462 { 463 return m_option_data.m_debug_mode; 464 } 465 466 467 // Check the arguments that were passed to this program to make sure they are valid and to get their 468 // argument values (if any). Return a boolean value indicating whether or not to start up the full 469 // debugger (i.e. the Command Interpreter) or not. Return FALSE if the arguments were invalid OR 470 // if the user only wanted help or version information. 471 472 SBError 473 Driver::ParseArgs (int argc, const char *argv[], FILE *out_fh, bool &exit) 474 { 475 ResetOptionValues (); 476 477 SBCommandReturnObject result; 478 479 SBError error; 480 std::string option_string; 481 struct option *long_options = NULL; 482 std::vector<struct option> long_options_vector; 483 uint32_t num_options; 484 485 for (num_options = 0; g_options[num_options].long_option != NULL; ++num_options) 486 /* Do Nothing. */; 487 488 if (num_options == 0) 489 { 490 if (argc > 1) 491 error.SetErrorStringWithFormat ("invalid number of options"); 492 return error; 493 } 494 495 BuildGetOptTable (g_options, long_options_vector, num_options); 496 497 if (long_options_vector.empty()) 498 long_options = NULL; 499 else 500 long_options = &long_options_vector.front(); 501 502 if (long_options == NULL) 503 { 504 error.SetErrorStringWithFormat ("invalid long options"); 505 return error; 506 } 507 508 // Build the option_string argument for call to getopt_long. 509 510 for (int i = 0; long_options[i].name != NULL; ++i) 511 { 512 if (long_options[i].flag == NULL) 513 { 514 option_string.push_back ((char) long_options[i].val); 515 switch (long_options[i].has_arg) 516 { 517 default: 518 case no_argument: 519 break; 520 case required_argument: 521 option_string.push_back (':'); 522 break; 523 case optional_argument: 524 option_string.append ("::"); 525 break; 526 } 527 } 528 } 529 530 // This is kind of a pain, but since we make the debugger in the Driver's constructor, we can't 531 // know at that point whether we should read in init files yet. So we don't read them in in the 532 // Driver constructor, then set the flags back to "read them in" here, and then if we see the 533 // "-n" flag, we'll turn it off again. Finally we have to read them in by hand later in the 534 // main loop. 535 536 m_debugger.SkipLLDBInitFiles (false); 537 m_debugger.SkipAppInitFiles (false); 538 539 // Prepare for & make calls to getopt_long. 540 #if __GLIBC__ 541 optind = 0; 542 #else 543 optreset = 1; 544 optind = 1; 545 #endif 546 int val; 547 while (1) 548 { 549 int long_options_index = -1; 550 val = ::getopt_long (argc, const_cast<char **>(argv), option_string.c_str(), long_options, &long_options_index); 551 552 if (val == -1) 553 break; 554 else if (val == '?') 555 { 556 m_option_data.m_print_help = true; 557 error.SetErrorStringWithFormat ("unknown or ambiguous option"); 558 break; 559 } 560 else if (val == 0) 561 continue; 562 else 563 { 564 m_option_data.m_seen_options.insert ((char) val); 565 if (long_options_index == -1) 566 { 567 for (int i = 0; 568 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val; 569 ++i) 570 { 571 if (long_options[i].val == val) 572 { 573 long_options_index = i; 574 break; 575 } 576 } 577 } 578 579 if (long_options_index >= 0) 580 { 581 const int short_option = g_options[long_options_index].short_option; 582 583 switch (short_option) 584 { 585 case 'h': 586 m_option_data.m_print_help = true; 587 break; 588 589 case 'v': 590 m_option_data.m_print_version = true; 591 break; 592 593 case 'c': 594 { 595 SBFileSpec file(optarg); 596 if (file.Exists()) 597 { 598 m_option_data.m_core_file = optarg; 599 } 600 else 601 error.SetErrorStringWithFormat("file specified in --core (-c) option doesn't exist: '%s'", optarg); 602 } 603 break; 604 605 case 'e': 606 m_option_data.m_use_external_editor = true; 607 break; 608 609 case 'x': 610 m_debugger.SkipLLDBInitFiles (true); 611 m_debugger.SkipAppInitFiles (true); 612 break; 613 614 case 'f': 615 { 616 SBFileSpec file(optarg); 617 if (file.Exists()) 618 { 619 m_option_data.m_args.push_back (optarg); 620 } 621 else if (file.ResolveExecutableLocation()) 622 { 623 char path[PATH_MAX]; 624 file.GetPath (path, sizeof(path)); 625 m_option_data.m_args.push_back (path); 626 } 627 else 628 error.SetErrorStringWithFormat("file specified in --file (-f) option doesn't exist: '%s'", optarg); 629 } 630 break; 631 632 case 'a': 633 if (!m_debugger.SetDefaultArchitecture (optarg)) 634 error.SetErrorStringWithFormat("invalid architecture in the -a or --arch option: '%s'", optarg); 635 break; 636 637 case 'l': 638 m_option_data.m_script_lang = m_debugger.GetScriptingLanguage (optarg); 639 break; 640 641 case 'd': 642 m_option_data.m_debug_mode = true; 643 break; 644 645 case 'n': 646 m_option_data.m_process_name = optarg; 647 break; 648 649 case 'w': 650 m_option_data.m_wait_for = true; 651 break; 652 653 case 'p': 654 { 655 char *remainder; 656 m_option_data.m_process_pid = strtol (optarg, &remainder, 0); 657 if (remainder == optarg || *remainder != '\0') 658 error.SetErrorStringWithFormat ("Could not convert process PID: \"%s\" into a pid.", 659 optarg); 660 } 661 break; 662 case 's': 663 { 664 SBFileSpec file(optarg); 665 if (file.Exists()) 666 m_option_data.m_source_command_files.push_back (optarg); 667 else if (file.ResolveExecutableLocation()) 668 { 669 char final_path[PATH_MAX]; 670 file.GetPath (final_path, sizeof(final_path)); 671 std::string path_str (final_path); 672 m_option_data.m_source_command_files.push_back (path_str); 673 } 674 else 675 error.SetErrorStringWithFormat("file specified in --source (-s) option doesn't exist: '%s'", optarg); 676 } 677 break; 678 679 default: 680 m_option_data.m_print_help = true; 681 error.SetErrorStringWithFormat ("unrecognized option %c", short_option); 682 break; 683 } 684 } 685 else 686 { 687 error.SetErrorStringWithFormat ("invalid option with value %i", val); 688 } 689 if (error.Fail()) 690 { 691 return error; 692 } 693 } 694 } 695 696 if (error.Fail() || m_option_data.m_print_help) 697 { 698 ShowUsage (out_fh, g_options, m_option_data); 699 exit = true; 700 } 701 else if (m_option_data.m_print_version) 702 { 703 ::fprintf (out_fh, "%s\n", m_debugger.GetVersionString()); 704 exit = true; 705 } 706 else if (m_option_data.m_process_name.empty() && m_option_data.m_process_pid == LLDB_INVALID_PROCESS_ID) 707 { 708 // Any arguments that are left over after option parsing are for 709 // the program. If a file was specified with -f then the filename 710 // is already in the m_option_data.m_args array, and any remaining args 711 // are arguments for the inferior program. If no file was specified with 712 // -f, then what is left is the program name followed by any arguments. 713 714 // Skip any options we consumed with getopt_long 715 argc -= optind; 716 argv += optind; 717 718 if (argc > 0) 719 { 720 for (int arg_idx=0; arg_idx<argc; ++arg_idx) 721 { 722 const char *arg = argv[arg_idx]; 723 if (arg) 724 m_option_data.m_args.push_back (arg); 725 } 726 } 727 728 } 729 else 730 { 731 // Skip any options we consumed with getopt_long 732 argc -= optind; 733 //argv += optind; // Commented out to keep static analyzer happy 734 735 if (argc > 0) 736 ::fprintf (out_fh, "Warning: program arguments are ignored when attaching.\n"); 737 } 738 739 return error; 740 } 741 742 size_t 743 Driver::GetProcessSTDOUT () 744 { 745 // The process has stuff waiting for stdout; get it and write it out to the appropriate place. 746 char stdio_buffer[1024]; 747 size_t len; 748 size_t total_bytes = 0; 749 while ((len = m_debugger.GetSelectedTarget().GetProcess().GetSTDOUT (stdio_buffer, sizeof (stdio_buffer))) > 0) 750 { 751 m_io_channel_ap->OutWrite (stdio_buffer, len, ASYNC); 752 total_bytes += len; 753 } 754 return total_bytes; 755 } 756 757 size_t 758 Driver::GetProcessSTDERR () 759 { 760 // The process has stuff waiting for stderr; get it and write it out to the appropriate place. 761 char stdio_buffer[1024]; 762 size_t len; 763 size_t total_bytes = 0; 764 while ((len = m_debugger.GetSelectedTarget().GetProcess().GetSTDERR (stdio_buffer, sizeof (stdio_buffer))) > 0) 765 { 766 m_io_channel_ap->ErrWrite (stdio_buffer, len, ASYNC); 767 total_bytes += len; 768 } 769 return total_bytes; 770 } 771 772 void 773 Driver::UpdateSelectedThread () 774 { 775 using namespace lldb; 776 SBProcess process(m_debugger.GetSelectedTarget().GetProcess()); 777 if (process.IsValid()) 778 { 779 SBThread curr_thread (process.GetSelectedThread()); 780 SBThread thread; 781 StopReason curr_thread_stop_reason = eStopReasonInvalid; 782 curr_thread_stop_reason = curr_thread.GetStopReason(); 783 784 if (!curr_thread.IsValid() || 785 curr_thread_stop_reason == eStopReasonInvalid || 786 curr_thread_stop_reason == eStopReasonNone) 787 { 788 // Prefer a thread that has just completed its plan over another thread as current thread. 789 SBThread plan_thread; 790 SBThread other_thread; 791 const size_t num_threads = process.GetNumThreads(); 792 size_t i; 793 for (i = 0; i < num_threads; ++i) 794 { 795 thread = process.GetThreadAtIndex(i); 796 StopReason thread_stop_reason = thread.GetStopReason(); 797 switch (thread_stop_reason) 798 { 799 default: 800 case eStopReasonInvalid: 801 case eStopReasonNone: 802 break; 803 804 case eStopReasonTrace: 805 case eStopReasonBreakpoint: 806 case eStopReasonWatchpoint: 807 case eStopReasonSignal: 808 case eStopReasonException: 809 case eStopReasonExec: 810 if (!other_thread.IsValid()) 811 other_thread = thread; 812 break; 813 case eStopReasonPlanComplete: 814 if (!plan_thread.IsValid()) 815 plan_thread = thread; 816 break; 817 } 818 } 819 if (plan_thread.IsValid()) 820 process.SetSelectedThread (plan_thread); 821 else if (other_thread.IsValid()) 822 process.SetSelectedThread (other_thread); 823 else 824 { 825 if (curr_thread.IsValid()) 826 thread = curr_thread; 827 else 828 thread = process.GetThreadAtIndex(0); 829 830 if (thread.IsValid()) 831 process.SetSelectedThread (thread); 832 } 833 } 834 } 835 } 836 837 // This function handles events that were broadcast by the process. 838 void 839 Driver::HandleBreakpointEvent (const SBEvent &event) 840 { 841 using namespace lldb; 842 const uint32_t event_type = SBBreakpoint::GetBreakpointEventTypeFromEvent (event); 843 844 if (event_type & eBreakpointEventTypeAdded 845 || event_type & eBreakpointEventTypeRemoved 846 || event_type & eBreakpointEventTypeEnabled 847 || event_type & eBreakpointEventTypeDisabled 848 || event_type & eBreakpointEventTypeCommandChanged 849 || event_type & eBreakpointEventTypeConditionChanged 850 || event_type & eBreakpointEventTypeIgnoreChanged 851 || event_type & eBreakpointEventTypeLocationsResolved) 852 { 853 // Don't do anything about these events, since the breakpoint commands already echo these actions. 854 } 855 else if (event_type & eBreakpointEventTypeLocationsAdded) 856 { 857 char message[256]; 858 uint32_t num_new_locations = SBBreakpoint::GetNumBreakpointLocationsFromEvent(event); 859 if (num_new_locations > 0) 860 { 861 SBBreakpoint breakpoint = SBBreakpoint::GetBreakpointFromEvent(event); 862 int message_len = ::snprintf (message, sizeof(message), "%d location%s added to breakpoint %d\n", 863 num_new_locations, 864 num_new_locations == 1 ? "" : "s", 865 breakpoint.GetID()); 866 m_io_channel_ap->OutWrite(message, message_len, ASYNC); 867 } 868 } 869 else if (event_type & eBreakpointEventTypeLocationsRemoved) 870 { 871 // These locations just get disabled, not sure it is worth spamming folks about this on the command line. 872 } 873 else if (event_type & eBreakpointEventTypeLocationsResolved) 874 { 875 // This might be an interesting thing to note, but I'm going to leave it quiet for now, it just looked noisy. 876 } 877 } 878 879 // This function handles events that were broadcast by the process. 880 void 881 Driver::HandleProcessEvent (const SBEvent &event) 882 { 883 using namespace lldb; 884 const uint32_t event_type = event.GetType(); 885 886 if (event_type & SBProcess::eBroadcastBitSTDOUT) 887 { 888 // The process has stdout available, get it and write it out to the 889 // appropriate place. 890 GetProcessSTDOUT (); 891 } 892 else if (event_type & SBProcess::eBroadcastBitSTDERR) 893 { 894 // The process has stderr available, get it and write it out to the 895 // appropriate place. 896 GetProcessSTDERR (); 897 } 898 else if (event_type & SBProcess::eBroadcastBitStateChanged) 899 { 900 // Drain all stout and stderr so we don't see any output come after 901 // we print our prompts 902 GetProcessSTDOUT (); 903 GetProcessSTDERR (); 904 // Something changed in the process; get the event and report the process's current status and location to 905 // the user. 906 StateType event_state = SBProcess::GetStateFromEvent (event); 907 if (event_state == eStateInvalid) 908 return; 909 910 SBProcess process (SBProcess::GetProcessFromEvent (event)); 911 assert (process.IsValid()); 912 913 switch (event_state) 914 { 915 case eStateInvalid: 916 case eStateUnloaded: 917 case eStateConnected: 918 case eStateAttaching: 919 case eStateLaunching: 920 case eStateStepping: 921 case eStateDetached: 922 { 923 char message[1024]; 924 int message_len = ::snprintf (message, sizeof(message), "Process %" PRIu64 " %s\n", process.GetProcessID(), 925 m_debugger.StateAsCString (event_state)); 926 m_io_channel_ap->OutWrite(message, message_len, ASYNC); 927 } 928 break; 929 930 case eStateRunning: 931 // Don't be chatty when we run... 932 break; 933 934 case eStateExited: 935 { 936 SBCommandReturnObject result; 937 m_debugger.GetCommandInterpreter().HandleCommand("process status", result, false); 938 m_io_channel_ap->ErrWrite (result.GetError(), result.GetErrorSize(), ASYNC); 939 m_io_channel_ap->OutWrite (result.GetOutput(), result.GetOutputSize(), ASYNC); 940 } 941 break; 942 943 case eStateStopped: 944 case eStateCrashed: 945 case eStateSuspended: 946 // Make sure the program hasn't been auto-restarted: 947 if (SBProcess::GetRestartedFromEvent (event)) 948 { 949 // FIXME: Do we want to report this, or would that just be annoyingly chatty? 950 char message[1024]; 951 int message_len = ::snprintf (message, sizeof(message), "Process %" PRIu64 " stopped and was programmatically restarted.\n", 952 process.GetProcessID()); 953 m_io_channel_ap->OutWrite(message, message_len, ASYNC); 954 } 955 else 956 { 957 if (GetDebugger().GetSelectedTarget() == process.GetTarget()) 958 { 959 SBCommandReturnObject result; 960 UpdateSelectedThread (); 961 m_debugger.GetCommandInterpreter().HandleCommand("process status", result, false); 962 m_io_channel_ap->ErrWrite (result.GetError(), result.GetErrorSize(), ASYNC); 963 m_io_channel_ap->OutWrite (result.GetOutput(), result.GetOutputSize(), ASYNC); 964 } 965 else 966 { 967 SBStream out_stream; 968 uint32_t target_idx = GetDebugger().GetIndexOfTarget(process.GetTarget()); 969 if (target_idx != UINT32_MAX) 970 out_stream.Printf ("Target %d: (", target_idx); 971 else 972 out_stream.Printf ("Target <unknown index>: ("); 973 process.GetTarget().GetDescription (out_stream, eDescriptionLevelBrief); 974 out_stream.Printf (") stopped.\n"); 975 m_io_channel_ap->OutWrite (out_stream.GetData(), out_stream.GetSize(), ASYNC); 976 } 977 } 978 break; 979 } 980 } 981 } 982 983 void 984 Driver::HandleThreadEvent (const SBEvent &event) 985 { 986 // At present the only thread event we handle is the Frame Changed event, and all we do for that is just 987 // reprint the thread status for that thread. 988 using namespace lldb; 989 const uint32_t event_type = event.GetType(); 990 if (event_type == SBThread::eBroadcastBitStackChanged) 991 { 992 SBThread thread = SBThread::GetThreadFromEvent (event); 993 if (thread.IsValid()) 994 { 995 SBStream out_stream; 996 thread.GetStatus(out_stream); 997 m_io_channel_ap->OutWrite (out_stream.GetData (), out_stream.GetSize (), ASYNC); 998 } 999 } 1000 } 1001 1002 // This function handles events broadcast by the IOChannel (HasInput, UserInterrupt, or ThreadShouldExit). 1003 1004 bool 1005 Driver::HandleIOEvent (const SBEvent &event) 1006 { 1007 bool quit = false; 1008 1009 const uint32_t event_type = event.GetType(); 1010 1011 if (event_type & IOChannel::eBroadcastBitHasUserInput) 1012 { 1013 // We got some input (i.e. a command string) from the user; pass it off to the command interpreter for 1014 // handling. 1015 1016 const char *command_string = SBEvent::GetCStringFromEvent(event); 1017 if (command_string == NULL) 1018 command_string = ""; 1019 SBCommandReturnObject result; 1020 1021 // We don't want the result to bypass the OutWrite function in IOChannel, as this can result in odd 1022 // output orderings and problems with the prompt. 1023 m_debugger.GetCommandInterpreter().HandleCommand (command_string, result, true); 1024 1025 const bool only_if_no_immediate = true; 1026 1027 const size_t output_size = result.GetOutputSize(); 1028 1029 if (output_size > 0) 1030 m_io_channel_ap->OutWrite (result.GetOutput(only_if_no_immediate), output_size, NO_ASYNC); 1031 1032 const size_t error_size = result.GetErrorSize(); 1033 1034 if (error_size > 0) 1035 m_io_channel_ap->OutWrite (result.GetError(only_if_no_immediate), error_size, NO_ASYNC); 1036 1037 // We are done getting and running our command, we can now clear the 1038 // m_waiting_for_command so we can get another one. 1039 m_waiting_for_command = false; 1040 1041 // If our editline input reader is active, it means another input reader 1042 // got pushed onto the input reader and caused us to become deactivated. 1043 // When the input reader above us gets popped, we will get re-activated 1044 // and our prompt will refresh in our callback 1045 if (m_editline_reader.IsActive()) 1046 { 1047 ReadyForCommand (); 1048 } 1049 } 1050 else if (event_type & IOChannel::eBroadcastBitUserInterrupt) 1051 { 1052 // This is here to handle control-c interrupts from the user. It has not yet really been implemented. 1053 // TO BE DONE: PROPERLY HANDLE CONTROL-C FROM USER 1054 //m_io_channel_ap->CancelInput(); 1055 // Anything else? Send Interrupt to process? 1056 } 1057 else if ((event_type & IOChannel::eBroadcastBitThreadShouldExit) || 1058 (event_type & IOChannel::eBroadcastBitThreadDidExit)) 1059 { 1060 // If the IOChannel thread is trying to go away, then it is definitely 1061 // time to end the debugging session. 1062 quit = true; 1063 } 1064 1065 return quit; 1066 } 1067 1068 void 1069 Driver::MasterThreadBytesReceived (void *baton, const void *src, size_t src_len) 1070 { 1071 Driver *driver = (Driver*)baton; 1072 driver->GetFromMaster ((const char *)src, src_len); 1073 } 1074 1075 void 1076 Driver::GetFromMaster (const char *src, size_t src_len) 1077 { 1078 // Echo the characters back to the Debugger's stdout, that way if you 1079 // type characters while a command is running, you'll see what you've typed. 1080 FILE *out_fh = m_debugger.GetOutputFileHandle(); 1081 if (out_fh) 1082 ::fwrite (src, 1, src_len, out_fh); 1083 } 1084 1085 size_t 1086 Driver::EditLineInputReaderCallback 1087 ( 1088 void *baton, 1089 SBInputReader *reader, 1090 InputReaderAction notification, 1091 const char *bytes, 1092 size_t bytes_len 1093 ) 1094 { 1095 Driver *driver = (Driver *)baton; 1096 1097 switch (notification) 1098 { 1099 case eInputReaderActivate: 1100 break; 1101 1102 case eInputReaderReactivate: 1103 driver->ReadyForCommand(); 1104 break; 1105 1106 case eInputReaderDeactivate: 1107 break; 1108 1109 case eInputReaderAsynchronousOutputWritten: 1110 if (driver->m_io_channel_ap.get() != NULL) 1111 driver->m_io_channel_ap->RefreshPrompt(); 1112 break; 1113 1114 case eInputReaderInterrupt: 1115 if (driver->m_io_channel_ap.get() != NULL) 1116 { 1117 SBProcess process(driver->GetDebugger().GetSelectedTarget().GetProcess()); 1118 if (!driver->m_io_channel_ap->EditLineHasCharacters() 1119 && process.IsValid() 1120 && (process.GetState() == lldb::eStateRunning || process.GetState() == lldb::eStateAttaching)) 1121 { 1122 process.SendAsyncInterrupt (); 1123 } 1124 else 1125 { 1126 driver->m_io_channel_ap->OutWrite ("^C\n", 3, NO_ASYNC); 1127 // I wish I could erase the entire input line, but there's no public API for that. 1128 driver->m_io_channel_ap->EraseCharsBeforeCursor(); 1129 driver->m_io_channel_ap->RefreshPrompt(); 1130 } 1131 } 1132 break; 1133 1134 case eInputReaderEndOfFile: 1135 if (driver->m_io_channel_ap.get() != NULL) 1136 { 1137 driver->m_io_channel_ap->OutWrite ("^D\n", 3, NO_ASYNC); 1138 driver->m_io_channel_ap->RefreshPrompt (); 1139 } 1140 write (driver->m_editline_pty.GetMasterFileDescriptor(), "quit\n", 5); 1141 break; 1142 1143 case eInputReaderGotToken: 1144 write (driver->m_editline_pty.GetMasterFileDescriptor(), bytes, bytes_len); 1145 break; 1146 1147 case eInputReaderDone: 1148 break; 1149 } 1150 return bytes_len; 1151 } 1152 1153 void 1154 Driver::MainLoop () 1155 { 1156 char error_str[1024]; 1157 if (m_editline_pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, error_str, sizeof(error_str)) == false) 1158 { 1159 ::fprintf (stderr, "error: failed to open driver pseudo terminal : %s", error_str); 1160 exit(1); 1161 } 1162 else 1163 { 1164 const char *driver_slave_name = m_editline_pty.GetSlaveName (error_str, sizeof(error_str)); 1165 if (driver_slave_name == NULL) 1166 { 1167 ::fprintf (stderr, "error: failed to get slave name for driver pseudo terminal : %s", error_str); 1168 exit(2); 1169 } 1170 else 1171 { 1172 m_editline_slave_fh = ::fopen (driver_slave_name, "r+"); 1173 if (m_editline_slave_fh == NULL) 1174 { 1175 SBError error; 1176 error.SetErrorToErrno(); 1177 ::fprintf (stderr, "error: failed to get open slave for driver pseudo terminal : %s", 1178 error.GetCString()); 1179 exit(3); 1180 } 1181 1182 ::setbuf (m_editline_slave_fh, NULL); 1183 } 1184 } 1185 1186 lldb_utility::PseudoTerminal editline_output_pty; 1187 FILE *editline_output_slave_fh = NULL; 1188 1189 if (editline_output_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str, sizeof (error_str)) == false) 1190 { 1191 ::fprintf (stderr, "error: failed to open output pseudo terminal : %s", error_str); 1192 exit(1); 1193 } 1194 else 1195 { 1196 const char *output_slave_name = editline_output_pty.GetSlaveName (error_str, sizeof(error_str)); 1197 if (output_slave_name == NULL) 1198 { 1199 ::fprintf (stderr, "error: failed to get slave name for output pseudo terminal : %s", error_str); 1200 exit(2); 1201 } 1202 else 1203 { 1204 editline_output_slave_fh = ::fopen (output_slave_name, "r+"); 1205 if (editline_output_slave_fh == NULL) 1206 { 1207 SBError error; 1208 error.SetErrorToErrno(); 1209 ::fprintf (stderr, "error: failed to get open slave for output pseudo terminal : %s", 1210 error.GetCString()); 1211 exit(3); 1212 } 1213 ::setbuf (editline_output_slave_fh, NULL); 1214 } 1215 } 1216 1217 // struct termios stdin_termios; 1218 1219 if (::tcgetattr(STDIN_FILENO, &g_old_stdin_termios) == 0) 1220 { 1221 g_old_stdin_termios_is_valid = true; 1222 atexit (reset_stdin_termios); 1223 } 1224 1225 ::setbuf (stdin, NULL); 1226 ::setbuf (stdout, NULL); 1227 1228 m_debugger.SetErrorFileHandle (stderr, false); 1229 m_debugger.SetOutputFileHandle (stdout, false); 1230 m_debugger.SetInputFileHandle (stdin, true); 1231 1232 m_debugger.SetUseExternalEditor(m_option_data.m_use_external_editor); 1233 1234 // You have to drain anything that comes to the master side of the PTY. master_out_comm is 1235 // for that purpose. The reason you need to do this is a curious reason... editline will echo 1236 // characters to the PTY when it gets characters while el_gets is not running, and then when 1237 // you call el_gets (or el_getc) it will try to reset the terminal back to raw mode which blocks 1238 // if there are unconsumed characters in the out buffer. 1239 // However, you don't need to do anything with the characters, since editline will dump these 1240 // unconsumed characters after printing the prompt again in el_gets. 1241 1242 SBCommunication master_out_comm("driver.editline"); 1243 master_out_comm.SetCloseOnEOF (false); 1244 master_out_comm.AdoptFileDesriptor(m_editline_pty.GetMasterFileDescriptor(), false); 1245 master_out_comm.SetReadThreadBytesReceivedCallback(Driver::MasterThreadBytesReceived, this); 1246 1247 if (master_out_comm.ReadThreadStart () == false) 1248 { 1249 ::fprintf (stderr, "error: failed to start master out read thread"); 1250 exit(5); 1251 } 1252 1253 SBCommandInterpreter sb_interpreter = m_debugger.GetCommandInterpreter(); 1254 1255 m_io_channel_ap.reset (new IOChannel(m_editline_slave_fh, editline_output_slave_fh, stdout, stderr, this)); 1256 1257 SBCommunication out_comm_2("driver.editline_output"); 1258 out_comm_2.SetCloseOnEOF (false); 1259 out_comm_2.AdoptFileDesriptor (editline_output_pty.GetMasterFileDescriptor(), false); 1260 out_comm_2.SetReadThreadBytesReceivedCallback (IOChannel::LibeditOutputBytesReceived, m_io_channel_ap.get()); 1261 1262 if (out_comm_2.ReadThreadStart () == false) 1263 { 1264 ::fprintf (stderr, "error: failed to start libedit output read thread"); 1265 exit (5); 1266 } 1267 1268 1269 struct winsize window_size; 1270 if (isatty (STDIN_FILENO) 1271 && ::ioctl (STDIN_FILENO, TIOCGWINSZ, &window_size) == 0) 1272 { 1273 if (window_size.ws_col > 0) 1274 m_debugger.SetTerminalWidth (window_size.ws_col); 1275 } 1276 1277 // Since input can be redirected by the debugger, we must insert our editline 1278 // input reader in the queue so we know when our reader should be active 1279 // and so we can receive bytes only when we are supposed to. 1280 SBError err (m_editline_reader.Initialize (m_debugger, 1281 Driver::EditLineInputReaderCallback, // callback 1282 this, // baton 1283 eInputReaderGranularityByte, // token_size 1284 NULL, // end token - NULL means never done 1285 NULL, // prompt - taken care of elsewhere 1286 false)); // echo input - don't need Debugger 1287 // to do this, we handle it elsewhere 1288 1289 if (err.Fail()) 1290 { 1291 ::fprintf (stderr, "error: %s", err.GetCString()); 1292 exit (6); 1293 } 1294 1295 m_debugger.PushInputReader (m_editline_reader); 1296 1297 SBListener listener(m_debugger.GetListener()); 1298 if (listener.IsValid()) 1299 { 1300 1301 listener.StartListeningForEventClass(m_debugger, 1302 SBTarget::GetBroadcasterClassName(), 1303 SBTarget::eBroadcastBitBreakpointChanged); 1304 listener.StartListeningForEventClass(m_debugger, 1305 SBThread::GetBroadcasterClassName(), 1306 SBThread::eBroadcastBitStackChanged); 1307 listener.StartListeningForEvents (*m_io_channel_ap, 1308 IOChannel::eBroadcastBitHasUserInput | 1309 IOChannel::eBroadcastBitUserInterrupt | 1310 IOChannel::eBroadcastBitThreadShouldExit | 1311 IOChannel::eBroadcastBitThreadDidStart | 1312 IOChannel::eBroadcastBitThreadDidExit); 1313 1314 if (m_io_channel_ap->Start ()) 1315 { 1316 bool iochannel_thread_exited = false; 1317 1318 listener.StartListeningForEvents (sb_interpreter.GetBroadcaster(), 1319 SBCommandInterpreter::eBroadcastBitQuitCommandReceived | 1320 SBCommandInterpreter::eBroadcastBitAsynchronousOutputData | 1321 SBCommandInterpreter::eBroadcastBitAsynchronousErrorData); 1322 1323 // Before we handle any options from the command line, we parse the 1324 // .lldbinit file in the user's home directory. 1325 SBCommandReturnObject result; 1326 sb_interpreter.SourceInitFileInHomeDirectory(result); 1327 if (GetDebugMode()) 1328 { 1329 result.PutError (m_debugger.GetErrorFileHandle()); 1330 result.PutOutput (m_debugger.GetOutputFileHandle()); 1331 } 1332 1333 // Now we handle options we got from the command line 1334 char command_string[PATH_MAX * 2]; 1335 const size_t num_source_command_files = GetNumSourceCommandFiles(); 1336 if (num_source_command_files > 0) 1337 { 1338 for (size_t i=0; i < num_source_command_files; ++i) 1339 { 1340 const char *command_file = GetSourceCommandFileAtIndex(i); 1341 ::snprintf (command_string, sizeof(command_string), "command source '%s'", command_file); 1342 m_debugger.GetCommandInterpreter().HandleCommand (command_string, result, false); 1343 if (GetDebugMode()) 1344 { 1345 result.PutError (m_debugger.GetErrorFileHandle()); 1346 result.PutOutput (m_debugger.GetOutputFileHandle()); 1347 } 1348 } 1349 } 1350 1351 // Was there a core file specified? 1352 std::string core_file_spec(""); 1353 if (!m_option_data.m_core_file.empty()) 1354 core_file_spec.append("--core ").append(m_option_data.m_core_file); 1355 1356 const size_t num_args = m_option_data.m_args.size(); 1357 if (num_args > 0) 1358 { 1359 char arch_name[64]; 1360 if (m_debugger.GetDefaultArchitecture (arch_name, sizeof (arch_name))) 1361 ::snprintf (command_string, 1362 sizeof (command_string), 1363 "target create --arch=%s %s \"%s\"", 1364 arch_name, 1365 core_file_spec.c_str(), 1366 m_option_data.m_args[0].c_str()); 1367 else 1368 ::snprintf (command_string, 1369 sizeof(command_string), 1370 "target create %s \"%s\"", 1371 core_file_spec.c_str(), 1372 m_option_data.m_args[0].c_str()); 1373 1374 m_debugger.HandleCommand (command_string); 1375 1376 if (num_args > 1) 1377 { 1378 m_debugger.HandleCommand ("settings clear target.run-args"); 1379 char arg_cstr[1024]; 1380 for (size_t arg_idx = 1; arg_idx < num_args; ++arg_idx) 1381 { 1382 ::snprintf (arg_cstr, 1383 sizeof(arg_cstr), 1384 "settings append target.run-args \"%s\"", 1385 m_option_data.m_args[arg_idx].c_str()); 1386 m_debugger.HandleCommand (arg_cstr); 1387 } 1388 } 1389 } 1390 else if (!core_file_spec.empty()) 1391 { 1392 ::snprintf (command_string, 1393 sizeof(command_string), 1394 "target create %s", 1395 core_file_spec.c_str()); 1396 m_debugger.HandleCommand (command_string);; 1397 } 1398 1399 // Now that all option parsing is done, we try and parse the .lldbinit 1400 // file in the current working directory 1401 sb_interpreter.SourceInitFileInCurrentWorkingDirectory (result); 1402 if (GetDebugMode()) 1403 { 1404 result.PutError(m_debugger.GetErrorFileHandle()); 1405 result.PutOutput(m_debugger.GetOutputFileHandle()); 1406 } 1407 1408 SBEvent event; 1409 1410 // Make sure the IO channel is started up before we try to tell it we 1411 // are ready for input 1412 listener.WaitForEventForBroadcasterWithType (UINT32_MAX, 1413 *m_io_channel_ap, 1414 IOChannel::eBroadcastBitThreadDidStart, 1415 event); 1416 // If we were asked to attach, then do that here: 1417 // I'm going to use the command string rather than directly 1418 // calling the API's because then I don't have to recode the 1419 // event handling here. 1420 if (!m_option_data.m_process_name.empty() 1421 || m_option_data.m_process_pid != LLDB_INVALID_PROCESS_ID) 1422 { 1423 std::string command_str("process attach "); 1424 if (m_option_data.m_process_pid != LLDB_INVALID_PROCESS_ID) 1425 { 1426 command_str.append("-p "); 1427 char pid_buffer[32]; 1428 ::snprintf (pid_buffer, sizeof(pid_buffer), "%" PRIu64, m_option_data.m_process_pid); 1429 command_str.append(pid_buffer); 1430 } 1431 else 1432 { 1433 command_str.append("-n \""); 1434 command_str.append(m_option_data.m_process_name); 1435 command_str.push_back('\"'); 1436 if (m_option_data.m_wait_for) 1437 command_str.append(" -w"); 1438 } 1439 1440 if (m_debugger.GetOutputFileHandle()) 1441 ::fprintf (m_debugger.GetOutputFileHandle(), 1442 "Attaching to process with:\n %s\n", 1443 command_str.c_str()); 1444 1445 // Force the attach to be synchronous: 1446 bool orig_async = m_debugger.GetAsync(); 1447 m_debugger.SetAsync(true); 1448 m_debugger.HandleCommand(command_str.c_str()); 1449 m_debugger.SetAsync(orig_async); 1450 } 1451 1452 ReadyForCommand (); 1453 1454 while (!GetIsDone()) 1455 { 1456 listener.WaitForEvent (UINT32_MAX, event); 1457 if (event.IsValid()) 1458 { 1459 if (event.GetBroadcaster().IsValid()) 1460 { 1461 uint32_t event_type = event.GetType(); 1462 if (event.BroadcasterMatchesRef (*m_io_channel_ap)) 1463 { 1464 if ((event_type & IOChannel::eBroadcastBitThreadShouldExit) || 1465 (event_type & IOChannel::eBroadcastBitThreadDidExit)) 1466 { 1467 SetIsDone(); 1468 if (event_type & IOChannel::eBroadcastBitThreadDidExit) 1469 iochannel_thread_exited = true; 1470 } 1471 else 1472 { 1473 if (HandleIOEvent (event)) 1474 SetIsDone(); 1475 } 1476 } 1477 else if (SBProcess::EventIsProcessEvent (event)) 1478 { 1479 HandleProcessEvent (event); 1480 } 1481 else if (SBBreakpoint::EventIsBreakpointEvent (event)) 1482 { 1483 HandleBreakpointEvent (event); 1484 } 1485 else if (SBThread::EventIsThreadEvent (event)) 1486 { 1487 HandleThreadEvent (event); 1488 } 1489 else if (event.BroadcasterMatchesRef (sb_interpreter.GetBroadcaster())) 1490 { 1491 // TODO: deprecate the eBroadcastBitQuitCommandReceived event 1492 // now that we have SBCommandInterpreter::SetCommandOverrideCallback() 1493 // that can take over a command 1494 if (event_type & SBCommandInterpreter::eBroadcastBitQuitCommandReceived) 1495 { 1496 SetIsDone(); 1497 } 1498 else if (event_type & SBCommandInterpreter::eBroadcastBitAsynchronousErrorData) 1499 { 1500 const char *data = SBEvent::GetCStringFromEvent (event); 1501 m_io_channel_ap->ErrWrite (data, strlen(data), ASYNC); 1502 } 1503 else if (event_type & SBCommandInterpreter::eBroadcastBitAsynchronousOutputData) 1504 { 1505 const char *data = SBEvent::GetCStringFromEvent (event); 1506 m_io_channel_ap->OutWrite (data, strlen(data), ASYNC); 1507 } 1508 } 1509 } 1510 } 1511 } 1512 1513 editline_output_pty.CloseMasterFileDescriptor(); 1514 master_out_comm.Disconnect(); 1515 out_comm_2.Disconnect(); 1516 reset_stdin_termios(); 1517 fclose (stdin); 1518 1519 CloseIOChannelFile (); 1520 1521 if (!iochannel_thread_exited) 1522 { 1523 event.Clear(); 1524 listener.GetNextEventForBroadcasterWithType (*m_io_channel_ap, 1525 IOChannel::eBroadcastBitThreadDidExit, 1526 event); 1527 if (!event.IsValid()) 1528 { 1529 // Send end EOF to the driver file descriptor 1530 m_io_channel_ap->Stop(); 1531 } 1532 } 1533 1534 SBDebugger::Destroy (m_debugger); 1535 } 1536 } 1537 } 1538 1539 1540 void 1541 Driver::ReadyForCommand () 1542 { 1543 if (m_waiting_for_command == false) 1544 { 1545 m_waiting_for_command = true; 1546 BroadcastEventByType (Driver::eBroadcastBitReadyForInput, true); 1547 } 1548 } 1549 1550 1551 void 1552 sigwinch_handler (int signo) 1553 { 1554 struct winsize window_size; 1555 if (isatty (STDIN_FILENO) 1556 && ::ioctl (STDIN_FILENO, TIOCGWINSZ, &window_size) == 0) 1557 { 1558 if ((window_size.ws_col > 0) && g_driver != NULL) 1559 { 1560 g_driver->GetDebugger().SetTerminalWidth (window_size.ws_col); 1561 } 1562 } 1563 } 1564 1565 void 1566 sigint_handler (int signo) 1567 { 1568 static bool g_interrupt_sent = false; 1569 if (g_driver) 1570 { 1571 if (!g_interrupt_sent) 1572 { 1573 g_interrupt_sent = true; 1574 g_driver->GetDebugger().DispatchInputInterrupt(); 1575 g_interrupt_sent = false; 1576 return; 1577 } 1578 } 1579 1580 exit (signo); 1581 } 1582 1583 void 1584 sigtstp_handler (int signo) 1585 { 1586 g_driver->GetDebugger().SaveInputTerminalState(); 1587 signal (signo, SIG_DFL); 1588 kill (getpid(), signo); 1589 signal (signo, sigtstp_handler); 1590 } 1591 1592 void 1593 sigcont_handler (int signo) 1594 { 1595 g_driver->GetDebugger().RestoreInputTerminalState(); 1596 signal (signo, SIG_DFL); 1597 kill (getpid(), signo); 1598 signal (signo, sigcont_handler); 1599 } 1600 1601 int 1602 main (int argc, char const *argv[], const char *envp[]) 1603 { 1604 SBDebugger::Initialize(); 1605 1606 SBHostOS::ThreadCreated ("<lldb.driver.main-thread>"); 1607 1608 signal (SIGPIPE, SIG_IGN); 1609 signal (SIGWINCH, sigwinch_handler); 1610 signal (SIGINT, sigint_handler); 1611 signal (SIGTSTP, sigtstp_handler); 1612 signal (SIGCONT, sigcont_handler); 1613 1614 // Create a scope for driver so that the driver object will destroy itself 1615 // before SBDebugger::Terminate() is called. 1616 { 1617 Driver driver; 1618 1619 bool exit = false; 1620 SBError error (driver.ParseArgs (argc, argv, stdout, exit)); 1621 if (error.Fail()) 1622 { 1623 const char *error_cstr = error.GetCString (); 1624 if (error_cstr) 1625 ::fprintf (stderr, "error: %s\n", error_cstr); 1626 } 1627 else if (!exit) 1628 { 1629 driver.MainLoop (); 1630 } 1631 } 1632 1633 SBDebugger::Terminate(); 1634 return 0; 1635 } 1636