1 //===-- Driver.cpp ----------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 #include "MICmnConfig.h"
13 #if MICONFIG_COMPILE_MIDRIVER_WITH_LLDBDRIVER
24 #include "Platform.h" // CODETAG_IOR_SIGNALS
28 #include <lldb\Host\windows\getopt\GetOptInc.h>
30 #include <lldb/API/SBBreakpoint.h>
31 #include <lldb/API/SBCommandInterpreter.h>
32 #include <lldb/API/SBCommandReturnObject.h>
33 #include <lldb/API/SBCommunication.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>
44 static void reset_stdin_termios();
45 static bool g_old_stdin_termios_is_valid = false;
46 static struct termios g_old_stdin_termios;
48 static char *g_debugger_name = (char *)"";
49 Driver *g_driver = NULL;
51 // In the Driver::MainLoop, we change the terminal settings. This function is
52 // added as an atexit handler to make sure we clean them up.
56 if (g_old_stdin_termios_is_valid)
58 g_old_stdin_termios_is_valid = false;
59 ::tcsetattr(STDIN_FILENO, TCSANOW, &g_old_stdin_termios);
65 uint32_t usage_mask; // Used to mark options that can be used together. If (1 << n & usage_mask) != 0
66 // then this option belongs to option set n.
67 bool required; // This option is required (in the current usage level)
68 const char *long_option; // Full name for this option.
69 int short_option; // Single character for this option.
70 int option_has_arg; // no_argument, required_argument or optional_argument
71 uint32_t completion_type; // Cookie the option class can use to do define the argument completion.
72 lldb::CommandArgumentType argument_type; // Type of argument this option takes
73 const char *usage_text; // Full text explaining what this options does and what (if any) argument to
77 #define LLDB_3_TO_5 LLDB_OPT_SET_3 | LLDB_OPT_SET_4 | LLDB_OPT_SET_5
78 #define LLDB_4_TO_5 LLDB_OPT_SET_4 | LLDB_OPT_SET_5
80 static OptionDefinition g_options[] = {
81 {LLDB_OPT_SET_1, true, "help", 'h', no_argument, 0, eArgTypeNone, "Prints out the usage information for the LLDB debugger."},
82 {LLDB_OPT_SET_2, true, "version", 'v', no_argument, 0, eArgTypeNone, "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_5, true, "attach-pid", 'p', required_argument, 0, eArgTypePid,
91 "Tells the debugger to attach to a process with the given pid."},
92 {LLDB_OPT_SET_4, true, "attach-name", 'n', required_argument, 0, eArgTypeProcessName,
93 "Tells the debugger to attach to a process with the given name."},
94 {LLDB_OPT_SET_4, true, "wait-for", 'w', no_argument, 0, eArgTypeNone,
95 "Tells the debugger to wait for a process with the given pid or name to launch before attaching."},
96 {LLDB_3_TO_5, false, "source", 's', required_argument, 0, eArgTypeFilename, "Tells the debugger to read in and execute the lldb "
97 "commands in the given file, after any file provided on "
98 "the command line has been loaded."},
99 {LLDB_3_TO_5, false, "one-line", 'o', required_argument, 0, eArgTypeNone,
100 "Tells the debugger to execute this one-line lldb command after any file provided on the command line has been loaded."},
101 {LLDB_3_TO_5, false, "source-before-file", 'S', required_argument, 0, eArgTypeFilename,
102 "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 "
104 {LLDB_3_TO_5, false, "one-line-before-file", 'O', required_argument, 0, eArgTypeNone,
105 "Tells the debugger to execute this one-line lldb command before any file provided on the command line has been loaded."},
106 {LLDB_3_TO_5, false, "source-quietly", 'Q', no_argument, 0, eArgTypeNone,
107 "Tells the debugger suppress output from commands provided in the -s, -S, -O and -o commands."},
108 {LLDB_3_TO_5, false, "editor", 'e', no_argument, 0, eArgTypeNone,
109 "Tells the debugger to open source files using the host's \"external editor\" mechanism."},
110 {LLDB_3_TO_5, false, "no-lldbinit", 'x', no_argument, 0, eArgTypeNone, "Do not automatically parse any '.lldbinit' files."},
111 {LLDB_3_TO_5, false, "no-use-colors", 'X', no_argument, 0, eArgTypeNone, "Do not use colors."},
112 {LLDB_OPT_SET_6, true, "python-path", 'P', no_argument, 0, eArgTypeNone,
113 "Prints out the path to the lldb.py file for this version of lldb."},
114 {LLDB_3_TO_5, false, "script-language", 'l', required_argument, 0, eArgTypeScriptLang,
115 "Tells the debugger to use the specified scripting language for user-defined scripts, rather than the default. "
116 "Valid scripting languages that can be specified include Python, Perl, Ruby and Tcl. Currently only the Python "
117 "extensions have been implemented."},
118 {LLDB_3_TO_5, false, "debug", 'd', no_argument, 0, eArgTypeNone,
119 "Tells the debugger to print out extra information for debugging itself."},
120 {0, false, NULL, 0, 0, 0, eArgTypeNone, NULL}};
122 static const uint32_t last_option_set_with_args = 2;
125 : SBBroadcaster("Driver")
126 , m_debugger(SBDebugger::Create(false))
129 // We want to be able to handle CTRL+D in the terminal to have it terminate
131 m_debugger.SetCloseInputOnEOF(false);
132 g_debugger_name = (char *)m_debugger.GetInstanceName();
133 if (g_debugger_name == NULL)
134 g_debugger_name = (char *)"";
141 g_debugger_name = NULL;
144 // This function takes INDENT, which tells how many spaces to output at the front
145 // of each line; TEXT, which is the text that is to be output. It outputs the
146 // text, on multiple lines if necessary, to RESULT, with INDENT spaces at the
147 // front of each line. It breaks lines on spaces, tabs or newlines, shortening
148 // the line if necessary to not break in the middle of a word. It assumes that
149 // each output line should contain a maximum of OUTPUT_MAX_COLUMNS characters.
152 OutputFormattedUsageText(FILE *out, int indent, const char *text, int output_max_columns)
154 int len = strlen(text);
155 std::string text_string(text);
157 // Force indentation to be reasonable.
158 if (indent >= output_max_columns)
161 // Will it all fit on one line?
163 if (len + indent < output_max_columns)
164 // Output as a single line
165 fprintf(out, "%*s%s\n", indent, "", text);
168 // We need to break it up into multiple lines.
169 int text_width = output_max_columns - indent - 1;
175 while (end < final_end)
177 // Dont start the 'text' on a space, since we're already outputting the indentation.
178 while ((start < final_end) && (text[start] == ' '))
181 end = start + text_width;
186 // If we're not at the end of the text, make sure we break the line on white space.
187 while (end > start && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
190 sub_len = end - start;
191 std::string substring = text_string.substr(start, sub_len);
192 fprintf(out, "%*s%s\n", indent, "", substring.c_str());
199 ShowUsage(FILE *out, OptionDefinition *option_table, Driver::OptionData data)
201 uint32_t screen_width = 80;
202 uint32_t indent_level = 0;
203 const char *name = "lldb";
205 fprintf(out, "\nUsage:\n\n");
209 // First, show each usage level set of options, e.g. <cmd> [options-for-level-0]
210 // <cmd> [options-for-level-1]
213 uint32_t num_options;
214 uint32_t num_option_sets = 0;
216 for (num_options = 0; option_table[num_options].long_option != NULL; ++num_options)
218 uint32_t this_usage_mask = option_table[num_options].usage_mask;
219 if (this_usage_mask == LLDB_OPT_SET_ALL)
221 if (num_option_sets == 0)
226 for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++)
228 if (this_usage_mask & 1 << j)
230 if (num_option_sets <= j)
231 num_option_sets = j + 1;
237 for (uint32_t opt_set = 0; opt_set < num_option_sets; opt_set++)
239 uint32_t opt_set_mask;
241 opt_set_mask = 1 << opt_set;
245 fprintf(out, "%*s%s", indent_level, "", name);
246 bool is_help_line = false;
248 for (uint32_t i = 0; i < num_options; ++i)
250 if (option_table[i].usage_mask & opt_set_mask)
252 CommandArgumentType arg_type = option_table[i].argument_type;
253 const char *arg_name = SBCommandInterpreter::GetArgumentTypeAsCString(arg_type);
254 // This is a bit of a hack, but there's no way to say certain options don't have arguments yet...
255 // so we do it by hand here.
256 if (option_table[i].short_option == 'h')
259 if (option_table[i].required)
261 if (option_table[i].option_has_arg == required_argument)
262 fprintf(out, " -%c <%s>", option_table[i].short_option, arg_name);
263 else if (option_table[i].option_has_arg == optional_argument)
264 fprintf(out, " -%c [<%s>]", option_table[i].short_option, arg_name);
266 fprintf(out, " -%c", option_table[i].short_option);
270 if (option_table[i].option_has_arg == required_argument)
271 fprintf(out, " [-%c <%s>]", option_table[i].short_option, arg_name);
272 else if (option_table[i].option_has_arg == optional_argument)
273 fprintf(out, " [-%c [<%s>]]", option_table[i].short_option, arg_name);
275 fprintf(out, " [-%c]", option_table[i].short_option);
279 if (!is_help_line && (opt_set <= last_option_set_with_args))
280 fprintf(out, " [[--] <PROGRAM-ARG-1> [<PROGRAM_ARG-2> ...]]");
283 fprintf(out, "\n\n");
285 // Now print out all the detailed information about the various options: long form, short form and help text:
286 // -- long_name <argument>
287 // - short <argument>
290 // This variable is used to keep track of which options' info we've printed out, because some options can be in
291 // more than one usage level, but we only want to print the long form of its information once.
293 Driver::OptionData::OptionSet options_seen;
294 Driver::OptionData::OptionSet::iterator pos;
298 for (uint32_t i = 0; i < num_options; ++i)
300 // Only print this option if we haven't already seen it.
301 pos = options_seen.find(option_table[i].short_option);
302 if (pos == options_seen.end())
304 CommandArgumentType arg_type = option_table[i].argument_type;
305 const char *arg_name = SBCommandInterpreter::GetArgumentTypeAsCString(arg_type);
307 options_seen.insert(option_table[i].short_option);
308 fprintf(out, "%*s-%c ", indent_level, "", option_table[i].short_option);
309 if (arg_type != eArgTypeNone)
310 fprintf(out, "<%s>", arg_name);
312 fprintf(out, "%*s--%s ", indent_level, "", option_table[i].long_option);
313 if (arg_type != eArgTypeNone)
314 fprintf(out, "<%s>", arg_name);
317 OutputFormattedUsageText(out, indent_level, option_table[i].usage_text, screen_width);
325 fprintf(out, "\n%*sNotes:\n", indent_level, "");
328 fprintf(out, "\n%*sMultiple \"-s\" and \"-o\" options can be provided. They will be processed from left to right in order, "
329 "\n%*swith the source files and commands interleaved. The same is true of the \"-S\" and \"-O\" options."
330 "\n%*sThe before file and after file sets can intermixed freely, the command parser will sort them out."
331 "\n%*sThe order of the file specifiers (\"-c\", \"-f\", etc.) is not significant in this regard.\n\n",
332 indent_level, "", indent_level, "", indent_level, "", indent_level, "");
334 fprintf(out, "\n%*sIf you don't provide -f then the first argument will be the file to be debugged"
335 "\n%*swhich means that '%s -- <filename> [<ARG1> [<ARG2>]]' also works."
336 "\n%*sBut remember to end the options with \"--\" if any of your arguments have a \"-\" in them.\n\n",
337 indent_level, "", indent_level, "", name, indent_level, "");
341 BuildGetOptTable(OptionDefinition *expanded_option_table, std::vector<struct option> &getopt_table, uint32_t num_options)
343 if (num_options == 0)
348 std::bitset<256> option_seen;
350 getopt_table.resize(num_options + 1);
352 for (i = 0, j = 0; i < num_options; ++i)
354 char short_opt = expanded_option_table[i].short_option;
356 if (option_seen.test(short_opt) == false)
358 getopt_table[j].name = expanded_option_table[i].long_option;
359 getopt_table[j].has_arg = expanded_option_table[i].option_has_arg;
360 getopt_table[j].flag = NULL;
361 getopt_table[j].val = expanded_option_table[i].short_option;
362 option_seen.set(short_opt);
367 getopt_table[j].name = NULL;
368 getopt_table[j].has_arg = 0;
369 getopt_table[j].flag = NULL;
370 getopt_table[j].val = 0;
373 Driver::OptionData::OptionData()
375 , m_script_lang(lldb::eScriptLanguageDefault)
378 , m_initial_commands()
379 , m_after_file_commands()
380 , m_debug_mode(false)
381 , m_source_quietly(false)
382 , m_print_version(false)
383 , m_print_python_path(false)
384 , m_print_help(false)
387 , m_process_pid(LLDB_INVALID_PROCESS_ID)
388 , m_use_external_editor(false)
393 Driver::OptionData::~OptionData()
398 Driver::OptionData::Clear()
401 m_script_lang = lldb::eScriptLanguageDefault;
402 m_initial_commands.clear();
403 m_after_file_commands.clear();
404 m_debug_mode = false;
405 m_source_quietly = false;
406 m_print_help = false;
407 m_print_version = false;
408 m_print_python_path = false;
409 m_use_external_editor = false;
411 m_process_name.erase();
412 m_process_pid = LLDB_INVALID_PROCESS_ID;
416 Driver::OptionData::AddInitialCommand(const char *command, bool before_file, bool is_file, SBError &error)
418 std::vector<std::pair<bool, std::string>> *command_set;
420 command_set = &(m_initial_commands);
422 command_set = &(m_after_file_commands);
426 SBFileSpec file(command);
428 command_set->push_back(std::pair<bool, std::string>(true, optarg));
429 else if (file.ResolveExecutableLocation())
431 char final_path[PATH_MAX];
432 file.GetPath(final_path, sizeof(final_path));
433 std::string path_str(final_path);
434 command_set->push_back(std::pair<bool, std::string>(true, path_str));
437 error.SetErrorStringWithFormat("file specified in --source (-s) option doesn't exist: '%s'", optarg);
440 command_set->push_back(std::pair<bool, std::string>(false, optarg));
444 Driver::ResetOptionValues()
446 m_option_data.Clear();
450 Driver::GetFilename() const
452 if (m_option_data.m_args.empty())
454 return m_option_data.m_args.front().c_str();
458 Driver::GetCrashLogFilename() const
460 if (m_option_data.m_crash_log.empty())
462 return m_option_data.m_crash_log.c_str();
466 Driver::GetScriptLanguage() const
468 return m_option_data.m_script_lang;
472 Driver::ExecuteInitialCommands(bool before_file)
475 std::vector<std::pair<bool, std::string>> *command_set;
477 command_set = &(m_option_data.m_initial_commands);
479 command_set = &(m_option_data.m_after_file_commands);
481 num_commands = command_set->size();
482 SBCommandReturnObject result;
483 bool old_async = GetDebugger().GetAsync();
484 GetDebugger().SetAsync(false);
485 for (size_t idx = 0; idx < num_commands; idx++)
487 bool is_file = (*command_set)[idx].first;
488 const char *command = (*command_set)[idx].second.c_str();
489 char command_string[PATH_MAX * 2];
490 const bool dump_stream_only_if_no_immediate = true;
491 const char *executed_command = command;
494 ::snprintf(command_string, sizeof(command_string), "command source -s %i '%s'", m_option_data.m_source_quietly, command);
495 executed_command = command_string;
498 m_debugger.GetCommandInterpreter().HandleCommand(executed_command, result, false);
499 if (!m_option_data.m_source_quietly || result.Succeeded() == false)
501 const size_t output_size = result.GetOutputSize();
504 const char *cstr = result.GetOutput(dump_stream_only_if_no_immediate);
508 const size_t error_size = result.GetErrorSize();
511 const char *cstr = result.GetError(dump_stream_only_if_no_immediate);
517 if (result.Succeeded() == false)
519 const char *type = before_file ? "before file" : "after_file";
521 ::fprintf(stderr, "Aborting %s command execution, command file: '%s' failed.\n", type, command);
523 ::fprintf(stderr, "Aborting %s command execution, command: '%s' failed.\n", type, command);
528 GetDebugger().SetAsync(old_async);
532 Driver::GetDebugMode() const
534 return m_option_data.m_debug_mode;
537 // Check the arguments that were passed to this program to make sure they are valid and to get their
538 // argument values (if any). Return a boolean value indicating whether or not to start up the full
539 // debugger (i.e. the Command Interpreter) or not. Return FALSE if the arguments were invalid OR
540 // if the user only wanted help or version information.
543 Driver::ParseArgs(int argc, const char *argv[], FILE *out_fh, bool &exiting)
547 SBCommandReturnObject result;
550 std::string option_string;
551 struct option *long_options = NULL;
552 std::vector<struct option> long_options_vector;
553 uint32_t num_options;
555 for (num_options = 0; g_options[num_options].long_option != NULL; ++num_options)
558 if (num_options == 0)
561 error.SetErrorStringWithFormat("invalid number of options");
565 BuildGetOptTable(g_options, long_options_vector, num_options);
567 if (long_options_vector.empty())
570 long_options = &long_options_vector.front();
572 if (long_options == NULL)
574 error.SetErrorStringWithFormat("invalid long options");
578 // Build the option_string argument for call to getopt_long_only.
580 for (int i = 0; long_options[i].name != NULL; ++i)
582 if (long_options[i].flag == NULL)
584 option_string.push_back((char)long_options[i].val);
585 switch (long_options[i].has_arg)
590 case required_argument:
591 option_string.push_back(':');
593 case optional_argument:
594 option_string.append("::");
600 // This is kind of a pain, but since we make the debugger in the Driver's constructor, we can't
601 // know at that point whether we should read in init files yet. So we don't read them in in the
602 // Driver constructor, then set the flags back to "read them in" here, and then if we see the
603 // "-n" flag, we'll turn it off again. Finally we have to read them in by hand later in the
606 m_debugger.SkipLLDBInitFiles(false);
607 m_debugger.SkipAppInitFiles(false);
609 // Prepare for & make calls to getopt_long_only.
619 int long_options_index = -1;
620 val = ::getopt_long_only(argc, const_cast<char **>(argv), option_string.c_str(), long_options, &long_options_index);
626 m_option_data.m_print_help = true;
627 error.SetErrorStringWithFormat("unknown or ambiguous option");
634 m_option_data.m_seen_options.insert((char)val);
635 if (long_options_index == -1)
637 for (int i = 0; long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val; ++i)
639 if (long_options[i].val == val)
641 long_options_index = i;
647 if (long_options_index >= 0)
649 const int short_option = g_options[long_options_index].short_option;
651 switch (short_option)
654 m_option_data.m_print_help = true;
658 m_option_data.m_print_version = true;
662 m_option_data.m_print_python_path = true;
667 SBFileSpec file(optarg);
670 m_option_data.m_core_file = optarg;
673 error.SetErrorStringWithFormat("file specified in --core (-c) option doesn't exist: '%s'", optarg);
678 m_option_data.m_use_external_editor = true;
682 m_debugger.SkipLLDBInitFiles(true);
683 m_debugger.SkipAppInitFiles(true);
687 m_debugger.SetUseColor(false);
692 SBFileSpec file(optarg);
695 m_option_data.m_args.push_back(optarg);
697 else if (file.ResolveExecutableLocation())
700 file.GetPath(path, sizeof(path));
701 m_option_data.m_args.push_back(path);
704 error.SetErrorStringWithFormat("file specified in --file (-f) option doesn't exist: '%s'", optarg);
709 if (!m_debugger.SetDefaultArchitecture(optarg))
710 error.SetErrorStringWithFormat("invalid architecture in the -a or --arch option: '%s'", optarg);
714 m_option_data.m_script_lang = m_debugger.GetScriptingLanguage(optarg);
718 m_option_data.m_debug_mode = true;
722 m_option_data.m_source_quietly = true;
726 m_option_data.m_process_name = optarg;
730 m_option_data.m_wait_for = true;
736 m_option_data.m_process_pid = strtol(optarg, &remainder, 0);
737 if (remainder == optarg || *remainder != '\0')
738 error.SetErrorStringWithFormat("Could not convert process PID: \"%s\" into a pid.", optarg);
742 m_option_data.AddInitialCommand(optarg, false, true, error);
745 m_option_data.AddInitialCommand(optarg, false, false, error);
748 m_option_data.AddInitialCommand(optarg, true, true, error);
751 m_option_data.AddInitialCommand(optarg, true, false, error);
754 m_option_data.m_print_help = true;
755 error.SetErrorStringWithFormat("unrecognized option %c", short_option);
761 error.SetErrorStringWithFormat("invalid option with value %i", val);
770 if (error.Fail() || m_option_data.m_print_help)
772 ShowUsage(out_fh, g_options, m_option_data);
775 else if (m_option_data.m_print_version)
777 ::fprintf(out_fh, "%s\n", m_debugger.GetVersionString());
780 else if (m_option_data.m_print_python_path)
782 SBFileSpec python_file_spec = SBHostOS::GetLLDBPythonPath();
783 if (python_file_spec.IsValid())
785 char python_path[PATH_MAX];
786 size_t num_chars = python_file_spec.GetPath(python_path, PATH_MAX);
787 if (num_chars < PATH_MAX)
789 ::fprintf(out_fh, "%s\n", python_path);
792 ::fprintf(out_fh, "<PATH TOO LONG>\n");
795 ::fprintf(out_fh, "<COULD NOT FIND PATH>\n");
798 else if (m_option_data.m_process_name.empty() && m_option_data.m_process_pid == LLDB_INVALID_PROCESS_ID)
800 // Any arguments that are left over after option parsing are for
801 // the program. If a file was specified with -f then the filename
802 // is already in the m_option_data.m_args array, and any remaining args
803 // are arguments for the inferior program. If no file was specified with
804 // -f, then what is left is the program name followed by any arguments.
806 // Skip any options we consumed with getopt_long_only
812 for (int arg_idx = 0; arg_idx < argc; ++arg_idx)
814 const char *arg = argv[arg_idx];
816 m_option_data.m_args.push_back(arg);
822 // Skip any options we consumed with getopt_long_only
824 // argv += optind; // Commented out to keep static analyzer happy
827 ::fprintf(out_fh, "Warning: program arguments are ignored when attaching.\n");
836 if (::tcgetattr(STDIN_FILENO, &g_old_stdin_termios) == 0)
838 g_old_stdin_termios_is_valid = true;
839 atexit(reset_stdin_termios);
842 ::setbuf(stdin, NULL);
843 ::setbuf(stdout, NULL);
845 m_debugger.SetErrorFileHandle(stderr, false);
846 m_debugger.SetOutputFileHandle(stdout, false);
847 m_debugger.SetInputFileHandle(stdin, true);
849 m_debugger.SetUseExternalEditor(m_option_data.m_use_external_editor);
851 struct winsize window_size;
852 if (isatty(STDIN_FILENO) && ::ioctl(STDIN_FILENO, TIOCGWINSZ, &window_size) == 0)
854 if (window_size.ws_col > 0)
855 m_debugger.SetTerminalWidth(window_size.ws_col);
858 SBCommandInterpreter sb_interpreter = m_debugger.GetCommandInterpreter();
860 // Before we handle any options from the command line, we parse the
861 // .lldbinit file in the user's home directory.
862 SBCommandReturnObject result;
863 sb_interpreter.SourceInitFileInHomeDirectory(result);
866 result.PutError(m_debugger.GetErrorFileHandle());
867 result.PutOutput(m_debugger.GetOutputFileHandle());
870 // Now we handle options we got from the command line
871 // First source in the commands specified to be run before the file arguments are processed.
872 ExecuteInitialCommands(true);
874 // Was there a core file specified?
875 std::string core_file_spec("");
876 if (!m_option_data.m_core_file.empty())
877 core_file_spec.append("--core ").append(m_option_data.m_core_file);
879 char command_string[PATH_MAX * 2];
880 const size_t num_args = m_option_data.m_args.size();
884 if (m_debugger.GetDefaultArchitecture(arch_name, sizeof(arch_name)))
885 ::snprintf(command_string, sizeof(command_string), "target create --arch=%s %s \"%s\"", arch_name, core_file_spec.c_str(),
886 m_option_data.m_args[0].c_str());
888 ::snprintf(command_string, sizeof(command_string), "target create %s \"%s\"", core_file_spec.c_str(),
889 m_option_data.m_args[0].c_str());
891 m_debugger.HandleCommand(command_string);
895 m_debugger.HandleCommand("settings clear target.run-args");
897 for (size_t arg_idx = 1; arg_idx < num_args; ++arg_idx)
899 ::snprintf(arg_cstr, sizeof(arg_cstr), "settings append target.run-args \"%s\"", m_option_data.m_args[arg_idx].c_str());
900 m_debugger.HandleCommand(arg_cstr);
904 else if (!core_file_spec.empty())
906 ::snprintf(command_string, sizeof(command_string), "target create %s", core_file_spec.c_str());
907 m_debugger.HandleCommand(command_string);
910 else if (!m_option_data.m_process_name.empty())
912 ::snprintf(command_string, sizeof(command_string), "process attach --name '%s'%s", m_option_data.m_process_name.c_str(),
913 m_option_data.m_wait_for ? " --waitfor" : "");
914 m_debugger.HandleCommand(command_string);
916 else if (LLDB_INVALID_PROCESS_ID != m_option_data.m_process_pid)
918 ::snprintf(command_string, sizeof(command_string), "process attach --pid %" PRIu64, m_option_data.m_process_pid);
919 m_debugger.HandleCommand(command_string);
922 ExecuteInitialCommands(false);
924 // Now that all option parsing is done, we try and parse the .lldbinit
925 // file in the current working directory
926 sb_interpreter.SourceInitFileInCurrentWorkingDirectory(result);
929 result.PutError(m_debugger.GetErrorFileHandle());
930 result.PutOutput(m_debugger.GetOutputFileHandle());
933 bool handle_events = true;
934 bool spawn_thread = false;
935 m_debugger.RunCommandInterpreter(handle_events, spawn_thread);
937 reset_stdin_termios();
940 SBDebugger::Destroy(m_debugger);
944 Driver::ResizeWindow(unsigned short col)
946 GetDebugger().SetTerminalWidth(col);
949 //++ ------------------------------------------------------------------------------------
950 // Details: Setup *this driver so it works as pass through (child) driver for the MI
951 // driver. Called by the parent (MI driver) driver.
952 // This driver has setup code in two places. The original in MainLoop() and
953 // in int main() (when MICONFIG_COMPILE_MIDRIVER_VERSION == 0) so that code can
954 // remain as much near to the original code as possible. If MI driver is the main
955 // driver (when MICONFIG_COMPILE_MIDRIVER_VERSION == 1) then this function is
956 // used to set up the Driver to work with the MI driver.
958 // Args: vwErrMsg - (W) On failure current error discription.
959 // Return: MIstatus::success - Functional succeeded.
960 // MIstatus::failure - Functional failed.
964 Driver::MISetup(CMIUtilString &vwErrMsg)
966 bool bOk = MIstatus::success;
968 // Is *this driver a pass through driver to the MI driver
969 CMIDriverBase *pParent = GetDriversParent();
970 if (pParent == nullptr)
973 // If MI is the main driver (which passes through to *this driver) then
974 // *this driver needs to be initialized after MI is initialize to have a valid
975 // pointer to the parent driver. *this is the parent's pass thru driver.
976 assert(pParent == nullptr);
977 return MIstatus::success; // Allow success for if Driver is the main driver
980 // MI driver may have streams it wants *this driver to use - still to be sorted
981 m_debugger.SetErrorFileHandle(pParent->GetStderr(), false); // MI may redirect to its own stream
982 m_debugger.SetOutputFileHandle(pParent->GetStdout(), false); // MI likely to NULL this
983 m_debugger.SetInputFileHandle(pParent->GetStdin(), false); // MI could use this to feed input
985 // ToDo: Do I need this?
986 m_debugger.SetUseExternalEditor(m_option_data.m_use_external_editor);
988 // ToDo: Do I need this?
989 struct winsize window_size;
990 if (isatty(STDIN_FILENO) && ::ioctl(STDIN_FILENO, TIOCGWINSZ, &window_size) == 0)
992 if (window_size.ws_col > 0)
993 m_debugger.SetTerminalWidth(window_size.ws_col);
999 //++ ------------------------------------------------------------------------------------
1000 // Details: Initialize setup *this driver ready for use.
1001 // Type: Overridden.
1003 // Return: MIstatus::success - Functional succeeded.
1004 // MIstatus::failure - Functional failed.
1008 Driver::DoInitialize(void)
1011 return MIstatus::success;
1014 //++ ------------------------------------------------------------------------------------
1015 // Details: Unbind detach or release resources used by *this driver.
1016 // Type: Overridden.
1018 // Return: MIstatus::success - Functional succeeded.
1019 // MIstatus::failure - Functional failed.
1023 Driver::DoShutdown(void)
1025 SBDebugger::Destroy(m_debugger);
1027 // Is *this driver a pass through driver to the MI driver
1028 CMIDriverBase *pParent = GetDriversParent();
1029 if (pParent == nullptr)
1031 // See DoInitialize().
1032 assert(pParent == nullptr);
1033 return MIstatus::success;
1036 // Put stuff here when *this driver is a pass thru driver to the MI driver
1038 return MIstatus::success;
1041 //++ ------------------------------------------------------------------------------------
1042 // Details: Retrieve the name for *this driver.
1043 // Type: Overridden.
1045 // Return: CMIUtilString & - Driver name.
1048 const CMIUtilString &
1049 Driver::GetName(void) const
1051 static CMIUtilString name("LLDB driver");
1055 //++ ------------------------------------------------------------------------------------
1056 // Details: Retrieve *this driver's last error condition.
1057 // Type: Overridden.
1059 // Return: CMIUtilString - Text description.
1063 Driver::GetError(void) const
1065 // Do nothing - to implement
1066 return CMIUtilString();
1069 //++ ------------------------------------------------------------------------------------
1070 // Details: Call this function puts *this driver to work.
1071 // Type: Overridden.
1073 // Return: MIstatus::success - Functional succeeded.
1074 // MIstatus::failure - Functional failed.
1078 Driver::DoMainLoop(void)
1082 return MIstatus::success;
1085 //++ ------------------------------------------------------------------------------------
1086 // Details: Call *this driver to resize the console window.
1087 // Type: Overridden.
1088 // Args: vTermWidth - (R) New window column size.
1089 // Return: MIstatus::success - Functional succeeded.
1090 // MIstatus::failure - Functional failed.
1094 Driver::DoResizeWindow(const uint32_t vTermWidth)
1096 ResizeWindow((unsigned short)vTermWidth);
1099 //++ ------------------------------------------------------------------------------------
1100 // Details: Call *this driver to return it's debugger.
1101 // Type: Overridden.
1103 // Return: lldb::SBDebugger & - LLDB debugger object reference.
1107 Driver::GetTheDebugger(void)
1109 return GetDebugger();
1112 //++ ------------------------------------------------------------------------------------
1113 // Details: Proxy function to allow the driver implementation to validate executable
1114 // command line arguments.
1115 // Type: Overrideable.
1116 // Args: argc - (R) An integer that contains the count of arguments that follow in
1117 // argv. The argc parameter is always greater than or equal to 1.
1118 // argv - (R) An array of null-terminated strings representing command-line
1119 // arguments entered by the user of the program. By convention,
1120 // argv[0] is the command with which the program is invoked.
1121 // vpStdOut - (R) Pointer to a standard output stream.
1122 // vwbExiting - (W) True = *this want to exit, Reasons: help, invalid arg(s),
1123 // version information only.
1124 // False = Continue to work, start debugger i.e. Command
1126 // Return: lldb::SBError - LLDB current error status.
1130 Driver::DoParseArgs(const int argc, const char *argv[], FILE *vpStdOut, bool &vwbExiting)
1132 return ParseArgs(argc, argv, vpStdOut, vwbExiting);
1135 //++ ------------------------------------------------------------------------------------
1136 // Details: A client can ask if *this driver is GDB/MI compatible.
1137 // Type: Overridden.
1139 // Return: True - GBD/MI compatible LLDB front end.
1140 // False - Not GBD/MI compatible LLDB front end.
1144 Driver::GetDriverIsGDBMICompatibleDriver(void) const
1149 //++ ------------------------------------------------------------------------------------
1150 // Details: This function allows *this driver to call on another driver to perform work
1151 // should this driver not be able to handle the client data input.
1152 // SetDriverToFallThruTo() specifies the fall through to driver.
1153 // Check the error message if the function returns a failure.
1154 // Type: Overridden.
1155 // Args: vCmd - (R) Command instruction to interpret.
1156 // vwErrMsg - (W) Error description on command failing.
1157 // Return: MIstatus::success - Command succeeded.
1158 // MIstatus::failure - Command failed.
1162 Driver::DoFallThruToAnotherDriver(const CMIUtilString &vCmd, CMIUtilString &vwErrMsg)
1164 bool bOk = MIstatus::success;
1167 // ToDo: Implement do work on other driver after this driver said "Give up you try"
1168 // This may nto be required if the feature to 'fall through' is not required
1169 SBCommandReturnObject returnObj = lldb::SBCommandReturnObject();
1170 SBCommandInterpreter cmdIntrp = m_debugger.GetCommandInterpreter();
1171 const lldb::ReturnStatus cmdResult = cmdIntrp.HandleCommand(vCmd.c_str(), returnObj);
1172 MIunused(cmdResult);
1173 if (returnObj.Succeeded() == false)
1175 bOk = MIstatus::failure;
1176 vwErrMsg = returnObj.GetError();
1182 //++ ------------------------------------------------------------------------------------
1183 // Details: This function allows *this driver to call functionality on the parent driver
1184 // ask for information for example.
1185 // Type: Overridden.
1186 // Args: vrOtherDriver - (R) Reference to another driver object.
1187 // Return: MIstatus::success - Functional succeeded.
1188 // MIstatus::failure - Functional failed.
1192 Driver::SetDriverParent(const CMIDriverBase &vrOtherDriver)
1194 m_pDriverParent = const_cast<CMIDriverBase *>(&vrOtherDriver);
1196 return MIstatus::success;
1199 //++ ------------------------------------------------------------------------------------
1200 // Details: Set a unique ID for *this driver. It cannot be empty.
1201 // Type: Overridden.
1202 // Args: vId - (R) Text description.
1203 // Return: MIstatus::success - Functional succeeded.
1204 // MIstatus::failure - Functional failed.
1208 Driver::SetId(const CMIUtilString &vId)
1212 // Invalid to have it empty
1213 return MIstatus::failure;
1216 m_strDriverId = vId;
1217 return MIstatus::success;
1220 //++ ------------------------------------------------------------------------------------
1221 // Details: Get the unique ID for *this driver.
1222 // Type: Overridden.
1224 // Return: CMIUtilString & - Text description.
1227 const CMIUtilString &
1228 Driver::GetId(void) const
1230 return m_strDriverId;
1233 //++ ------------------------------------------------------------------------------------
1234 // Details: Create *this driver. Function contains functionality that needs to be called
1235 // prior to constructing the *this driver.
1236 // Type: Static method.
1238 // Return: Driver * - Ptr to the LLDB driver object.
1242 Driver::CreateSelf(void)
1244 lldb::SBDebugger::Initialize();
1246 Driver *pDriver = new Driver;
1250 //++ ------------------------------------------------------------------------------------
1251 // Details: Retrieve the name for *this driver.
1252 // Type: Overridden.
1254 // Return: CMIUtilString - Driver name.
1257 const CMIUtilString &
1258 Driver::GetDriverName(void) const
1263 //++ ------------------------------------------------------------------------------------
1264 // Details: Get the unique ID for *this driver.
1265 // Type: Overridden.
1267 // Return: CMIUtilString & - Text description.
1270 const CMIUtilString &
1271 Driver::GetDriverId(void) const
1276 #endif // MICONFIG_COMPILE_MIDRIVER_WITH_LLDBDRIVER