1 //===-- source/Host/common/OptionParser.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 "lldb/Host/OptionParser.h" 11 #include "lldb/Host/HostGetOpt.h" 12 #include "lldb/lldb-private-types.h" 13 14 #include <vector> 15 16 using namespace lldb_private; 17 18 void OptionParser::Prepare(std::unique_lock<std::mutex> &lock) { 19 static std::mutex g_mutex; 20 lock = std::unique_lock<std::mutex>(g_mutex); 21 #ifdef __GLIBC__ 22 optind = 0; 23 #else 24 optreset = 1; 25 optind = 1; 26 #endif 27 } 28 29 void OptionParser::EnableError(bool error) { opterr = error ? 1 : 0; } 30 31 int OptionParser::Parse(int argc, char *const argv[], const char *optstring, 32 const Option *longopts, int *longindex) { 33 std::vector<option> opts; 34 while (longopts->definition != nullptr) { 35 option opt; 36 opt.flag = longopts->flag; 37 opt.val = longopts->val; 38 opt.name = longopts->definition->long_option; 39 opt.has_arg = longopts->definition->option_has_arg; 40 opts.push_back(opt); 41 ++longopts; 42 } 43 opts.push_back(option()); 44 return getopt_long_only(argc, argv, optstring, &opts[0], longindex); 45 } 46 47 char *OptionParser::GetOptionArgument() { return optarg; } 48 49 int OptionParser::GetOptionIndex() { return optind; } 50 51 int OptionParser::GetOptionErrorCause() { return optopt; } 52 53 std::string OptionParser::GetShortOptionString(struct option *long_options) { 54 std::string s; 55 int i = 0; 56 bool done = false; 57 while (!done) { 58 if (long_options[i].name == 0 && long_options[i].has_arg == 0 && 59 long_options[i].flag == 0 && long_options[i].val == 0) { 60 done = true; 61 } else { 62 if (long_options[i].flag == NULL && isalpha(long_options[i].val)) { 63 s.append(1, (char)long_options[i].val); 64 switch (long_options[i].has_arg) { 65 default: 66 case no_argument: 67 break; 68 69 case optional_argument: 70 s.append(2, ':'); 71 break; 72 case required_argument: 73 s.append(1, ':'); 74 break; 75 } 76 } 77 ++i; 78 } 79 } 80 return s; 81 } 82