arg_int.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /*
  2. * SPDX-FileCopyrightText: 1998-2001,2003-2011,2013 Stewart Heitmann
  3. *
  4. * SPDX-License-Identifier: BSD-3-Clause
  5. */
  6. /*******************************************************************************
  7. * arg_int: Implements the int command-line option
  8. *
  9. * This file is part of the argtable3 library.
  10. *
  11. * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
  12. * <sheitmann@users.sourceforge.net>
  13. * All rights reserved.
  14. *
  15. * Redistribution and use in source and binary forms, with or without
  16. * modification, are permitted provided that the following conditions are met:
  17. * * Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. * * Redistributions in binary form must reproduce the above copyright
  20. * notice, this list of conditions and the following disclaimer in the
  21. * documentation and/or other materials provided with the distribution.
  22. * * Neither the name of STEWART HEITMANN nor the names of its contributors
  23. * may be used to endorse or promote products derived from this software
  24. * without specific prior written permission.
  25. *
  26. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  27. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  28. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  29. * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
  30. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  31. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  32. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  33. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  34. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  35. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  36. ******************************************************************************/
  37. #include "argtable3.h"
  38. #ifndef ARG_AMALGAMATION
  39. #include "argtable3_private.h"
  40. #endif
  41. #include <ctype.h>
  42. #include <limits.h>
  43. #include <stdlib.h>
  44. static void arg_int_resetfn(struct arg_int* parent) {
  45. ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
  46. parent->count = 0;
  47. }
  48. /* strtol0x() is like strtol() except that the numeric string is */
  49. /* expected to be prefixed by "0X" where X is a user supplied char. */
  50. /* The string may optionally be prefixed by white space and + or - */
  51. /* as in +0X123 or -0X123. */
  52. /* Once the prefix has been scanned, the remainder of the numeric */
  53. /* string is converted using strtol() with the given base. */
  54. /* eg: to parse hex str="-0X12324", specify X='X' and base=16. */
  55. /* eg: to parse oct str="+0o12324", specify X='O' and base=8. */
  56. /* eg: to parse bin str="-0B01010", specify X='B' and base=2. */
  57. /* Failure of conversion is indicated by result where *endptr==str. */
  58. static long int strtol0X(const char* str, const char** endptr, char X, int base) {
  59. long int val; /* stores result */
  60. int s = 1; /* sign is +1 or -1 */
  61. const char* ptr = str; /* ptr to current position in str */
  62. /* skip leading whitespace */
  63. while (isspace((int)(*ptr)))
  64. ptr++;
  65. /* printf("1) %s\n",ptr); */
  66. /* scan optional sign character */
  67. switch (*ptr) {
  68. case '+':
  69. ptr++;
  70. s = 1;
  71. break;
  72. case '-':
  73. ptr++;
  74. s = -1;
  75. break;
  76. default:
  77. s = 1;
  78. break;
  79. }
  80. /* printf("2) %s\n",ptr); */
  81. /* '0X' prefix */
  82. if ((*ptr++) != '0') {
  83. /* printf("failed to detect '0'\n"); */
  84. *endptr = str;
  85. return 0;
  86. }
  87. /* printf("3) %s\n",ptr); */
  88. if (toupper(*ptr++) != toupper(X)) {
  89. /* printf("failed to detect '%c'\n",X); */
  90. *endptr = str;
  91. return 0;
  92. }
  93. /* printf("4) %s\n",ptr); */
  94. /* attempt conversion on remainder of string using strtol() */
  95. val = strtol(ptr, (char**)endptr, base);
  96. if (*endptr == ptr) {
  97. /* conversion failed */
  98. *endptr = str;
  99. return 0;
  100. }
  101. /* success */
  102. return s * val;
  103. }
  104. /* Returns 1 if str matches suffix (case insensitive). */
  105. /* Str may contain trailing whitespace, but nothing else. */
  106. static int detectsuffix(const char* str, const char* suffix) {
  107. /* scan pairwise through strings until mismatch detected */
  108. while (toupper(*str) == toupper(*suffix)) {
  109. /* printf("'%c' '%c'\n", *str, *suffix); */
  110. /* return 1 (success) if match persists until the string terminator */
  111. if (*str == '\0')
  112. return 1;
  113. /* next chars */
  114. str++;
  115. suffix++;
  116. }
  117. /* printf("'%c' '%c' mismatch\n", *str, *suffix); */
  118. /* return 0 (fail) if the matching did not consume the entire suffix */
  119. if (*suffix != 0)
  120. return 0; /* failed to consume entire suffix */
  121. /* skip any remaining whitespace in str */
  122. while (isspace((int)(*str)))
  123. str++;
  124. /* return 1 (success) if we have reached end of str else return 0 (fail) */
  125. return (*str == '\0') ? 1 : 0;
  126. }
  127. static int arg_int_scanfn(struct arg_int* parent, const char* argval) {
  128. int errorcode = 0;
  129. if (parent->count == parent->hdr.maxcount) {
  130. /* maximum number of arguments exceeded */
  131. errorcode = ARG_ERR_MAXCOUNT;
  132. } else if (!argval) {
  133. /* a valid argument with no argument value was given. */
  134. /* This happens when an optional argument value was invoked. */
  135. /* leave parent arguiment value unaltered but still count the argument. */
  136. parent->count++;
  137. } else {
  138. long int val;
  139. const char* end;
  140. /* attempt to extract hex integer (eg: +0x123) from argval into val conversion */
  141. val = strtol0X(argval, &end, 'X', 16);
  142. if (end == argval) {
  143. /* hex failed, attempt octal conversion (eg +0o123) */
  144. val = strtol0X(argval, &end, 'O', 8);
  145. if (end == argval) {
  146. /* octal failed, attempt binary conversion (eg +0B101) */
  147. val = strtol0X(argval, &end, 'B', 2);
  148. if (end == argval) {
  149. /* binary failed, attempt decimal conversion with no prefix (eg 1234) */
  150. val = strtol(argval, (char**)&end, 10);
  151. if (end == argval) {
  152. /* all supported number formats failed */
  153. return ARG_ERR_BADINT;
  154. }
  155. }
  156. }
  157. }
  158. /* Safety check for integer overflow. WARNING: this check */
  159. /* achieves nothing on machines where size(int)==size(long). */
  160. if (val > INT_MAX || val < INT_MIN)
  161. errorcode = ARG_ERR_OVERFLOW;
  162. /* Detect any suffixes (KB,MB,GB) and multiply argument value appropriately. */
  163. /* We need to be mindful of integer overflows when using such big numbers. */
  164. if (detectsuffix(end, "KB")) /* kilobytes */
  165. {
  166. if (val > (INT_MAX / 1024) || val < (INT_MIN / 1024))
  167. errorcode = ARG_ERR_OVERFLOW; /* Overflow would occur if we proceed */
  168. else
  169. val *= 1024; /* 1KB = 1024 */
  170. } else if (detectsuffix(end, "MB")) /* megabytes */
  171. {
  172. if (val > (INT_MAX / 1048576) || val < (INT_MIN / 1048576))
  173. errorcode = ARG_ERR_OVERFLOW; /* Overflow would occur if we proceed */
  174. else
  175. val *= 1048576; /* 1MB = 1024*1024 */
  176. } else if (detectsuffix(end, "GB")) /* gigabytes */
  177. {
  178. if (val > (INT_MAX / 1073741824) || val < (INT_MIN / 1073741824))
  179. errorcode = ARG_ERR_OVERFLOW; /* Overflow would occur if we proceed */
  180. else
  181. val *= 1073741824; /* 1GB = 1024*1024*1024 */
  182. } else if (!detectsuffix(end, ""))
  183. errorcode = ARG_ERR_BADINT; /* invalid suffix detected */
  184. /* if success then store result in parent->ival[] array */
  185. if (errorcode == 0)
  186. parent->ival[parent->count++] = (int)val;
  187. }
  188. /* printf("%s:scanfn(%p,%p) returns %d\n",__FILE__,parent,argval,errorcode); */
  189. return errorcode;
  190. }
  191. static int arg_int_checkfn(struct arg_int* parent) {
  192. int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0;
  193. /*printf("%s:checkfn(%p) returns %d\n",__FILE__,parent,errorcode);*/
  194. return errorcode;
  195. }
  196. static void arg_int_errorfn(struct arg_int* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) {
  197. const char* shortopts = parent->hdr.shortopts;
  198. const char* longopts = parent->hdr.longopts;
  199. const char* datatype = parent->hdr.datatype;
  200. /* make argval NULL safe */
  201. argval = argval ? argval : "";
  202. arg_dstr_catf(ds, "%s: ", progname);
  203. switch (errorcode) {
  204. case ARG_ERR_MINCOUNT:
  205. arg_dstr_cat(ds, "missing option ");
  206. arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
  207. break;
  208. case ARG_ERR_MAXCOUNT:
  209. arg_dstr_cat(ds, "excess option ");
  210. arg_print_option_ds(ds, shortopts, longopts, argval, "\n");
  211. break;
  212. case ARG_ERR_BADINT:
  213. arg_dstr_catf(ds, "invalid argument \"%s\" to option ", argval);
  214. arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
  215. break;
  216. case ARG_ERR_OVERFLOW:
  217. arg_dstr_cat(ds, "integer overflow at option ");
  218. arg_print_option_ds(ds, shortopts, longopts, datatype, " ");
  219. arg_dstr_catf(ds, "(%s is too large)\n", argval);
  220. break;
  221. }
  222. }
  223. struct arg_int* arg_int0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
  224. return arg_intn(shortopts, longopts, datatype, 0, 1, glossary);
  225. }
  226. struct arg_int* arg_int1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
  227. return arg_intn(shortopts, longopts, datatype, 1, 1, glossary);
  228. }
  229. struct arg_int* arg_intn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary) {
  230. size_t nbytes;
  231. struct arg_int* result;
  232. /* foolproof things by ensuring maxcount is not less than mincount */
  233. maxcount = (maxcount < mincount) ? mincount : maxcount;
  234. nbytes = sizeof(struct arg_int) /* storage for struct arg_int */
  235. + (size_t)maxcount * sizeof(int); /* storage for ival[maxcount] array */
  236. result = (struct arg_int*)xmalloc(nbytes);
  237. /* init the arg_hdr struct */
  238. result->hdr.flag = ARG_HASVALUE;
  239. result->hdr.shortopts = shortopts;
  240. result->hdr.longopts = longopts;
  241. result->hdr.datatype = datatype ? datatype : "<int>";
  242. result->hdr.glossary = glossary;
  243. result->hdr.mincount = mincount;
  244. result->hdr.maxcount = maxcount;
  245. result->hdr.parent = result;
  246. result->hdr.resetfn = (arg_resetfn*)arg_int_resetfn;
  247. result->hdr.scanfn = (arg_scanfn*)arg_int_scanfn;
  248. result->hdr.checkfn = (arg_checkfn*)arg_int_checkfn;
  249. result->hdr.errorfn = (arg_errorfn*)arg_int_errorfn;
  250. /* store the ival[maxcount] array immediately after the arg_int struct */
  251. result->ival = (int*)(result + 1);
  252. result->count = 0;
  253. ARG_TRACE(("arg_intn() returns %p\n", result));
  254. return result;
  255. }