getopt.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. /*
  2. * Copyright (c) 2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/StringView.h>
  27. #include <AK/Vector.h>
  28. #include <getopt.h>
  29. #include <stdio.h>
  30. #include <string.h>
  31. #include <unistd.h>
  32. int opterr = 1;
  33. int optopt = 0;
  34. int optind = 1;
  35. int optreset = 0;
  36. char* optarg = nullptr;
  37. // POSIX says, "When an element of argv[] contains multiple option characters,
  38. // it is unspecified how getopt() determines which options have already been
  39. // processed". Well, this is how we do it.
  40. static size_t s_index_into_multioption_argument = 0;
  41. static inline void report_error(const char* format, ...)
  42. {
  43. if (!opterr)
  44. return;
  45. fputs("\033[31m", stderr);
  46. va_list ap;
  47. va_start(ap, format);
  48. vfprintf(stderr, format, ap);
  49. va_end(ap);
  50. fputs("\033[0m\n", stderr);
  51. }
  52. namespace {
  53. class OptionParser {
  54. public:
  55. OptionParser(int argc, char* const* argv, const StringView& short_options, const option* long_options, int* out_long_option_index = nullptr);
  56. ~OptionParser();
  57. int getopt();
  58. private:
  59. bool lookup_short_option(char option, int& needs_value) const;
  60. int handle_short_option();
  61. const option* lookup_long_option(char* raw) const;
  62. int handle_long_option();
  63. void shift_argv();
  64. bool find_next_option();
  65. size_t m_argc { 0 };
  66. char** m_argv { nullptr };
  67. StringView m_short_options;
  68. const option* m_long_options { nullptr };
  69. int* m_out_long_option_index { nullptr };
  70. bool m_stop_on_first_non_option { false };
  71. size_t m_arg_index { 0 };
  72. size_t m_consumed_args { 0 };
  73. };
  74. OptionParser::OptionParser(int argc, char* const* argv, const StringView& short_options, const option* long_options, int* out_long_option_index)
  75. : m_argc(argc)
  76. , m_short_options(short_options)
  77. , m_long_options(long_options)
  78. , m_out_long_option_index(out_long_option_index)
  79. {
  80. m_argv = new char*[m_argc + 1];
  81. memmove(m_argv, argv, sizeof(char*) * (m_argc + 1));
  82. // In the following case:
  83. // $ foo bar -o baz
  84. // we want to parse the option (-o baz) first, and leave the argument (bar)
  85. // in argv after we return -1 when invoked the second time. So we reorder
  86. // argv to put options first and positional arguments next. To turn this
  87. // behavior off, start the short options spec with a "+". This is a GNU
  88. // extension that we support.
  89. m_stop_on_first_non_option = short_options.starts_with('+');
  90. // See if we should reset the internal state.
  91. if (optreset || optind == 0) {
  92. optreset = 0;
  93. optind = 1;
  94. s_index_into_multioption_argument = 0;
  95. }
  96. optopt = 0;
  97. optarg = nullptr;
  98. }
  99. OptionParser::~OptionParser()
  100. {
  101. delete[] m_argv;
  102. }
  103. int OptionParser::getopt()
  104. {
  105. bool should_reorder_argv = !m_stop_on_first_non_option;
  106. int res = -1;
  107. bool found_an_option = find_next_option();
  108. StringView arg = m_argv[m_arg_index];
  109. if (!found_an_option) {
  110. res = -1;
  111. if (arg == "--")
  112. m_consumed_args = 1;
  113. else
  114. m_consumed_args = 0;
  115. } else {
  116. // Alright, so we have an option on our hands!
  117. bool is_long_option = arg.starts_with("--");
  118. if (is_long_option)
  119. res = handle_long_option();
  120. else
  121. res = handle_short_option();
  122. // If we encountered an error, return immediately.
  123. if (res == '?')
  124. return '?';
  125. }
  126. if (should_reorder_argv)
  127. shift_argv();
  128. else
  129. VERIFY(optind == static_cast<int>(m_arg_index));
  130. optind += m_consumed_args;
  131. return res;
  132. }
  133. bool OptionParser::lookup_short_option(char option, int& needs_value) const
  134. {
  135. Vector<StringView> parts = m_short_options.split_view(option, true);
  136. VERIFY(parts.size() <= 2);
  137. if (parts.size() < 2) {
  138. // Haven't found the option in the spec.
  139. return false;
  140. }
  141. if (parts[1].starts_with("::")) {
  142. // If an option is followed by two colons, it optionally accepts an
  143. // argument.
  144. needs_value = optional_argument;
  145. } else if (parts[1].starts_with(':')) {
  146. // If it's followed by one colon, it requires an argument.
  147. needs_value = required_argument;
  148. } else {
  149. // Otherwise, it doesn't accept arguments.
  150. needs_value = no_argument;
  151. }
  152. return true;
  153. }
  154. int OptionParser::handle_short_option()
  155. {
  156. StringView arg = m_argv[m_arg_index];
  157. VERIFY(arg.starts_with('-'));
  158. if (s_index_into_multioption_argument == 0) {
  159. // Just starting to parse this argument, skip the "-".
  160. s_index_into_multioption_argument = 1;
  161. }
  162. char option = arg[s_index_into_multioption_argument];
  163. s_index_into_multioption_argument++;
  164. int needs_value = no_argument;
  165. bool ok = lookup_short_option(option, needs_value);
  166. if (!ok) {
  167. optopt = option;
  168. report_error("Unrecognized option \033[1m-%c\033[22m", option);
  169. return '?';
  170. }
  171. // Let's see if we're at the end of this argument already.
  172. if (s_index_into_multioption_argument < arg.length()) {
  173. // This not yet the end.
  174. if (needs_value == no_argument) {
  175. optarg = nullptr;
  176. m_consumed_args = 0;
  177. } else {
  178. // Treat the rest of the argument as the value, the "-ovalue"
  179. // syntax.
  180. optarg = m_argv[m_arg_index] + s_index_into_multioption_argument;
  181. // Next time, process the next argument.
  182. s_index_into_multioption_argument = 0;
  183. m_consumed_args = 1;
  184. }
  185. } else {
  186. s_index_into_multioption_argument = 0;
  187. if (needs_value != required_argument) {
  188. optarg = nullptr;
  189. m_consumed_args = 1;
  190. } else if (m_arg_index + 1 < m_argc) {
  191. // Treat the next argument as a value, the "-o value" syntax.
  192. optarg = m_argv[m_arg_index + 1];
  193. m_consumed_args = 2;
  194. } else {
  195. report_error("Missing value for option \033[1m-%c\033[22m", option);
  196. return '?';
  197. }
  198. }
  199. return option;
  200. }
  201. const option* OptionParser::lookup_long_option(char* raw) const
  202. {
  203. StringView arg = raw;
  204. for (size_t index = 0; m_long_options[index].name; index++) {
  205. auto& option = m_long_options[index];
  206. StringView name = option.name;
  207. if (!arg.starts_with(name))
  208. continue;
  209. // It would be better to not write out the index at all unless we're
  210. // sure we've found the right option, but whatever.
  211. if (m_out_long_option_index)
  212. *m_out_long_option_index = index;
  213. // Can either be "--option" or "--option=value".
  214. if (arg.length() == name.length()) {
  215. optarg = nullptr;
  216. return &option;
  217. }
  218. VERIFY(arg.length() > name.length());
  219. if (arg[name.length()] == '=') {
  220. optarg = raw + name.length() + 1;
  221. return &option;
  222. }
  223. }
  224. return nullptr;
  225. }
  226. int OptionParser::handle_long_option()
  227. {
  228. VERIFY(StringView(m_argv[m_arg_index]).starts_with("--"));
  229. // We cannot set optopt to anything sensible for long options, so set it to 0.
  230. optopt = 0;
  231. auto* option = lookup_long_option(m_argv[m_arg_index] + 2);
  232. if (!option) {
  233. report_error("Unrecognized option \033[1m%s\033[22m", m_argv[m_arg_index]);
  234. return '?';
  235. }
  236. // lookup_long_option() will also set optarg if the value of the option is
  237. // specified using "--option=value" syntax.
  238. // Figure out whether this option needs and/or has a value (also called "an
  239. // argument", but let's not call it that to distinguish it from argv
  240. // elements).
  241. switch (option->has_arg) {
  242. case no_argument:
  243. if (optarg) {
  244. report_error("Option \033[1m--%s\033[22m doesn't accept an argument", option->name);
  245. return '?';
  246. }
  247. m_consumed_args = 1;
  248. break;
  249. case optional_argument:
  250. m_consumed_args = 1;
  251. break;
  252. case required_argument:
  253. if (optarg) {
  254. // Value specified using "--option=value" syntax.
  255. m_consumed_args = 1;
  256. } else if (m_arg_index + 1 < m_argc) {
  257. // Treat the next argument as a value in "--option value" syntax.
  258. optarg = m_argv[m_arg_index + 1];
  259. m_consumed_args = 2;
  260. } else {
  261. report_error("Missing value for option \033[1m--%s\033[22m", option->name);
  262. return '?';
  263. }
  264. break;
  265. default:
  266. VERIFY_NOT_REACHED();
  267. }
  268. // Now that we've figured the value out, see about reporting this option to
  269. // our caller.
  270. if (option->flag) {
  271. *option->flag = option->val;
  272. return 0;
  273. }
  274. return option->val;
  275. }
  276. void OptionParser::shift_argv()
  277. {
  278. // We've just parsed an option (which perhaps has a value).
  279. // Put the option (along with it value, if any) in front of other arguments.
  280. VERIFY(optind <= static_cast<int>(m_arg_index));
  281. if (optind == static_cast<int>(m_arg_index) || m_consumed_args == 0) {
  282. // Nothing to do!
  283. return;
  284. }
  285. char* buffer[m_consumed_args];
  286. memcpy(buffer, &m_argv[m_arg_index], sizeof(char*) * m_consumed_args);
  287. memmove(&m_argv[optind + m_consumed_args], &m_argv[optind], sizeof(char*) * (m_arg_index - optind));
  288. memcpy(&m_argv[optind], buffer, sizeof(char*) * m_consumed_args);
  289. }
  290. bool OptionParser::find_next_option()
  291. {
  292. for (m_arg_index = optind; m_arg_index < m_argc && m_argv[m_arg_index]; m_arg_index++) {
  293. StringView arg = m_argv[m_arg_index];
  294. // Anything that doesn't start with a "-" is not an option.
  295. if (!arg.starts_with('-')) {
  296. if (m_stop_on_first_non_option)
  297. return false;
  298. continue;
  299. }
  300. // As a special case, a single "-" is not an option either.
  301. // (It's typically used by programs to refer to stdin).
  302. if (arg == "-")
  303. continue;
  304. // As another special case, a "--" is not an option either, and we stop
  305. // looking for further options if we encounter it.
  306. if (arg == "--")
  307. return false;
  308. // Otherwise, we have found an option!
  309. return true;
  310. }
  311. // Reached the end and still found no options.
  312. return false;
  313. }
  314. }
  315. int getopt(int argc, char* const* argv, const char* short_options)
  316. {
  317. option dummy { nullptr, 0, nullptr, 0 };
  318. OptionParser parser { argc, argv, short_options, &dummy };
  319. return parser.getopt();
  320. }
  321. int getopt_long(int argc, char* const* argv, const char* short_options, const struct option* long_options, int* out_long_option_index)
  322. {
  323. OptionParser parser { argc, argv, short_options, long_options, out_long_option_index };
  324. return parser.getopt();
  325. }