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 <stdio.h> 13 #include <string.h> 14 #include <stdlib.h> 15 #include <limits.h> 16 #include <fcntl.h> 17 18 // Includes for pipe() 19 #if defined(_WIN32) 20 #include <io.h> 21 #include <fcntl.h> 22 #else 23 #include <unistd.h> 24 #endif 25 26 #include <string> 27 28 #include <thread> 29 #include "lldb/API/SBBreakpoint.h" 30 #include "lldb/API/SBCommandInterpreter.h" 31 #include "lldb/API/SBCommandReturnObject.h" 32 #include "lldb/API/SBCommunication.h" 33 #include "lldb/API/SBDebugger.h" 34 #include "lldb/API/SBEvent.h" 35 #include "lldb/API/SBHostOS.h" 36 #include "lldb/API/SBListener.h" 37 #include "lldb/API/SBStream.h" 38 #include "lldb/API/SBTarget.h" 39 #include "lldb/API/SBThread.h" 40 #include "lldb/API/SBProcess.h" 41 42 #if !defined(__APPLE__) 43 #include "llvm/Support/DataTypes.h" 44 #endif 45 46 using namespace lldb; 47 48 static void reset_stdin_termios (); 49 static bool g_old_stdin_termios_is_valid = false; 50 static struct termios g_old_stdin_termios; 51 52 static char *g_debugger_name = (char *) ""; 53 static Driver *g_driver = NULL; 54 55 // In the Driver::MainLoop, we change the terminal settings. This function is 56 // added as an atexit handler to make sure we clean them up. 57 static void 58 reset_stdin_termios () 59 { 60 if (g_old_stdin_termios_is_valid) 61 { 62 g_old_stdin_termios_is_valid = false; 63 ::tcsetattr (STDIN_FILENO, TCSANOW, &g_old_stdin_termios); 64 } 65 } 66 67 typedef struct 68 { 69 uint32_t usage_mask; // Used to mark options that can be used together. If (1 << n & usage_mask) != 0 70 // then this option belongs to option set n. 71 bool required; // This option is required (in the current usage level) 72 const char * long_option; // Full name for this option. 73 int short_option; // Single character for this option. 74 int option_has_arg; // no_argument, required_argument or optional_argument 75 uint32_t completion_type; // Cookie the option class can use to do define the argument completion. 76 lldb::CommandArgumentType argument_type; // Type of argument this option takes 77 const char * usage_text; // Full text explaining what this options does and what (if any) argument to 78 // pass it. 79 } OptionDefinition; 80 81 #define LLDB_3_TO_5 LLDB_OPT_SET_3|LLDB_OPT_SET_4|LLDB_OPT_SET_5 82 #define LLDB_4_TO_5 LLDB_OPT_SET_4|LLDB_OPT_SET_5 83 84 static OptionDefinition g_options[] = 85 { 86 { LLDB_OPT_SET_1, true , "help" , 'h', no_argument , 0, eArgTypeNone, 87 "Prints out the usage information for the LLDB debugger." }, 88 { LLDB_OPT_SET_2, true , "version" , 'v', no_argument , 0, eArgTypeNone, 89 "Prints out the current version number of the LLDB debugger." }, 90 { LLDB_OPT_SET_3, true , "arch" , 'a', required_argument, 0, eArgTypeArchitecture, 91 "Tells the debugger to use the specified architecture when starting and running the program. <architecture> must " 92 "be one of the architectures for which the program was compiled." }, 93 { LLDB_OPT_SET_3, true , "file" , 'f', required_argument, 0, eArgTypeFilename, 94 "Tells the debugger to use the file <filename> as the program to be debugged." }, 95 { LLDB_OPT_SET_3, false, "core" , 'c', required_argument, 0, eArgTypeFilename, 96 "Tells the debugger to use the fullpath to <path> as the core file." }, 97 { LLDB_OPT_SET_5, true , "attach-pid" , 'p', required_argument, 0, eArgTypePid, 98 "Tells the debugger to attach to a process with the given pid." }, 99 { LLDB_OPT_SET_4, true , "attach-name" , 'n', required_argument, 0, eArgTypeProcessName, 100 "Tells the debugger to attach to a process with the given name." }, 101 { LLDB_OPT_SET_4, true , "wait-for" , 'w', no_argument , 0, eArgTypeNone, 102 "Tells the debugger to wait for a process with the given pid or name to launch before attaching." }, 103 { LLDB_3_TO_5, false, "source" , 's', required_argument, 0, eArgTypeFilename, 104 "Tells the debugger to read in and execute the lldb commands in the given file, after any file provided on the command line has been loaded." }, 105 { LLDB_3_TO_5, false, "one-line" , 'o', required_argument, 0, eArgTypeNone, 106 "Tells the debugger to execute this one-line lldb command after any file provided on the command line has been loaded." }, 107 { LLDB_3_TO_5, false, "source-before-file" , 'S', required_argument, 0, eArgTypeFilename, 108 "Tells the debugger to read in and execute the lldb commands in the given file, before any file provided on the command line has been loaded." }, 109 { LLDB_3_TO_5, false, "one-line-before-file" , 'O', required_argument, 0, eArgTypeNone, 110 "Tells the debugger to execute this one-line lldb command before any file provided on the command line has been loaded." }, 111 { LLDB_3_TO_5, false, "source-quietly" , 'Q', no_argument , 0, eArgTypeNone, 112 "Tells the debugger to execute this one-line lldb command before any file provided on the command line has been loaded." }, 113 { LLDB_3_TO_5, false, "batch" , 'b', no_argument , 0, eArgTypeNone, 114 "Tells the debugger to running the commands from -s, -S, -o & -O, and then quit. However if any run command stopped due to a signal or crash, " 115 "the debugger will return to the interactive prompt at the place of the crash." }, 116 { LLDB_3_TO_5, false, "editor" , 'e', no_argument , 0, eArgTypeNone, 117 "Tells the debugger to open source files using the host's \"external editor\" mechanism." }, 118 { LLDB_3_TO_5, false, "no-lldbinit" , 'x', no_argument , 0, eArgTypeNone, 119 "Do not automatically parse any '.lldbinit' files." }, 120 { LLDB_3_TO_5, false, "no-use-colors" , 'X', no_argument , 0, eArgTypeNone, 121 "Do not use colors." }, 122 { LLDB_OPT_SET_6, true , "python-path" , 'P', no_argument , 0, eArgTypeNone, 123 "Prints out the path to the lldb.py file for this version of lldb." }, 124 { LLDB_3_TO_5, false, "script-language", 'l', required_argument, 0, eArgTypeScriptLang, 125 "Tells the debugger to use the specified scripting language for user-defined scripts, rather than the default. " 126 "Valid scripting languages that can be specified include Python, Perl, Ruby and Tcl. Currently only the Python " 127 "extensions have been implemented." }, 128 { LLDB_3_TO_5, false, "debug" , 'd', no_argument , 0, eArgTypeNone, 129 "Tells the debugger to print out extra information for debugging itself." }, 130 { 0, false, NULL , 0 , 0 , 0, eArgTypeNone, NULL } 131 }; 132 133 static const uint32_t last_option_set_with_args = 2; 134 135 Driver::Driver () : 136 SBBroadcaster ("Driver"), 137 m_debugger (SBDebugger::Create(false)), 138 m_option_data () 139 { 140 // We want to be able to handle CTRL+D in the terminal to have it terminate 141 // certain input 142 m_debugger.SetCloseInputOnEOF (false); 143 g_debugger_name = (char *) m_debugger.GetInstanceName(); 144 if (g_debugger_name == NULL) 145 g_debugger_name = (char *) ""; 146 g_driver = this; 147 } 148 149 Driver::~Driver () 150 { 151 g_driver = NULL; 152 g_debugger_name = NULL; 153 } 154 155 156 // This function takes INDENT, which tells how many spaces to output at the front 157 // of each line; TEXT, which is the text that is to be output. It outputs the 158 // text, on multiple lines if necessary, to RESULT, with INDENT spaces at the 159 // front of each line. It breaks lines on spaces, tabs or newlines, shortening 160 // the line if necessary to not break in the middle of a word. It assumes that 161 // each output line should contain a maximum of OUTPUT_MAX_COLUMNS characters. 162 163 void 164 OutputFormattedUsageText (FILE *out, int indent, const char *text, int output_max_columns) 165 { 166 int len = strlen (text); 167 std::string text_string (text); 168 169 // Force indentation to be reasonable. 170 if (indent >= output_max_columns) 171 indent = 0; 172 173 // Will it all fit on one line? 174 175 if (len + indent < output_max_columns) 176 // Output as a single line 177 fprintf (out, "%*s%s\n", indent, "", text); 178 else 179 { 180 // We need to break it up into multiple lines. 181 int text_width = output_max_columns - indent - 1; 182 int start = 0; 183 int end = start; 184 int final_end = len; 185 int sub_len; 186 187 while (end < final_end) 188 { 189 // Dont start the 'text' on a space, since we're already outputting the indentation. 190 while ((start < final_end) && (text[start] == ' ')) 191 start++; 192 193 end = start + text_width; 194 if (end > final_end) 195 end = final_end; 196 else 197 { 198 // If we're not at the end of the text, make sure we break the line on white space. 199 while (end > start 200 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n') 201 end--; 202 } 203 sub_len = end - start; 204 std::string substring = text_string.substr (start, sub_len); 205 fprintf (out, "%*s%s\n", indent, "", substring.c_str()); 206 start = end + 1; 207 } 208 } 209 } 210 211 void 212 ShowUsage (FILE *out, OptionDefinition *option_table, Driver::OptionData data) 213 { 214 uint32_t screen_width = 80; 215 uint32_t indent_level = 0; 216 const char *name = "lldb"; 217 218 fprintf (out, "\nUsage:\n\n"); 219 220 indent_level += 2; 221 222 223 // First, show each usage level set of options, e.g. <cmd> [options-for-level-0] 224 // <cmd> [options-for-level-1] 225 // etc. 226 227 uint32_t num_options; 228 uint32_t num_option_sets = 0; 229 230 for (num_options = 0; option_table[num_options].long_option != NULL; ++num_options) 231 { 232 uint32_t this_usage_mask = option_table[num_options].usage_mask; 233 if (this_usage_mask == LLDB_OPT_SET_ALL) 234 { 235 if (num_option_sets == 0) 236 num_option_sets = 1; 237 } 238 else 239 { 240 for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++) 241 { 242 if (this_usage_mask & 1 << j) 243 { 244 if (num_option_sets <= j) 245 num_option_sets = j + 1; 246 } 247 } 248 } 249 } 250 251 for (uint32_t opt_set = 0; opt_set < num_option_sets; opt_set++) 252 { 253 uint32_t opt_set_mask; 254 255 opt_set_mask = 1 << opt_set; 256 257 if (opt_set > 0) 258 fprintf (out, "\n"); 259 fprintf (out, "%*s%s", indent_level, "", name); 260 bool is_help_line = false; 261 262 for (uint32_t i = 0; i < num_options; ++i) 263 { 264 if (option_table[i].usage_mask & opt_set_mask) 265 { 266 CommandArgumentType arg_type = option_table[i].argument_type; 267 const char *arg_name = SBCommandInterpreter::GetArgumentTypeAsCString (arg_type); 268 // This is a bit of a hack, but there's no way to say certain options don't have arguments yet... 269 // so we do it by hand here. 270 if (option_table[i].short_option == 'h') 271 is_help_line = true; 272 273 if (option_table[i].required) 274 { 275 if (option_table[i].option_has_arg == required_argument) 276 fprintf (out, " -%c <%s>", option_table[i].short_option, arg_name); 277 else if (option_table[i].option_has_arg == optional_argument) 278 fprintf (out, " -%c [<%s>]", option_table[i].short_option, arg_name); 279 else 280 fprintf (out, " -%c", option_table[i].short_option); 281 } 282 else 283 { 284 if (option_table[i].option_has_arg == required_argument) 285 fprintf (out, " [-%c <%s>]", option_table[i].short_option, arg_name); 286 else if (option_table[i].option_has_arg == optional_argument) 287 fprintf (out, " [-%c [<%s>]]", option_table[i].short_option, arg_name); 288 else 289 fprintf (out, " [-%c]", option_table[i].short_option); 290 } 291 } 292 } 293 if (!is_help_line && (opt_set <= last_option_set_with_args)) 294 fprintf (out, " [[--] <PROGRAM-ARG-1> [<PROGRAM_ARG-2> ...]]"); 295 } 296 297 fprintf (out, "\n\n"); 298 299 // Now print out all the detailed information about the various options: long form, short form and help text: 300 // -- long_name <argument> 301 // - short <argument> 302 // help text 303 304 // This variable is used to keep track of which options' info we've printed out, because some options can be in 305 // more than one usage level, but we only want to print the long form of its information once. 306 307 Driver::OptionData::OptionSet options_seen; 308 Driver::OptionData::OptionSet::iterator pos; 309 310 indent_level += 5; 311 312 for (uint32_t i = 0; i < num_options; ++i) 313 { 314 // Only print this option if we haven't already seen it. 315 pos = options_seen.find (option_table[i].short_option); 316 if (pos == options_seen.end()) 317 { 318 CommandArgumentType arg_type = option_table[i].argument_type; 319 const char *arg_name = SBCommandInterpreter::GetArgumentTypeAsCString (arg_type); 320 321 options_seen.insert (option_table[i].short_option); 322 fprintf (out, "%*s-%c ", indent_level, "", option_table[i].short_option); 323 if (arg_type != eArgTypeNone) 324 fprintf (out, "<%s>", arg_name); 325 fprintf (out, "\n"); 326 fprintf (out, "%*s--%s ", indent_level, "", option_table[i].long_option); 327 if (arg_type != eArgTypeNone) 328 fprintf (out, "<%s>", arg_name); 329 fprintf (out, "\n"); 330 indent_level += 5; 331 OutputFormattedUsageText (out, indent_level, option_table[i].usage_text, screen_width); 332 indent_level -= 5; 333 fprintf (out, "\n"); 334 } 335 } 336 337 indent_level -= 5; 338 339 fprintf (out, "\n%*sNotes:\n", 340 indent_level, ""); 341 indent_level += 5; 342 343 fprintf (out, "\n%*sMultiple \"-s\" and \"-o\" options can be provided. They will be processed from left to right in order, " 344 "\n%*swith the source files and commands interleaved. The same is true of the \"-S\" and \"-O\" options." 345 "\n%*sThe before file and after file sets can intermixed freely, the command parser will sort them out." 346 "\n%*sThe order of the file specifiers (\"-c\", \"-f\", etc.) is not significant in this regard.\n\n", 347 indent_level, "", 348 indent_level, "", 349 indent_level, "", 350 indent_level, ""); 351 352 fprintf (out, "\n%*sIf you don't provide -f then the first argument will be the file to be debugged" 353 "\n%*swhich means that '%s -- <filename> [<ARG1> [<ARG2>]]' also works." 354 "\n%*sBut remember to end the options with \"--\" if any of your arguments have a \"-\" in them.\n\n", 355 indent_level, "", 356 indent_level, "", 357 name, 358 indent_level, ""); 359 } 360 361 void 362 BuildGetOptTable (OptionDefinition *expanded_option_table, std::vector<struct option> &getopt_table, 363 uint32_t num_options) 364 { 365 if (num_options == 0) 366 return; 367 368 uint32_t i; 369 uint32_t j; 370 std::bitset<256> option_seen; 371 372 getopt_table.resize (num_options + 1); 373 374 for (i = 0, j = 0; i < num_options; ++i) 375 { 376 char short_opt = expanded_option_table[i].short_option; 377 378 if (option_seen.test(short_opt) == false) 379 { 380 getopt_table[j].name = expanded_option_table[i].long_option; 381 getopt_table[j].has_arg = expanded_option_table[i].option_has_arg; 382 getopt_table[j].flag = NULL; 383 getopt_table[j].val = expanded_option_table[i].short_option; 384 option_seen.set(short_opt); 385 ++j; 386 } 387 } 388 389 getopt_table[j].name = NULL; 390 getopt_table[j].has_arg = 0; 391 getopt_table[j].flag = NULL; 392 getopt_table[j].val = 0; 393 394 } 395 396 Driver::OptionData::OptionData () : 397 m_args(), 398 m_script_lang (lldb::eScriptLanguageDefault), 399 m_core_file (), 400 m_crash_log (), 401 m_initial_commands (), 402 m_after_file_commands (), 403 m_debug_mode (false), 404 m_source_quietly(false), 405 m_print_version (false), 406 m_print_python_path (false), 407 m_print_help (false), 408 m_wait_for(false), 409 m_process_name(), 410 m_process_pid(LLDB_INVALID_PROCESS_ID), 411 m_use_external_editor(false), 412 m_batch(false), 413 m_seen_options() 414 { 415 } 416 417 Driver::OptionData::~OptionData () 418 { 419 } 420 421 void 422 Driver::OptionData::Clear () 423 { 424 m_args.clear (); 425 m_script_lang = lldb::eScriptLanguageDefault; 426 m_initial_commands.clear (); 427 m_after_file_commands.clear (); 428 m_debug_mode = false; 429 m_source_quietly = false; 430 m_print_help = false; 431 m_print_version = false; 432 m_print_python_path = false; 433 m_use_external_editor = false; 434 m_wait_for = false; 435 m_process_name.erase(); 436 m_batch = false; 437 m_process_pid = LLDB_INVALID_PROCESS_ID; 438 } 439 440 void 441 Driver::OptionData::AddInitialCommand (const char *command, bool before_file, bool is_file, SBError &error) 442 { 443 std::vector<std::pair<bool, std::string> > *command_set; 444 if (before_file) 445 command_set = &(m_initial_commands); 446 else 447 command_set = &(m_after_file_commands); 448 449 if (is_file) 450 { 451 SBFileSpec file(command); 452 if (file.Exists()) 453 command_set->push_back (std::pair<bool, std::string> (true, optarg)); 454 else if (file.ResolveExecutableLocation()) 455 { 456 char final_path[PATH_MAX]; 457 file.GetPath (final_path, sizeof(final_path)); 458 std::string path_str (final_path); 459 command_set->push_back (std::pair<bool, std::string> (true, path_str)); 460 } 461 else 462 error.SetErrorStringWithFormat("file specified in --source (-s) option doesn't exist: '%s'", optarg); 463 } 464 else 465 command_set->push_back (std::pair<bool, std::string> (false, optarg)); 466 } 467 468 void 469 Driver::ResetOptionValues () 470 { 471 m_option_data.Clear (); 472 } 473 474 const char * 475 Driver::GetFilename() const 476 { 477 if (m_option_data.m_args.empty()) 478 return NULL; 479 return m_option_data.m_args.front().c_str(); 480 } 481 482 const char * 483 Driver::GetCrashLogFilename() const 484 { 485 if (m_option_data.m_crash_log.empty()) 486 return NULL; 487 return m_option_data.m_crash_log.c_str(); 488 } 489 490 lldb::ScriptLanguage 491 Driver::GetScriptLanguage() const 492 { 493 return m_option_data.m_script_lang; 494 } 495 496 void 497 Driver::WriteInitialCommands (bool before_file, SBStream &strm) 498 { 499 std::vector<std::pair<bool, std::string> > &command_set = before_file ? m_option_data.m_initial_commands : 500 m_option_data.m_after_file_commands; 501 502 for (const auto &command_pair : command_set) 503 { 504 const char *command = command_pair.second.c_str(); 505 if (command_pair.first) 506 strm.Printf("command source -s %i '%s'\n", m_option_data.m_source_quietly, command); 507 else 508 strm.Printf("%s\n", command); 509 } 510 } 511 512 bool 513 Driver::GetDebugMode() const 514 { 515 return m_option_data.m_debug_mode; 516 } 517 518 519 // Check the arguments that were passed to this program to make sure they are valid and to get their 520 // argument values (if any). Return a boolean value indicating whether or not to start up the full 521 // debugger (i.e. the Command Interpreter) or not. Return FALSE if the arguments were invalid OR 522 // if the user only wanted help or version information. 523 524 SBError 525 Driver::ParseArgs (int argc, const char *argv[], FILE *out_fh, bool &exiting) 526 { 527 ResetOptionValues (); 528 529 SBCommandReturnObject result; 530 531 SBError error; 532 std::string option_string; 533 struct option *long_options = NULL; 534 std::vector<struct option> long_options_vector; 535 uint32_t num_options; 536 537 for (num_options = 0; g_options[num_options].long_option != NULL; ++num_options) 538 /* Do Nothing. */; 539 540 if (num_options == 0) 541 { 542 if (argc > 1) 543 error.SetErrorStringWithFormat ("invalid number of options"); 544 return error; 545 } 546 547 BuildGetOptTable (g_options, long_options_vector, num_options); 548 549 if (long_options_vector.empty()) 550 long_options = NULL; 551 else 552 long_options = &long_options_vector.front(); 553 554 if (long_options == NULL) 555 { 556 error.SetErrorStringWithFormat ("invalid long options"); 557 return error; 558 } 559 560 // Build the option_string argument for call to getopt_long_only. 561 562 for (int i = 0; long_options[i].name != NULL; ++i) 563 { 564 if (long_options[i].flag == NULL) 565 { 566 option_string.push_back ((char) long_options[i].val); 567 switch (long_options[i].has_arg) 568 { 569 default: 570 case no_argument: 571 break; 572 case required_argument: 573 option_string.push_back (':'); 574 break; 575 case optional_argument: 576 option_string.append ("::"); 577 break; 578 } 579 } 580 } 581 582 // This is kind of a pain, but since we make the debugger in the Driver's constructor, we can't 583 // know at that point whether we should read in init files yet. So we don't read them in in the 584 // Driver constructor, then set the flags back to "read them in" here, and then if we see the 585 // "-n" flag, we'll turn it off again. Finally we have to read them in by hand later in the 586 // main loop. 587 588 m_debugger.SkipLLDBInitFiles (false); 589 m_debugger.SkipAppInitFiles (false); 590 591 // Prepare for & make calls to getopt_long_only. 592 #if __GLIBC__ 593 optind = 0; 594 #else 595 optreset = 1; 596 optind = 1; 597 #endif 598 int val; 599 while (1) 600 { 601 int long_options_index = -1; 602 val = ::getopt_long_only (argc, const_cast<char **>(argv), option_string.c_str(), long_options, &long_options_index); 603 604 if (val == -1) 605 break; 606 else if (val == '?') 607 { 608 m_option_data.m_print_help = true; 609 error.SetErrorStringWithFormat ("unknown or ambiguous option"); 610 break; 611 } 612 else if (val == 0) 613 continue; 614 else 615 { 616 m_option_data.m_seen_options.insert ((char) val); 617 if (long_options_index == -1) 618 { 619 for (int i = 0; 620 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val; 621 ++i) 622 { 623 if (long_options[i].val == val) 624 { 625 long_options_index = i; 626 break; 627 } 628 } 629 } 630 631 if (long_options_index >= 0) 632 { 633 const int short_option = g_options[long_options_index].short_option; 634 635 switch (short_option) 636 { 637 case 'h': 638 m_option_data.m_print_help = true; 639 break; 640 641 case 'v': 642 m_option_data.m_print_version = true; 643 break; 644 645 case 'P': 646 m_option_data.m_print_python_path = true; 647 break; 648 649 case 'b': 650 m_option_data.m_batch = true; 651 break; 652 653 case 'c': 654 { 655 SBFileSpec file(optarg); 656 if (file.Exists()) 657 { 658 m_option_data.m_core_file = optarg; 659 } 660 else 661 error.SetErrorStringWithFormat("file specified in --core (-c) option doesn't exist: '%s'", optarg); 662 } 663 break; 664 665 case 'e': 666 m_option_data.m_use_external_editor = true; 667 break; 668 669 case 'x': 670 m_debugger.SkipLLDBInitFiles (true); 671 m_debugger.SkipAppInitFiles (true); 672 break; 673 674 case 'X': 675 m_debugger.SetUseColor (false); 676 break; 677 678 case 'f': 679 { 680 SBFileSpec file(optarg); 681 if (file.Exists()) 682 { 683 m_option_data.m_args.push_back (optarg); 684 } 685 else if (file.ResolveExecutableLocation()) 686 { 687 char path[PATH_MAX]; 688 file.GetPath (path, sizeof(path)); 689 m_option_data.m_args.push_back (path); 690 } 691 else 692 error.SetErrorStringWithFormat("file specified in --file (-f) option doesn't exist: '%s'", optarg); 693 } 694 break; 695 696 case 'a': 697 if (!m_debugger.SetDefaultArchitecture (optarg)) 698 error.SetErrorStringWithFormat("invalid architecture in the -a or --arch option: '%s'", optarg); 699 break; 700 701 case 'l': 702 m_option_data.m_script_lang = m_debugger.GetScriptingLanguage (optarg); 703 break; 704 705 case 'd': 706 m_option_data.m_debug_mode = true; 707 break; 708 709 case 'Q': 710 m_option_data.m_source_quietly = true; 711 break; 712 713 case 'n': 714 m_option_data.m_process_name = optarg; 715 break; 716 717 case 'w': 718 m_option_data.m_wait_for = true; 719 break; 720 721 case 'p': 722 { 723 char *remainder; 724 m_option_data.m_process_pid = strtol (optarg, &remainder, 0); 725 if (remainder == optarg || *remainder != '\0') 726 error.SetErrorStringWithFormat ("Could not convert process PID: \"%s\" into a pid.", 727 optarg); 728 } 729 break; 730 case 's': 731 m_option_data.AddInitialCommand(optarg, false, true, error); 732 break; 733 case 'o': 734 m_option_data.AddInitialCommand(optarg, false, false, error); 735 break; 736 case 'S': 737 m_option_data.AddInitialCommand(optarg, true, true, error); 738 break; 739 case 'O': 740 m_option_data.AddInitialCommand(optarg, true, false, error); 741 break; 742 default: 743 m_option_data.m_print_help = true; 744 error.SetErrorStringWithFormat ("unrecognized option %c", short_option); 745 break; 746 } 747 } 748 else 749 { 750 error.SetErrorStringWithFormat ("invalid option with value %i", val); 751 } 752 if (error.Fail()) 753 { 754 return error; 755 } 756 } 757 } 758 759 if (error.Fail() || m_option_data.m_print_help) 760 { 761 ShowUsage (out_fh, g_options, m_option_data); 762 exiting = true; 763 } 764 else if (m_option_data.m_print_version) 765 { 766 ::fprintf (out_fh, "%s\n", m_debugger.GetVersionString()); 767 exiting = true; 768 } 769 else if (m_option_data.m_print_python_path) 770 { 771 SBFileSpec python_file_spec = SBHostOS::GetLLDBPythonPath(); 772 if (python_file_spec.IsValid()) 773 { 774 char python_path[PATH_MAX]; 775 size_t num_chars = python_file_spec.GetPath(python_path, PATH_MAX); 776 if (num_chars < PATH_MAX) 777 { 778 ::fprintf (out_fh, "%s\n", python_path); 779 } 780 else 781 ::fprintf (out_fh, "<PATH TOO LONG>\n"); 782 } 783 else 784 ::fprintf (out_fh, "<COULD NOT FIND PATH>\n"); 785 exiting = true; 786 } 787 else if (m_option_data.m_process_name.empty() && m_option_data.m_process_pid == LLDB_INVALID_PROCESS_ID) 788 { 789 // Any arguments that are left over after option parsing are for 790 // the program. If a file was specified with -f then the filename 791 // is already in the m_option_data.m_args array, and any remaining args 792 // are arguments for the inferior program. If no file was specified with 793 // -f, then what is left is the program name followed by any arguments. 794 795 // Skip any options we consumed with getopt_long_only 796 argc -= optind; 797 argv += optind; 798 799 if (argc > 0) 800 { 801 for (int arg_idx=0; arg_idx<argc; ++arg_idx) 802 { 803 const char *arg = argv[arg_idx]; 804 if (arg) 805 m_option_data.m_args.push_back (arg); 806 } 807 } 808 809 } 810 else 811 { 812 // Skip any options we consumed with getopt_long_only 813 argc -= optind; 814 //argv += optind; // Commented out to keep static analyzer happy 815 816 if (argc > 0) 817 ::fprintf (out_fh, "Warning: program arguments are ignored when attaching.\n"); 818 } 819 820 return error; 821 } 822 823 void 824 Driver::MainLoop () 825 { 826 if (::tcgetattr(STDIN_FILENO, &g_old_stdin_termios) == 0) 827 { 828 g_old_stdin_termios_is_valid = true; 829 atexit (reset_stdin_termios); 830 } 831 832 ::setbuf (stdin, NULL); 833 ::setbuf (stdout, NULL); 834 835 m_debugger.SetErrorFileHandle (stderr, false); 836 m_debugger.SetOutputFileHandle (stdout, false); 837 m_debugger.SetInputFileHandle (stdin, false); // Don't take ownership of STDIN yet... 838 839 m_debugger.SetUseExternalEditor(m_option_data.m_use_external_editor); 840 841 struct winsize window_size; 842 if (isatty (STDIN_FILENO) 843 && ::ioctl (STDIN_FILENO, TIOCGWINSZ, &window_size) == 0) 844 { 845 if (window_size.ws_col > 0) 846 m_debugger.SetTerminalWidth (window_size.ws_col); 847 } 848 849 SBCommandInterpreter sb_interpreter = m_debugger.GetCommandInterpreter(); 850 851 // Before we handle any options from the command line, we parse the 852 // .lldbinit file in the user's home directory. 853 SBCommandReturnObject result; 854 sb_interpreter.SourceInitFileInHomeDirectory(result); 855 if (GetDebugMode()) 856 { 857 result.PutError (m_debugger.GetErrorFileHandle()); 858 result.PutOutput (m_debugger.GetOutputFileHandle()); 859 } 860 861 // Now we handle options we got from the command line 862 SBStream commands_stream; 863 864 // First source in the commands specified to be run before the file arguments are processed. 865 WriteInitialCommands(true, commands_stream); 866 867 const size_t num_args = m_option_data.m_args.size(); 868 if (num_args > 0) 869 { 870 char arch_name[64]; 871 if (m_debugger.GetDefaultArchitecture (arch_name, sizeof (arch_name))) 872 commands_stream.Printf("target create --arch=%s \"%s\"", arch_name, m_option_data.m_args[0].c_str()); 873 else 874 commands_stream.Printf("target create \"%s\"", m_option_data.m_args[0].c_str()); 875 876 if (!m_option_data.m_core_file.empty()) 877 { 878 commands_stream.Printf(" --core \"%s\"", m_option_data.m_core_file.c_str()); 879 } 880 commands_stream.Printf("\n"); 881 882 if (num_args > 1) 883 { 884 commands_stream.Printf ("settings set -- target.run-args "); 885 for (size_t arg_idx = 1; arg_idx < num_args; ++arg_idx) 886 { 887 const char *arg_cstr = m_option_data.m_args[arg_idx].c_str(); 888 if (strchr(arg_cstr, '"') == NULL) 889 commands_stream.Printf(" \"%s\"", arg_cstr); 890 else 891 commands_stream.Printf(" '%s'", arg_cstr); 892 } 893 commands_stream.Printf("\n"); 894 } 895 } 896 else if (!m_option_data.m_core_file.empty()) 897 { 898 commands_stream.Printf("target create --core \"%s\"\n", m_option_data.m_core_file.c_str()); 899 } 900 else if (!m_option_data.m_process_name.empty()) 901 { 902 commands_stream.Printf ("process attach --name \"%s\"", m_option_data.m_process_name.c_str()); 903 904 if (m_option_data.m_wait_for) 905 commands_stream.Printf(" --waitfor"); 906 907 commands_stream.Printf("\n"); 908 909 } 910 else if (LLDB_INVALID_PROCESS_ID != m_option_data.m_process_pid) 911 { 912 commands_stream.Printf ("process attach --pid %" PRIu64 "\n", m_option_data.m_process_pid); 913 } 914 915 WriteInitialCommands(false, commands_stream); 916 917 // Now that all option parsing is done, we try and parse the .lldbinit 918 // file in the current working directory 919 sb_interpreter.SourceInitFileInCurrentWorkingDirectory (result); 920 if (GetDebugMode()) 921 { 922 result.PutError(m_debugger.GetErrorFileHandle()); 923 result.PutOutput(m_debugger.GetOutputFileHandle()); 924 } 925 926 bool handle_events = true; 927 bool spawn_thread = false; 928 929 // Check if we have any data in the commands stream, and if so, save it to a temp file 930 // so we can then run the command interpreter using the file contents. 931 const char *commands_data = commands_stream.GetData(); 932 const size_t commands_size = commands_stream.GetSize(); 933 934 // The command file might have requested that we quit, this variable will track that. 935 bool quit_requested = false; 936 bool stopped_for_crash = false; 937 if (commands_data && commands_size) 938 { 939 enum PIPES { READ, WRITE }; // Constants 0 and 1 for READ and WRITE 940 941 bool success = true; 942 int fds[2] = { -1, -1 }; 943 int err = 0; 944 #ifdef _WIN32 945 err = _pipe(fds, commands_size, O_BINARY); 946 #else 947 err = pipe(fds); 948 #endif 949 if (err == 0) 950 { 951 ssize_t nrwr = write(fds[WRITE], commands_data, commands_size); 952 if (nrwr < 0) 953 { 954 fprintf(stderr, "error: write(%i, %p, %zd) failed (errno = %i) " 955 "when trying to open LLDB commands pipe\n", 956 fds[WRITE], commands_data, commands_size, errno); 957 success = false; 958 } 959 else if (static_cast<size_t>(nrwr) == commands_size) 960 { 961 // Close the write end of the pipe so when we give the read end to 962 // the debugger/command interpreter it will exit when it consumes all 963 // of the data 964 #ifdef _WIN32 965 _close(fds[WRITE]); fds[WRITE] = -1; 966 #else 967 close(fds[WRITE]); fds[WRITE] = -1; 968 #endif 969 // Now open the read file descriptor in a FILE * that we can give to 970 // the debugger as an input handle 971 FILE *commands_file = fdopen(fds[READ], "r"); 972 if (commands_file) 973 { 974 fds[READ] = -1; // The FILE * 'commands_file' now owns the read descriptor 975 // Hand ownership if the FILE * over to the debugger for "commands_file". 976 m_debugger.SetInputFileHandle (commands_file, true); 977 978 // Set the debugger into Sync mode when running the command file. Otherwise command files 979 // that run the target won't run in a sensible way. 980 bool old_async = m_debugger.GetAsync(); 981 m_debugger.SetAsync(false); 982 int num_errors; 983 984 SBCommandInterpreterRunOptions options; 985 options.SetStopOnError (true); 986 if (m_option_data.m_batch) 987 options.SetStopOnCrash (true); 988 989 m_debugger.RunCommandInterpreter(handle_events, 990 spawn_thread, 991 options, 992 num_errors, 993 quit_requested, 994 stopped_for_crash); 995 m_debugger.SetAsync(old_async); 996 } 997 else 998 { 999 fprintf(stderr, 1000 "error: fdopen(%i, \"r\") failed (errno = %i) when " 1001 "trying to open LLDB commands pipe\n", 1002 fds[READ], errno); 1003 success = false; 1004 } 1005 } 1006 else 1007 { 1008 assert(!"partial writes not handled"); 1009 success = false; 1010 } 1011 } 1012 else 1013 { 1014 fprintf(stderr, "error: can't create pipe file descriptors for LLDB commands\n"); 1015 success = false; 1016 } 1017 1018 // Close any pipes that we still have ownership of 1019 if ( fds[WRITE] != -1) 1020 { 1021 #ifdef _WIN32 1022 _close(fds[WRITE]); fds[WRITE] = -1; 1023 #else 1024 close(fds[WRITE]); fds[WRITE] = -1; 1025 #endif 1026 1027 } 1028 1029 if ( fds[READ] != -1) 1030 { 1031 #ifdef _WIN32 1032 _close(fds[READ]); fds[READ] = -1; 1033 #else 1034 close(fds[READ]); fds[READ] = -1; 1035 #endif 1036 } 1037 1038 // Something went wrong with command pipe 1039 if (!success) 1040 { 1041 exit(1); 1042 } 1043 1044 } 1045 1046 // Now set the input file handle to STDIN and run the command 1047 // interpreter again in interactive mode and let the debugger 1048 // take ownership of stdin 1049 1050 bool go_interactive = true; 1051 if (quit_requested) 1052 go_interactive = false; 1053 else if (m_option_data.m_batch && !stopped_for_crash) 1054 go_interactive = false; 1055 1056 if (go_interactive) 1057 { 1058 m_debugger.SetInputFileHandle (stdin, true); 1059 m_debugger.RunCommandInterpreter(handle_events, spawn_thread); 1060 } 1061 1062 reset_stdin_termios(); 1063 fclose (stdin); 1064 1065 SBDebugger::Destroy (m_debugger); 1066 } 1067 1068 1069 void 1070 Driver::ResizeWindow (unsigned short col) 1071 { 1072 GetDebugger().SetTerminalWidth (col); 1073 } 1074 1075 void 1076 sigwinch_handler (int signo) 1077 { 1078 struct winsize window_size; 1079 if (isatty (STDIN_FILENO) 1080 && ::ioctl (STDIN_FILENO, TIOCGWINSZ, &window_size) == 0) 1081 { 1082 if ((window_size.ws_col > 0) && g_driver != NULL) 1083 { 1084 g_driver->ResizeWindow (window_size.ws_col); 1085 } 1086 } 1087 } 1088 1089 void 1090 sigint_handler (int signo) 1091 { 1092 static bool g_interrupt_sent = false; 1093 if (g_driver) 1094 { 1095 if (!g_interrupt_sent) 1096 { 1097 g_interrupt_sent = true; 1098 g_driver->GetDebugger().DispatchInputInterrupt(); 1099 g_interrupt_sent = false; 1100 return; 1101 } 1102 } 1103 1104 exit (signo); 1105 } 1106 1107 void 1108 sigtstp_handler (int signo) 1109 { 1110 g_driver->GetDebugger().SaveInputTerminalState(); 1111 signal (signo, SIG_DFL); 1112 kill (getpid(), signo); 1113 signal (signo, sigtstp_handler); 1114 } 1115 1116 void 1117 sigcont_handler (int signo) 1118 { 1119 g_driver->GetDebugger().RestoreInputTerminalState(); 1120 signal (signo, SIG_DFL); 1121 kill (getpid(), signo); 1122 signal (signo, sigcont_handler); 1123 } 1124 1125 int 1126 main (int argc, char const *argv[], const char *envp[]) 1127 { 1128 #ifdef _MSC_VER 1129 // disable buffering on windows 1130 setvbuf(stdout, NULL, _IONBF, 0); 1131 setvbuf(stdin , NULL, _IONBF, 0); 1132 #endif 1133 1134 SBDebugger::Initialize(); 1135 1136 SBHostOS::ThreadCreated ("<lldb.driver.main-thread>"); 1137 1138 signal (SIGPIPE, SIG_IGN); 1139 signal (SIGWINCH, sigwinch_handler); 1140 signal (SIGINT, sigint_handler); 1141 signal (SIGTSTP, sigtstp_handler); 1142 signal (SIGCONT, sigcont_handler); 1143 1144 // Create a scope for driver so that the driver object will destroy itself 1145 // before SBDebugger::Terminate() is called. 1146 { 1147 Driver driver; 1148 1149 bool exiting = false; 1150 SBError error (driver.ParseArgs (argc, argv, stdout, exiting)); 1151 if (error.Fail()) 1152 { 1153 const char *error_cstr = error.GetCString (); 1154 if (error_cstr) 1155 ::fprintf (stderr, "error: %s\n", error_cstr); 1156 } 1157 else if (!exiting) 1158 { 1159 driver.MainLoop (); 1160 } 1161 } 1162 1163 SBDebugger::Terminate(); 1164 return 0; 1165 } 1166