getopt.c 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. /* Copyright (c) 2012, Kim Gräsman
  2. * All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are met:
  6. * * Redistributions of source code must retain the above copyright notice,
  7. * this list of conditions and the following disclaimer.
  8. * * Redistributions in binary form must reproduce the above copyright notice,
  9. * this list of conditions and the following disclaimer in the documentation
  10. * and/or other materials provided with the distribution.
  11. * * Neither the name of Kim Gräsman nor the names of contributors may be used
  12. * to endorse or promote products derived from this software without specific
  13. * prior written permission.
  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
  18. * ARE DISCLAIMED. IN NO EVENT SHALL KIM GRÄSMAN BE LIABLE FOR ANY DIRECT,
  19. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  20. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  21. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  22. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  24. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "getopt.h"
  27. #include <stddef.h>
  28. #include <string.h>
  29. const int no_argument = 0;
  30. const int required_argument = 1;
  31. const int optional_argument = 2;
  32. char* optarg;
  33. int optopt;
  34. /* The variable optind [...] shall be initialized to 1 by the system. */
  35. int optind = 1;
  36. int opterr;
  37. static char* optcursor = NULL;
  38. /* Implemented based on [1] and [2] for optional arguments.
  39. optopt is handled FreeBSD-style, per [3].
  40. Other GNU and FreeBSD extensions are purely accidental.
  41. [1] http://pubs.opengroup.org/onlinepubs/000095399/functions/getopt.html
  42. [2] http://www.kernel.org/doc/man-pages/online/pages/man3/getopt.3.html
  43. [3] http://www.freebsd.org/cgi/man.cgi?query=getopt&sektion=3&manpath=FreeBSD+9.0-RELEASE
  44. */
  45. int getopt(int argc, char* const argv[], const char* optstring) {
  46. int optchar = -1;
  47. const char* optdecl = NULL;
  48. optarg = NULL;
  49. opterr = 0;
  50. optopt = 0;
  51. /* Unspecified, but we need it to avoid overrunning the argv bounds. */
  52. if (optind >= argc)
  53. goto no_more_optchars;
  54. /* If, when getopt() is called argv[optind] is a null pointer, getopt()
  55. shall return -1 without changing optind. */
  56. if (argv[optind] == NULL)
  57. goto no_more_optchars;
  58. /* If, when getopt() is called *argv[optind] is not the character '-',
  59. getopt() shall return -1 without changing optind. */
  60. if (*argv[optind] != '-')
  61. goto no_more_optchars;
  62. /* If, when getopt() is called argv[optind] points to the string "-",
  63. getopt() shall return -1 without changing optind. */
  64. if (strcmp(argv[optind], "-") == 0)
  65. goto no_more_optchars;
  66. /* If, when getopt() is called argv[optind] points to the string "--",
  67. getopt() shall return -1 after incrementing optind. */
  68. if (strcmp(argv[optind], "--") == 0) {
  69. ++optind;
  70. goto no_more_optchars;
  71. }
  72. if (optcursor == NULL || *optcursor == '\0')
  73. optcursor = argv[optind] + 1;
  74. optchar = *optcursor;
  75. /* FreeBSD: The variable optopt saves the last known option character
  76. returned by getopt(). */
  77. optopt = optchar;
  78. /* The getopt() function shall return the next option character (if one is
  79. found) from argv that matches a character in optstring, if there is
  80. one that matches. */
  81. optdecl = strchr(optstring, optchar);
  82. if (optdecl) {
  83. /* [I]f a character is followed by a colon, the option takes an
  84. argument. */
  85. if (optdecl[1] == ':') {
  86. optarg = ++optcursor;
  87. if (*optarg == '\0') {
  88. /* GNU extension: Two colons mean an option takes an
  89. optional arg; if there is text in the current argv-element
  90. (i.e., in the same word as the option name itself, for example,
  91. "-oarg"), then it is returned in optarg, otherwise optarg is set
  92. to zero. */
  93. if (optdecl[2] != ':') {
  94. /* If the option was the last character in the string pointed to by
  95. an element of argv, then optarg shall contain the next element
  96. of argv, and optind shall be incremented by 2. If the resulting
  97. value of optind is greater than argc, this indicates a missing
  98. option-argument, and getopt() shall return an error indication.
  99. Otherwise, optarg shall point to the string following the
  100. option character in that element of argv, and optind shall be
  101. incremented by 1.
  102. */
  103. if (++optind < argc) {
  104. optarg = argv[optind];
  105. } else {
  106. /* If it detects a missing option-argument, it shall return the
  107. colon character ( ':' ) if the first character of optstring
  108. was a colon, or a question-mark character ( '?' ) otherwise.
  109. */
  110. optarg = NULL;
  111. optchar = (optstring[0] == ':') ? ':' : '?';
  112. }
  113. } else {
  114. optarg = NULL;
  115. }
  116. }
  117. optcursor = NULL;
  118. }
  119. } else {
  120. /* If getopt() encounters an option character that is not contained in
  121. optstring, it shall return the question-mark ( '?' ) character. */
  122. optchar = '?';
  123. }
  124. if (optcursor == NULL || *++optcursor == '\0')
  125. ++optind;
  126. return optchar;
  127. no_more_optchars:
  128. optcursor = NULL;
  129. return -1;
  130. }
  131. /* Implementation based on [1].
  132. [1] http://www.kernel.org/doc/man-pages/online/pages/man3/getopt.3.html
  133. */
  134. int getopt_long(int argc, char* const argv[], const char* optstring,
  135. const struct option* longopts, int* longindex) {
  136. const struct option* o = longopts;
  137. const struct option* match = NULL;
  138. int num_matches = 0;
  139. size_t argument_name_length = 0;
  140. const char* current_argument = NULL;
  141. int retval = -1;
  142. optarg = NULL;
  143. optopt = 0;
  144. if (optind >= argc)
  145. return -1;
  146. if (strlen(argv[optind]) < 3 || strncmp(argv[optind], "--", 2) != 0)
  147. return getopt(argc, argv, optstring);
  148. /* It's an option; starts with -- and is longer than two chars. */
  149. current_argument = argv[optind] + 2;
  150. argument_name_length = strcspn(current_argument, "=");
  151. for (; o->name; ++o) {
  152. if (strncmp(o->name, current_argument, argument_name_length) == 0) {
  153. match = o;
  154. ++num_matches;
  155. }
  156. }
  157. if (num_matches == 1) {
  158. /* If longindex is not NULL, it points to a variable which is set to the
  159. index of the long option relative to longopts. */
  160. if (longindex)
  161. *longindex = (int) (match - longopts);
  162. /* If flag is NULL, then getopt_long() shall return val.
  163. Otherwise, getopt_long() returns 0, and flag shall point to a variable
  164. which shall be set to val if the option is found, but left unchanged if
  165. the option is not found. */
  166. if (match->flag)
  167. *(match->flag) = match->val;
  168. retval = match->flag ? 0 : match->val;
  169. if (match->has_arg != no_argument) {
  170. optarg = strchr(argv[optind], '=');
  171. if (optarg != NULL)
  172. ++optarg;
  173. if (match->has_arg == required_argument) {
  174. /* Only scan the next argv for required arguments. Behavior is not
  175. specified, but has been observed with Ubuntu and Mac OSX. */
  176. if (optarg == NULL && ++optind < argc) {
  177. optarg = argv[optind];
  178. }
  179. if (optarg == NULL)
  180. retval = ':';
  181. }
  182. } else if (strchr(argv[optind], '=')) {
  183. /* An argument was provided to a non-argument option.
  184. I haven't seen this specified explicitly, but both GNU and BSD-based
  185. implementations show this behavior.
  186. */
  187. retval = '?';
  188. }
  189. } else {
  190. /* Unknown option or ambiguous match. */
  191. retval = '?';
  192. }
  193. ++optind;
  194. return retval;
  195. }