getopt.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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** argv, const StringView& short_options, const option* long_options, int* out_long_option_index = nullptr);
  56. int getopt();
  57. private:
  58. bool lookup_short_option(char option, int& needs_value) const;
  59. int handle_short_option();
  60. const option* lookup_long_option(char* raw) const;
  61. int handle_long_option();
  62. void shift_argv();
  63. bool find_next_option();
  64. size_t m_argc { 0 };
  65. char** m_argv { nullptr };
  66. StringView m_short_options;
  67. const option* m_long_options { nullptr };
  68. int* m_out_long_option_index { nullptr };
  69. bool m_stop_on_first_non_option { false };
  70. size_t m_arg_index { 0 };
  71. size_t m_consumed_args { 0 };
  72. };
  73. OptionParser::OptionParser(int argc, char** argv, const StringView& short_options, const option* long_options, int* out_long_option_index)
  74. : m_argc(argc)
  75. , m_argv(argv)
  76. , m_short_options(short_options)
  77. , m_long_options(long_options)
  78. , m_out_long_option_index(out_long_option_index)
  79. {
  80. // In the following case:
  81. // $ foo bar -o baz
  82. // we want to parse the option (-o baz) first, and leave the argument (bar)
  83. // in argv after we return -1 when invoked the second time. So we reorder
  84. // argv to put options first and positional arguments next. To turn this
  85. // behavior off, start the short options spec with a "+". This is a GNU
  86. // extension that we support.
  87. m_stop_on_first_non_option = short_options.starts_with('+');
  88. // See if we should reset the internal state.
  89. if (optreset || optind == 0) {
  90. optreset = 0;
  91. optind = 1;
  92. s_index_into_multioption_argument = 0;
  93. }
  94. optopt = 0;
  95. optarg = nullptr;
  96. }
  97. int OptionParser::getopt()
  98. {
  99. bool should_reorder_argv = !m_stop_on_first_non_option;
  100. int res = -1;
  101. bool found_an_option = find_next_option();
  102. StringView arg = m_argv[m_arg_index];
  103. if (!found_an_option) {
  104. res = -1;
  105. if (arg == "--")
  106. m_consumed_args = 1;
  107. else
  108. m_consumed_args = 0;
  109. } else {
  110. // Alright, so we have an option on our hands!
  111. bool is_long_option = arg.starts_with("--");
  112. if (is_long_option)
  113. res = handle_long_option();
  114. else
  115. res = handle_short_option();
  116. // If we encountered an error, return immediately.
  117. if (res == '?')
  118. return '?';
  119. }
  120. if (should_reorder_argv)
  121. shift_argv();
  122. else
  123. ASSERT(optind == static_cast<int>(m_arg_index));
  124. optind += m_consumed_args;
  125. return res;
  126. }
  127. bool OptionParser::lookup_short_option(char option, int& needs_value) const
  128. {
  129. Vector<StringView> parts = m_short_options.split_view(option, true);
  130. ASSERT(parts.size() <= 2);
  131. if (parts.size() < 2) {
  132. // Haven't found the option in the spec.
  133. return false;
  134. }
  135. if (parts[1].starts_with("::")) {
  136. // If an option is followed by two colons, it optionally accepts an
  137. // argument.
  138. needs_value = optional_argument;
  139. } else if (parts[1].starts_with(':')) {
  140. // If it's followed by one colon, it requires an argument.
  141. needs_value = required_argument;
  142. } else {
  143. // Otherwise, it doesn't accept arguments.
  144. needs_value = no_argument;
  145. }
  146. return true;
  147. }
  148. int OptionParser::handle_short_option()
  149. {
  150. StringView arg = m_argv[m_arg_index];
  151. ASSERT(arg.starts_with('-'));
  152. if (s_index_into_multioption_argument == 0) {
  153. // Just starting to parse this argument, skip the "-".
  154. s_index_into_multioption_argument = 1;
  155. }
  156. char option = arg[s_index_into_multioption_argument];
  157. s_index_into_multioption_argument++;
  158. int needs_value = no_argument;
  159. bool ok = lookup_short_option(option, needs_value);
  160. if (!ok) {
  161. optopt = option;
  162. report_error("Unrecognized option \033[1m-%c\033[22m", option);
  163. return '?';
  164. }
  165. // Let's see if we're at the end of this argument already.
  166. if (s_index_into_multioption_argument < arg.length()) {
  167. // This not yet the end.
  168. if (needs_value == no_argument) {
  169. optarg = nullptr;
  170. m_consumed_args = 0;
  171. } else {
  172. // Treat the rest of the argument as the value, the "-ovalue"
  173. // syntax.
  174. optarg = m_argv[m_arg_index] + s_index_into_multioption_argument;
  175. // Next time, process the next argument.
  176. s_index_into_multioption_argument = 0;
  177. m_consumed_args = 1;
  178. }
  179. } else {
  180. s_index_into_multioption_argument = 0;
  181. if (needs_value != required_argument) {
  182. optarg = nullptr;
  183. m_consumed_args = 1;
  184. } else if (m_arg_index + 1 < m_argc) {
  185. // Treat the next argument as a value, the "-o value" syntax.
  186. optarg = m_argv[m_arg_index + 1];
  187. m_consumed_args = 2;
  188. } else {
  189. report_error("Missing value for option \033[1m-%c\033[22m", option);
  190. return '?';
  191. }
  192. }
  193. return option;
  194. }
  195. const option* OptionParser::lookup_long_option(char* raw) const
  196. {
  197. StringView arg = raw;
  198. for (size_t index = 0; m_long_options[index].name; index++) {
  199. auto& option = m_long_options[index];
  200. StringView name = option.name;
  201. if (!arg.starts_with(name))
  202. continue;
  203. // It would be better to not write out the index at all unless we're
  204. // sure we've found the right option, but whatever.
  205. if (m_out_long_option_index)
  206. *m_out_long_option_index = index;
  207. // Can either be "--option" or "--option=value".
  208. if (arg.length() == name.length()) {
  209. optarg = nullptr;
  210. return &option;
  211. }
  212. ASSERT(arg.length() > name.length());
  213. if (arg[name.length()] == '=') {
  214. optarg = raw + name.length() + 1;
  215. return &option;
  216. }
  217. }
  218. return nullptr;
  219. }
  220. int OptionParser::handle_long_option()
  221. {
  222. ASSERT(StringView(m_argv[m_arg_index]).starts_with("--"));
  223. // We cannot set optopt to anything sensible for long options, so set it to 0.
  224. optopt = 0;
  225. auto* option = lookup_long_option(m_argv[m_arg_index] + 2);
  226. if (!option) {
  227. report_error("Unrecognized option \033[1m%s\033[22m", m_argv[m_arg_index]);
  228. return '?';
  229. }
  230. // lookup_long_option() will also set optarg if the value of the option is
  231. // specified using "--option=value" syntax.
  232. // Figure out whether this option needs and/or has a value (also called "an
  233. // argument", but let's not call it that to distinguish it from argv
  234. // elements).
  235. switch (option->has_arg) {
  236. case no_argument:
  237. if (optarg) {
  238. report_error("Option \033[1m--%s\033[22m doesn't accept an argument", option->name);
  239. return '?';
  240. }
  241. m_consumed_args = 1;
  242. break;
  243. case optional_argument:
  244. m_consumed_args = 1;
  245. break;
  246. case required_argument:
  247. if (optarg) {
  248. // Value specified using "--option=value" syntax.
  249. m_consumed_args = 1;
  250. } else if (m_arg_index + 1 < m_argc) {
  251. // Treat the next argument as a value in "--option value" syntax.
  252. optarg = m_argv[m_arg_index + 1];
  253. m_consumed_args = 2;
  254. } else {
  255. report_error("Missing value for option \033[1m--%s\033[22m", option->name);
  256. return '?';
  257. }
  258. break;
  259. default:
  260. ASSERT_NOT_REACHED();
  261. }
  262. // Now that we've figured the value out, see about reporting this option to
  263. // our caller.
  264. if (option->flag) {
  265. *option->flag = option->val;
  266. return 0;
  267. }
  268. return option->val;
  269. }
  270. void OptionParser::shift_argv()
  271. {
  272. // We've just parsed an option (which perhaps has a value).
  273. // Put the option (along with it value, if any) in front of other arguments.
  274. ASSERT(optind <= static_cast<int>(m_arg_index));
  275. if (optind == static_cast<int>(m_arg_index) || m_consumed_args == 0) {
  276. // Nothing to do!
  277. return;
  278. }
  279. char* buffer[m_consumed_args];
  280. memcpy(buffer, &m_argv[m_arg_index], sizeof(char*) * m_consumed_args);
  281. memmove(&m_argv[optind + m_consumed_args], &m_argv[optind], sizeof(char*) * (m_arg_index - optind));
  282. memcpy(&m_argv[optind], buffer, sizeof(char*) * m_consumed_args);
  283. }
  284. bool OptionParser::find_next_option()
  285. {
  286. for (m_arg_index = optind; m_arg_index < m_argc && m_argv[m_arg_index]; m_arg_index++) {
  287. StringView arg = m_argv[m_arg_index];
  288. // Anything that doesn't start with a "-" is not an option.
  289. if (!arg.starts_with('-')) {
  290. if (m_stop_on_first_non_option)
  291. return false;
  292. continue;
  293. }
  294. // As a special case, a single "-" is not an option either.
  295. // (It's typically used by programs to refer to stdin).
  296. if (arg == "-")
  297. continue;
  298. // As another special case, a "--" is not an option either, and we stop
  299. // looking for further options if we encounter it.
  300. if (arg == "--")
  301. return false;
  302. // Otherwise, we have found an option!
  303. return true;
  304. }
  305. // Reached the end and still found no options.
  306. return false;
  307. }
  308. }
  309. int getopt(int argc, char** argv, const char* short_options)
  310. {
  311. option dummy { nullptr, 0, nullptr, 0 };
  312. OptionParser parser { argc, argv, short_options, &dummy };
  313. return parser.getopt();
  314. }
  315. int getopt_long(int argc, char** argv, const char* short_options, const struct option* long_options, int* out_long_option_index)
  316. {
  317. OptionParser parser { argc, argv, short_options, long_options, out_long_option_index };
  318. return parser.getopt();
  319. }