1 //===-- source/Host/common/OptionParser.cpp -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "lldb/Host/OptionParser.h" 10 #include "lldb/Host/HostGetOpt.h" 11 #include "lldb/lldb-private-types.h" 12 13 #include <vector> 14 15 using namespace lldb_private; 16 17 void OptionParser::Prepare(std::unique_lock<std::mutex> &lock) { 18 static std::mutex g_mutex; 19 lock = std::unique_lock<std::mutex>(g_mutex); 20 #ifdef __GLIBC__ 21 optind = 0; 22 #else 23 optreset = 1; 24 optind = 1; 25 #endif 26 } 27 28 void OptionParser::EnableError(bool error) { opterr = error ? 1 : 0; } 29 30 int OptionParser::Parse(llvm::MutableArrayRef<char *> argv, 31 llvm::StringRef optstring, const Option *longopts, 32 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 std::string opt_cstr = std::string(optstring); 45 return getopt_long_only(argv.size() - 1, argv.data(), opt_cstr.c_str(), 46 &opts[0], longindex); 47 } 48 49 char *OptionParser::GetOptionArgument() { return optarg; } 50 51 int OptionParser::GetOptionIndex() { return optind; } 52 53 int OptionParser::GetOptionErrorCause() { return optopt; } 54 55 std::string OptionParser::GetShortOptionString(struct option *long_options) { 56 std::string s; 57 int i = 0; 58 bool done = false; 59 while (!done) { 60 if (long_options[i].name == nullptr && long_options[i].has_arg == 0 && 61 long_options[i].flag == nullptr && long_options[i].val == 0) { 62 done = true; 63 } else { 64 if (long_options[i].flag == nullptr && isalpha(long_options[i].val)) { 65 s.append(1, (char)long_options[i].val); 66 switch (long_options[i].has_arg) { 67 default: 68 case no_argument: 69 break; 70 71 case optional_argument: 72 s.append(2, ':'); 73 break; 74 case required_argument: 75 s.append(1, ':'); 76 break; 77 } 78 } 79 ++i; 80 } 81 } 82 return s; 83 } 84