diff --git a/src/argtable3.c b/src/argtable3.c index b3639b0..e1d8af7 100644 --- a/src/argtable3.c +++ b/src/argtable3.c @@ -1,4658 +1,3 @@ -/******************************************************************************* - * arg_cmd: Provides the sub-command mechanism - * - * This file is part of the argtable3 library. - * - * Copyright (C) 2013-2019 Tom G. Huang - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of STEWART HEITMANN nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -#include "argtable3.h" - -#ifndef ARG_AMALGAMATION -#include "argtable3_private.h" -#endif - -#include -#include -#include - -#define MAX_MODULE_VERSION_SIZE 128 - -static arg_hashtable_t* s_hashtable = NULL; -static char* s_module_name = NULL; -static int s_mod_ver_major = 0; -static int s_mod_ver_minor = 0; -static int s_mod_ver_patch = 0; -static char* s_mod_ver_tag = NULL; -static char* s_mod_ver = NULL; - -void arg_set_module_name(const char* name) { - size_t slen; - - xfree(s_module_name); - slen = strlen(name); - s_module_name = (char*)xmalloc(slen + 1); - memset(s_module_name, 0, slen + 1); - -#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__)) - strncpy_s(s_module_name, slen + 1, name, slen); -#else - memcpy(s_module_name, name, slen); -#endif -} - -void arg_set_module_version(int major, int minor, int patch, const char* tag) { - size_t slen_tag, slen_ds; - arg_dstr_t ds; - - s_mod_ver_major = major; - s_mod_ver_minor = minor; - s_mod_ver_patch = patch; - - xfree(s_mod_ver_tag); - slen_tag = strlen(tag); - s_mod_ver_tag = (char*)xmalloc(slen_tag + 1); - memset(s_mod_ver_tag, 0, slen_tag + 1); - -#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__)) - strncpy_s(s_mod_ver_tag, slen_tag + 1, tag, slen_tag); -#else - memcpy(s_mod_ver_tag, tag, slen_tag); -#endif - - ds = arg_dstr_create(); - arg_dstr_catf(ds, "%d.", s_mod_ver_major); - arg_dstr_catf(ds, "%d.", s_mod_ver_minor); - arg_dstr_catf(ds, "%d.", s_mod_ver_patch); - arg_dstr_cat(ds, s_mod_ver_tag); - - xfree(s_mod_ver); - slen_ds = strlen(arg_dstr_cstr(ds)); - s_mod_ver = (char*)xmalloc(slen_ds + 1); - memset(s_mod_ver, 0, slen_ds + 1); - -#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__)) - strncpy_s(s_mod_ver, slen_ds + 1, arg_dstr_cstr(ds), slen_ds); -#else - memcpy(s_mod_ver, arg_dstr_cstr(ds), slen_ds); -#endif - - arg_dstr_destroy(ds); -} - -static unsigned int hash_key(const void* key) { - const char* str = (const char*)key; - int c; - unsigned int hash = 5381; - - while ((c = *str++) != 0) - hash = ((hash << 5) + hash) + (unsigned int)c; /* hash * 33 + c */ - - return hash; -} - -static int equal_keys(const void* key1, const void* key2) { - char* k1 = (char*)key1; - char* k2 = (char*)key2; - return (0 == strcmp(k1, k2)); -} - -void arg_cmd_init(void) { - s_hashtable = arg_hashtable_create(32, hash_key, equal_keys); -} - -void arg_cmd_uninit(void) { - arg_hashtable_destroy(s_hashtable, 1); -} - -void arg_cmd_register(const char* name, arg_cmdfn* proc, const char* description) { - arg_cmd_info_t* cmd_info; - size_t slen_name; - void* k; - - assert(strlen(name) < ARG_CMD_NAME_LEN); - assert(strlen(description) < ARG_CMD_DESCRIPTION_LEN); - - /* Check if the command already exists. */ - /* If the command exists, replace the existing command. */ - /* If the command doesn't exist, insert the command. */ - cmd_info = (arg_cmd_info_t*)arg_hashtable_search(s_hashtable, name); - if (cmd_info) { - arg_hashtable_remove(s_hashtable, name); - cmd_info = NULL; - } - - cmd_info = (arg_cmd_info_t*)xmalloc(sizeof(arg_cmd_info_t)); - memset(cmd_info, 0, sizeof(arg_cmd_info_t)); - -#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__)) - strncpy_s(cmd_info->name, ARG_CMD_NAME_LEN, name, strlen(name)); - strncpy_s(cmd_info->description, ARG_CMD_DESCRIPTION_LEN, description, strlen(description)); -#else - memcpy(cmd_info->name, name, strlen(name)); - memcpy(cmd_info->description, description, strlen(description)); -#endif - - cmd_info->proc = proc; - - slen_name = strlen(name); - k = xmalloc(slen_name + 1); - memset(k, 0, slen_name + 1); - -#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__)) - strncpy_s((char*)k, slen_name + 1, name, slen_name); -#else - memcpy((char*)k, name, slen_name); -#endif - - arg_hashtable_insert(s_hashtable, k, cmd_info); -} - -void arg_cmd_unregister(const char* name) { - arg_hashtable_remove(s_hashtable, name); -} - -int arg_cmd_dispatch(const char* name, int argc, char* argv[], arg_dstr_t res) { - arg_cmd_info_t* cmd_info = arg_cmd_info(name); - - assert(cmd_info != NULL); - assert(cmd_info->proc != NULL); - - return cmd_info->proc(argc, argv, res); -} - -arg_cmd_info_t* arg_cmd_info(const char* name) { - return (arg_cmd_info_t*)arg_hashtable_search(s_hashtable, name); -} - -unsigned int arg_cmd_count(void) { - return arg_hashtable_count(s_hashtable); -} - -arg_cmd_itr_t arg_cmd_itr_create(void) { - return (arg_cmd_itr_t)arg_hashtable_itr_create(s_hashtable); -} - -int arg_cmd_itr_advance(arg_cmd_itr_t itr) { - return arg_hashtable_itr_advance((arg_hashtable_itr_t*)itr); -} - -char* arg_cmd_itr_key(arg_cmd_itr_t itr) { - return (char*)arg_hashtable_itr_key((arg_hashtable_itr_t*)itr); -} - -arg_cmd_info_t* arg_cmd_itr_value(arg_cmd_itr_t itr) { - return (arg_cmd_info_t*)arg_hashtable_itr_value((arg_hashtable_itr_t*)itr); -} - -void arg_cmd_itr_destroy(arg_cmd_itr_t itr) { - arg_hashtable_itr_destroy((arg_hashtable_itr_t*)itr); -} - -int arg_cmd_itr_search(arg_cmd_itr_t itr, void* k) { - return arg_hashtable_itr_search((arg_hashtable_itr_t*)itr, s_hashtable, k); -} - -static const char* module_name(void) { - if (s_module_name == NULL || strlen(s_module_name) == 0) - return ""; - - return s_module_name; -} - -static const char* module_version(void) { - if (s_mod_ver == NULL || strlen(s_mod_ver) == 0) - return "0.0.0.0"; - - return s_mod_ver; -} - -void arg_make_get_help_msg(arg_dstr_t res) { - arg_dstr_catf(res, "%s v%s\n", module_name(), module_version()); - arg_dstr_catf(res, "Please type '%s help' to get more information.\n", module_name()); -} - -void arg_make_help_msg(arg_dstr_t ds, char* cmd_name, void** argtable) { - arg_cmd_info_t* cmd_info = (arg_cmd_info_t*)arg_hashtable_search(s_hashtable, cmd_name); - if (cmd_info) { - arg_dstr_catf(ds, "%s: %s\n", cmd_name, cmd_info->description); - } - - arg_dstr_cat(ds, "Usage:\n"); - arg_dstr_catf(ds, " %s", module_name()); - - arg_print_syntaxv_ds(ds, argtable, "\n \nAvailable options:\n"); - arg_print_glossary_ds(ds, argtable, " %-23s %s\n"); - - arg_dstr_cat(ds, "\n"); -} - -void arg_make_syntax_err_msg(arg_dstr_t ds, void** argtable, struct arg_end* end) { - arg_print_errors_ds(ds, end, module_name()); - arg_dstr_cat(ds, "Usage: \n"); - arg_dstr_catf(ds, " %s", module_name()); - arg_print_syntaxv_ds(ds, argtable, "\n"); - arg_dstr_cat(ds, "\n"); -} - -int arg_make_syntax_err_help_msg(arg_dstr_t ds, char* name, int help, int nerrors, void** argtable, struct arg_end* end, int* exitcode) { - /* help handling - * note: '-h|--help' takes precedence over error reporting - */ - if (help > 0) { - arg_make_help_msg(ds, name, argtable); - *exitcode = EXIT_SUCCESS; - return 1; - } - - /* syntax error handling */ - if (nerrors > 0) { - arg_make_syntax_err_msg(ds, argtable, end); - *exitcode = EXIT_FAILURE; - return 1; - } - - return 0; -} -/******************************************************************************* - * arg_date: Implements the date command-line option - * - * This file is part of the argtable3 library. - * - * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of STEWART HEITMANN nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -#include "argtable3.h" - -#ifndef ARG_AMALGAMATION -#include "argtable3_private.h" -#endif - -#include -#include - -char* arg_strptime(const char* buf, const char* fmt, struct tm* tm); - -static void arg_date_resetfn(struct arg_date* parent) { - ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent)); - parent->count = 0; -} - -static int arg_date_scanfn(struct arg_date* parent, const char* argval) { - int errorcode = 0; - - if (parent->count == parent->hdr.maxcount) { - errorcode = ARG_ERR_MAXCOUNT; - } else if (!argval) { - /* no argument value was given, leave parent->tmval[] unaltered but still count it */ - parent->count++; - } else { - const char* pend; - struct tm tm = parent->tmval[parent->count]; - - /* parse the given argument value, store result in parent->tmval[] */ - pend = arg_strptime(argval, parent->format, &tm); - if (pend && pend[0] == '\0') - parent->tmval[parent->count++] = tm; - else - errorcode = ARG_ERR_BADDATE; - } - - ARG_TRACE(("%s:scanfn(%p) returns %d\n", __FILE__, parent, errorcode)); - return errorcode; -} - -static int arg_date_checkfn(struct arg_date* parent) { - int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0; - - ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode)); - return errorcode; -} - -static void arg_date_errorfn(struct arg_date* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) { - const char* shortopts = parent->hdr.shortopts; - const char* longopts = parent->hdr.longopts; - const char* datatype = parent->hdr.datatype; - - /* make argval NULL safe */ - argval = argval ? argval : ""; - - arg_dstr_catf(ds, "%s: ", progname); - switch (errorcode) { - case ARG_ERR_MINCOUNT: - arg_dstr_cat(ds, "missing option "); - arg_print_option_ds(ds, shortopts, longopts, datatype, "\n"); - break; - - case ARG_ERR_MAXCOUNT: - arg_dstr_cat(ds, "excess option "); - arg_print_option_ds(ds, shortopts, longopts, argval, "\n"); - break; - - case ARG_ERR_BADDATE: { - struct tm tm; - char buff[200]; - - arg_dstr_catf(ds, "illegal timestamp format \"%s\"\n", argval); - memset(&tm, 0, sizeof(tm)); - arg_strptime("1999-12-31 23:59:59", "%F %H:%M:%S", &tm); - strftime(buff, sizeof(buff), parent->format, &tm); - arg_dstr_catf(ds, "correct format is \"%s\"\n", buff); - break; - } - } -} - -struct arg_date* arg_date0(const char* shortopts, const char* longopts, const char* format, const char* datatype, const char* glossary) { - return arg_daten(shortopts, longopts, format, datatype, 0, 1, glossary); -} - -struct arg_date* arg_date1(const char* shortopts, const char* longopts, const char* format, const char* datatype, const char* glossary) { - return arg_daten(shortopts, longopts, format, datatype, 1, 1, glossary); -} - -struct arg_date* -arg_daten(const char* shortopts, const char* longopts, const char* format, const char* datatype, int mincount, int maxcount, const char* glossary) { - size_t nbytes; - struct arg_date* result; - - /* foolproof things by ensuring maxcount is not less than mincount */ - maxcount = (maxcount < mincount) ? mincount : maxcount; - - /* default time format is the national date format for the locale */ - if (!format) - format = "%x"; - - nbytes = sizeof(struct arg_date) /* storage for struct arg_date */ - + (size_t)maxcount * sizeof(struct tm); /* storage for tmval[maxcount] array */ - - /* allocate storage for the arg_date struct + tmval[] array. */ - /* we use calloc because we want the tmval[] array zero filled. */ - result = (struct arg_date*)xcalloc(1, nbytes); - - /* init the arg_hdr struct */ - result->hdr.flag = ARG_HASVALUE; - result->hdr.shortopts = shortopts; - result->hdr.longopts = longopts; - result->hdr.datatype = datatype ? datatype : format; - result->hdr.glossary = glossary; - result->hdr.mincount = mincount; - result->hdr.maxcount = maxcount; - result->hdr.parent = result; - result->hdr.resetfn = (arg_resetfn*)arg_date_resetfn; - result->hdr.scanfn = (arg_scanfn*)arg_date_scanfn; - result->hdr.checkfn = (arg_checkfn*)arg_date_checkfn; - result->hdr.errorfn = (arg_errorfn*)arg_date_errorfn; - - /* store the tmval[maxcount] array immediately after the arg_date struct */ - result->tmval = (struct tm*)(result + 1); - - /* init the remaining arg_date member variables */ - result->count = 0; - result->format = format; - - ARG_TRACE(("arg_daten() returns %p\n", result)); - return result; -} - -/*- - * Copyright (c) 1997, 1998, 2005, 2008 The NetBSD Foundation, Inc. - * All rights reserved. - * - * This code was contributed to The NetBSD Foundation by Klaus Klein. - * Heavily optimised by David Laight - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include - -/* - * We do not implement alternate representations. However, we always - * check whether a given modifier is allowed for a certain conversion. - */ -#define ALT_E 0x01 -#define ALT_O 0x02 -#define LEGAL_ALT(x) \ - { \ - if (alt_format & ~(x)) \ - return (0); \ - } -#define TM_YEAR_BASE (1900) - -static int conv_num(const char**, int*, int, int); - -static const char* day[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; - -static const char* abday[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; - -static const char* mon[12] = {"January", "February", "March", "April", "May", "June", - "July", "August", "September", "October", "November", "December"}; - -static const char* abmon[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; - -static const char* am_pm[2] = {"AM", "PM"}; - -static int arg_strcasecmp(const char* s1, const char* s2) { - const unsigned char* us1 = (const unsigned char*)s1; - const unsigned char* us2 = (const unsigned char*)s2; - while (tolower(*us1) == tolower(*us2++)) - if (*us1++ == '\0') - return 0; - - return tolower(*us1) - tolower(*--us2); -} - -static int arg_strncasecmp(const char* s1, const char* s2, size_t n) { - if (n != 0) { - const unsigned char* us1 = (const unsigned char*)s1; - const unsigned char* us2 = (const unsigned char*)s2; - do { - if (tolower(*us1) != tolower(*us2++)) - return tolower(*us1) - tolower(*--us2); - - if (*us1++ == '\0') - break; - } while (--n != 0); - } - - return 0; -} - -char* arg_strptime(const char* buf, const char* fmt, struct tm* tm) { - char c; - const char* bp; - size_t len = 0; - int alt_format, i, split_year = 0; - - bp = buf; - - while ((c = *fmt) != '\0') { - /* Clear `alternate' modifier prior to new conversion. */ - alt_format = 0; - - /* Eat up white-space. */ - if (isspace(c)) { - while (isspace((int)(*bp))) - bp++; - - fmt++; - continue; - } - - if ((c = *fmt++) != '%') - goto literal; - - again: - switch (c = *fmt++) { - case '%': /* "%%" is converted to "%". */ - literal: - if (c != *bp++) - return (0); - break; - - /* - * "Alternative" modifiers. Just set the appropriate flag - * and start over again. - */ - case 'E': /* "%E?" alternative conversion modifier. */ - LEGAL_ALT(0); - alt_format |= ALT_E; - goto again; - - case 'O': /* "%O?" alternative conversion modifier. */ - LEGAL_ALT(0); - alt_format |= ALT_O; - goto again; - - /* - * "Complex" conversion rules, implemented through recursion. - */ - case 'c': /* Date and time, using the locale's format. */ - LEGAL_ALT(ALT_E); - bp = arg_strptime(bp, "%x %X", tm); - if (!bp) - return (0); - break; - - case 'D': /* The date as "%m/%d/%y". */ - LEGAL_ALT(0); - bp = arg_strptime(bp, "%m/%d/%y", tm); - if (!bp) - return (0); - break; - - case 'R': /* The time as "%H:%M". */ - LEGAL_ALT(0); - bp = arg_strptime(bp, "%H:%M", tm); - if (!bp) - return (0); - break; - - case 'r': /* The time in 12-hour clock representation. */ - LEGAL_ALT(0); - bp = arg_strptime(bp, "%I:%M:%S %p", tm); - if (!bp) - return (0); - break; - - case 'T': /* The time as "%H:%M:%S". */ - LEGAL_ALT(0); - bp = arg_strptime(bp, "%H:%M:%S", tm); - if (!bp) - return (0); - break; - - case 'X': /* The time, using the locale's format. */ - LEGAL_ALT(ALT_E); - bp = arg_strptime(bp, "%H:%M:%S", tm); - if (!bp) - return (0); - break; - - case 'x': /* The date, using the locale's format. */ - LEGAL_ALT(ALT_E); - bp = arg_strptime(bp, "%m/%d/%y", tm); - if (!bp) - return (0); - break; - - /* - * "Elementary" conversion rules. - */ - case 'A': /* The day of week, using the locale's form. */ - case 'a': - LEGAL_ALT(0); - for (i = 0; i < 7; i++) { - /* Full name. */ - len = strlen(day[i]); - if (arg_strncasecmp(day[i], bp, len) == 0) - break; - - /* Abbreviated name. */ - len = strlen(abday[i]); - if (arg_strncasecmp(abday[i], bp, len) == 0) - break; - } - - /* Nothing matched. */ - if (i == 7) - return (0); - - tm->tm_wday = i; - bp += len; - break; - - case 'B': /* The month, using the locale's form. */ - case 'b': - case 'h': - LEGAL_ALT(0); - for (i = 0; i < 12; i++) { - /* Full name. */ - len = strlen(mon[i]); - if (arg_strncasecmp(mon[i], bp, len) == 0) - break; - - /* Abbreviated name. */ - len = strlen(abmon[i]); - if (arg_strncasecmp(abmon[i], bp, len) == 0) - break; - } - - /* Nothing matched. */ - if (i == 12) - return (0); - - tm->tm_mon = i; - bp += len; - break; - - case 'C': /* The century number. */ - LEGAL_ALT(ALT_E); - if (!(conv_num(&bp, &i, 0, 99))) - return (0); - - if (split_year) { - tm->tm_year = (tm->tm_year % 100) + (i * 100); - } else { - tm->tm_year = i * 100; - split_year = 1; - } - break; - - case 'd': /* The day of month. */ - case 'e': - LEGAL_ALT(ALT_O); - if (!(conv_num(&bp, &tm->tm_mday, 1, 31))) - return (0); - break; - - case 'k': /* The hour (24-hour clock representation). */ - LEGAL_ALT(0); - /* FALLTHROUGH */ - case 'H': - LEGAL_ALT(ALT_O); - if (!(conv_num(&bp, &tm->tm_hour, 0, 23))) - return (0); - break; - - case 'l': /* The hour (12-hour clock representation). */ - LEGAL_ALT(0); - /* FALLTHROUGH */ - case 'I': - LEGAL_ALT(ALT_O); - if (!(conv_num(&bp, &tm->tm_hour, 1, 12))) - return (0); - if (tm->tm_hour == 12) - tm->tm_hour = 0; - break; - - case 'j': /* The day of year. */ - LEGAL_ALT(0); - if (!(conv_num(&bp, &i, 1, 366))) - return (0); - tm->tm_yday = i - 1; - break; - - case 'M': /* The minute. */ - LEGAL_ALT(ALT_O); - if (!(conv_num(&bp, &tm->tm_min, 0, 59))) - return (0); - break; - - case 'm': /* The month. */ - LEGAL_ALT(ALT_O); - if (!(conv_num(&bp, &i, 1, 12))) - return (0); - tm->tm_mon = i - 1; - break; - - case 'p': /* The locale's equivalent of AM/PM. */ - LEGAL_ALT(0); - /* AM? */ - if (arg_strcasecmp(am_pm[0], bp) == 0) { - if (tm->tm_hour > 11) - return (0); - - bp += strlen(am_pm[0]); - break; - } - /* PM? */ - else if (arg_strcasecmp(am_pm[1], bp) == 0) { - if (tm->tm_hour > 11) - return (0); - - tm->tm_hour += 12; - bp += strlen(am_pm[1]); - break; - } - - /* Nothing matched. */ - return (0); - - case 'S': /* The seconds. */ - LEGAL_ALT(ALT_O); - if (!(conv_num(&bp, &tm->tm_sec, 0, 61))) - return (0); - break; - - case 'U': /* The week of year, beginning on sunday. */ - case 'W': /* The week of year, beginning on monday. */ - LEGAL_ALT(ALT_O); - /* - * XXX This is bogus, as we can not assume any valid - * information present in the tm structure at this - * point to calculate a real value, so just check the - * range for now. - */ - if (!(conv_num(&bp, &i, 0, 53))) - return (0); - break; - - case 'w': /* The day of week, beginning on sunday. */ - LEGAL_ALT(ALT_O); - if (!(conv_num(&bp, &tm->tm_wday, 0, 6))) - return (0); - break; - - case 'Y': /* The year. */ - LEGAL_ALT(ALT_E); - if (!(conv_num(&bp, &i, 0, 9999))) - return (0); - - tm->tm_year = i - TM_YEAR_BASE; - break; - - case 'y': /* The year within 100 years of the epoch. */ - LEGAL_ALT(ALT_E | ALT_O); - if (!(conv_num(&bp, &i, 0, 99))) - return (0); - - if (split_year) { - tm->tm_year = ((tm->tm_year / 100) * 100) + i; - break; - } - split_year = 1; - if (i <= 68) - tm->tm_year = i + 2000 - TM_YEAR_BASE; - else - tm->tm_year = i + 1900 - TM_YEAR_BASE; - break; - - /* - * Miscellaneous conversions. - */ - case 'n': /* Any kind of white-space. */ - case 't': - LEGAL_ALT(0); - while (isspace((int)(*bp))) - bp++; - break; - - default: /* Unknown/unsupported conversion. */ - return (0); - } - } - - /* LINTED functional specification */ - return ((char*)bp); -} - -static int conv_num(const char** buf, int* dest, int llim, int ulim) { - int result = 0; - - /* The limit also determines the number of valid digits. */ - int rulim = ulim; - - if (**buf < '0' || **buf > '9') - return (0); - - do { - result *= 10; - result += *(*buf)++ - '0'; - rulim /= 10; - } while ((result * 10 <= ulim) && rulim && **buf >= '0' && **buf <= '9'); - - if (result < llim || result > ulim) - return (0); - - *dest = result; - return (1); -} -/******************************************************************************* - * arg_dbl: Implements the double command-line option - * - * This file is part of the argtable3 library. - * - * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of STEWART HEITMANN nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -#include "argtable3.h" - -#ifndef ARG_AMALGAMATION -#include "argtable3_private.h" -#endif - -#include - -static void arg_dbl_resetfn(struct arg_dbl* parent) { - ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent)); - parent->count = 0; -} - -static int arg_dbl_scanfn(struct arg_dbl* parent, const char* argval) { - int errorcode = 0; - - if (parent->count == parent->hdr.maxcount) { - /* maximum number of arguments exceeded */ - errorcode = ARG_ERR_MAXCOUNT; - } else if (!argval) { - /* a valid argument with no argument value was given. */ - /* This happens when an optional argument value was invoked. */ - /* leave parent argument value unaltered but still count the argument. */ - parent->count++; - } else { - double val; - char* end; - - /* extract double from argval into val */ - val = strtod(argval, &end); - - /* if success then store result in parent->dval[] array otherwise return error*/ - if (*end == 0) - parent->dval[parent->count++] = val; - else - errorcode = ARG_ERR_BADDOUBLE; - } - - ARG_TRACE(("%s:scanfn(%p) returns %d\n", __FILE__, parent, errorcode)); - return errorcode; -} - -static int arg_dbl_checkfn(struct arg_dbl* parent) { - int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0; - - ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode)); - return errorcode; -} - -static void arg_dbl_errorfn(struct arg_dbl* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) { - const char* shortopts = parent->hdr.shortopts; - const char* longopts = parent->hdr.longopts; - const char* datatype = parent->hdr.datatype; - - /* make argval NULL safe */ - argval = argval ? argval : ""; - - arg_dstr_catf(ds, "%s: ", progname); - switch (errorcode) { - case ARG_ERR_MINCOUNT: - arg_dstr_cat(ds, "missing option "); - arg_print_option_ds(ds, shortopts, longopts, datatype, "\n"); - break; - - case ARG_ERR_MAXCOUNT: - arg_dstr_cat(ds, "excess option "); - arg_print_option_ds(ds, shortopts, longopts, argval, "\n"); - break; - - case ARG_ERR_BADDOUBLE: - arg_dstr_catf(ds, "invalid argument \"%s\" to option ", argval); - arg_print_option_ds(ds, shortopts, longopts, datatype, "\n"); - break; - } -} - -struct arg_dbl* arg_dbl0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) { - return arg_dbln(shortopts, longopts, datatype, 0, 1, glossary); -} - -struct arg_dbl* arg_dbl1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) { - return arg_dbln(shortopts, longopts, datatype, 1, 1, glossary); -} - -struct arg_dbl* arg_dbln(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary) { - size_t nbytes; - struct arg_dbl* result; - size_t addr; - size_t rem; - - /* foolproof things by ensuring maxcount is not less than mincount */ - maxcount = (maxcount < mincount) ? mincount : maxcount; - - nbytes = sizeof(struct arg_dbl) /* storage for struct arg_dbl */ - + (size_t)(maxcount + 1) * sizeof(double); /* storage for dval[maxcount] array plus one extra for padding to memory boundary */ - - result = (struct arg_dbl*)xmalloc(nbytes); - - /* init the arg_hdr struct */ - result->hdr.flag = ARG_HASVALUE; - result->hdr.shortopts = shortopts; - result->hdr.longopts = longopts; - result->hdr.datatype = datatype ? datatype : ""; - result->hdr.glossary = glossary; - result->hdr.mincount = mincount; - result->hdr.maxcount = maxcount; - result->hdr.parent = result; - result->hdr.resetfn = (arg_resetfn*)arg_dbl_resetfn; - result->hdr.scanfn = (arg_scanfn*)arg_dbl_scanfn; - result->hdr.checkfn = (arg_checkfn*)arg_dbl_checkfn; - result->hdr.errorfn = (arg_errorfn*)arg_dbl_errorfn; - - /* Store the dval[maxcount] array on the first double boundary that - * immediately follows the arg_dbl struct. We do the memory alignment - * purely for SPARC and Motorola systems. They require floats and - * doubles to be aligned on natural boundaries. - */ - addr = (size_t)(result + 1); - rem = addr % sizeof(double); - result->dval = (double*)(addr + sizeof(double) - rem); - ARG_TRACE(("addr=%p, dval=%p, sizeof(double)=%d rem=%d\n", addr, result->dval, (int)sizeof(double), (int)rem)); - - result->count = 0; - - ARG_TRACE(("arg_dbln() returns %p\n", result)); - return result; -} -/******************************************************************************* - * arg_dstr: Implements the dynamic string utilities - * - * This file is part of the argtable3 library. - * - * Copyright (C) 2013-2019 Tom G. Huang - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of STEWART HEITMANN nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -#include "argtable3.h" - -#ifndef ARG_AMALGAMATION -#include "argtable3_private.h" -#endif - -#include -#include -#include - -#if defined(_MSC_VER) -#pragma warning(push) -#pragma warning(disable : 4996) -#endif - -#define START_VSNBUFF 16 - -/* - * This dynamic string module is adapted from TclResult.c in the Tcl library. - * Here is the copyright notice from the library: - * - * This software is copyrighted by the Regents of the University of - * California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState - * Corporation and other parties. The following terms apply to all files - * associated with the software unless explicitly disclaimed in - * individual files. - * - * The authors hereby grant permission to use, copy, modify, distribute, - * and license this software and its documentation for any purpose, provided - * that existing copyright notices are retained in all copies and that this - * notice is included verbatim in any distributions. No written agreement, - * license, or royalty fee is required for any of the authorized uses. - * Modifications to this software may be copyrighted by their authors - * and need not follow the licensing terms described here, provided that - * the new terms are clearly indicated on the first page of each file where - * they apply. - * - * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY - * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES - * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY - * DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE - * IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE - * NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR - * MODIFICATIONS. - * - * GOVERNMENT USE: If you are acquiring this software on behalf of the - * U.S. government, the Government shall have only "Restricted Rights" - * in the software and related documentation as defined in the Federal - * Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you - * are acquiring the software on behalf of the Department of Defense, the - * software shall be classified as "Commercial Computer Software" and the - * Government shall have only "Restricted Rights" as defined in Clause - * 252.227-7014 (b) (3) of DFARs. Notwithstanding the foregoing, the - * authors grant the U.S. Government and others acting in its behalf - * permission to use and distribute the software in accordance with the - * terms specified in this license. - */ - -typedef struct _internal_arg_dstr { - char* data; - arg_dstr_freefn* free_proc; - char sbuf[ARG_DSTR_SIZE + 1]; - char* append_data; - int append_data_size; - int append_used; -} _internal_arg_dstr_t; - -static void setup_append_buf(arg_dstr_t res, int newSpace); - -arg_dstr_t arg_dstr_create(void) { - _internal_arg_dstr_t* h = (_internal_arg_dstr_t*)xmalloc(sizeof(_internal_arg_dstr_t)); - memset(h, 0, sizeof(_internal_arg_dstr_t)); - h->sbuf[0] = 0; - h->data = h->sbuf; - h->free_proc = ARG_DSTR_STATIC; - return h; -} - -void arg_dstr_destroy(arg_dstr_t ds) { - if (ds == NULL) - return; - - arg_dstr_reset(ds); - xfree(ds); - return; -} - -void arg_dstr_set(arg_dstr_t ds, char* str, arg_dstr_freefn* free_proc) { - int length; - register arg_dstr_freefn* old_free_proc = ds->free_proc; - char* old_result = ds->data; - - if (str == NULL) { - ds->sbuf[0] = 0; - ds->data = ds->sbuf; - ds->free_proc = ARG_DSTR_STATIC; - } else if (free_proc == ARG_DSTR_VOLATILE) { - length = (int)strlen(str); - if (length > ARG_DSTR_SIZE) { - ds->data = (char*)xmalloc((unsigned)length + 1); - ds->free_proc = ARG_DSTR_DYNAMIC; - } else { - ds->data = ds->sbuf; - ds->free_proc = ARG_DSTR_STATIC; - } - strcpy(ds->data, str); - } else { - ds->data = str; - ds->free_proc = free_proc; - } - - /* - * If the old result was dynamically-allocated, free it up. Do it here, - * rather than at the beginning, in case the new result value was part of - * the old result value. - */ - - if ((old_free_proc != 0) && (old_result != ds->data)) { - if (old_free_proc == ARG_DSTR_DYNAMIC) { - xfree(old_result); - } else { - (*old_free_proc)(old_result); - } - } - - if ((ds->append_data != NULL) && (ds->append_data_size > 0)) { - xfree(ds->append_data); - ds->append_data = NULL; - ds->append_data_size = 0; - } -} - -char* arg_dstr_cstr(arg_dstr_t ds) /* Interpreter whose result to return. */ -{ - return ds->data; -} - -void arg_dstr_cat(arg_dstr_t ds, const char* str) { - setup_append_buf(ds, (int)strlen(str) + 1); - memcpy(ds->data + strlen(ds->data), str, strlen(str)); -} - -void arg_dstr_catc(arg_dstr_t ds, char c) { - setup_append_buf(ds, 2); - memcpy(ds->data + strlen(ds->data), &c, 1); -} - -/* - * The logic of the `arg_dstr_catf` function is adapted from the `bformat` - * function in The Better String Library by Paul Hsieh. Here is the copyright - * notice from the library: - * - * Copyright (c) 2014, Paul Hsieh - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * * Neither the name of bstrlib nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -void arg_dstr_catf(arg_dstr_t ds, const char* fmt, ...) { - va_list arglist; - char* buff; - int n, r; - size_t slen; - - if (fmt == NULL) - return; - - /* Since the length is not determinable beforehand, a search is - performed using the truncating "vsnprintf" call (to avoid buffer - overflows) on increasing potential sizes for the output result. */ - - if ((n = (int)(2 * strlen(fmt))) < START_VSNBUFF) - n = START_VSNBUFF; - - buff = (char*)xmalloc((size_t)(n + 2)); - memset(buff, 0, (size_t)(n + 2)); - - for (;;) { - va_start(arglist, fmt); - r = vsnprintf(buff, (size_t)(n + 1), fmt, arglist); - va_end(arglist); - - slen = strlen(buff); - if (slen < (size_t)n) - break; - - if (r > n) - n = r; - else - n += n; - - xfree(buff); - buff = (char*)xmalloc((size_t)(n + 2)); - memset(buff, 0, (size_t)(n + 2)); - } - - arg_dstr_cat(ds, buff); - xfree(buff); -} - -static void setup_append_buf(arg_dstr_t ds, int new_space) { - int total_space; - - /* - * Make the append buffer larger, if that's necessary, then copy the - * data into the append buffer and make the append buffer the official - * data. - */ - if (ds->data != ds->append_data) { - /* - * If the buffer is too big, then free it up so we go back to a - * smaller buffer. This avoids tying up memory forever after a large - * operation. - */ - if (ds->append_data_size > 500) { - xfree(ds->append_data); - ds->append_data = NULL; - ds->append_data_size = 0; - } - ds->append_used = (int)strlen(ds->data); - } else if (ds->data[ds->append_used] != 0) { - /* - * Most likely someone has modified a result created by - * arg_dstr_cat et al. so that it has a different size. Just - * recompute the size. - */ - ds->append_used = (int)strlen(ds->data); - } - - total_space = new_space + ds->append_used; - if (total_space >= ds->append_data_size) { - char* newbuf; - - if (total_space < 100) { - total_space = 200; - } else { - total_space *= 2; - } - newbuf = (char*)xmalloc((unsigned)total_space); - memset(newbuf, 0, (size_t)total_space); - strcpy(newbuf, ds->data); - if (ds->append_data != NULL) { - xfree(ds->append_data); - } - ds->append_data = newbuf; - ds->append_data_size = total_space; - } else if (ds->data != ds->append_data) { - strcpy(ds->append_data, ds->data); - } - - arg_dstr_free(ds); - ds->data = ds->append_data; -} - -void arg_dstr_free(arg_dstr_t ds) { - if (ds->free_proc != NULL) { - if (ds->free_proc == ARG_DSTR_DYNAMIC) { - xfree(ds->data); - } else { - (*ds->free_proc)(ds->data); - } - ds->free_proc = NULL; - } -} - -void arg_dstr_reset(arg_dstr_t ds) { - arg_dstr_free(ds); - if ((ds->append_data != NULL) && (ds->append_data_size > 0)) { - xfree(ds->append_data); - ds->append_data = NULL; - ds->append_data_size = 0; - } - - ds->data = ds->sbuf; - ds->sbuf[0] = 0; -} - -#if defined(_MSC_VER) -#pragma warning(pop) -#endif -/******************************************************************************* - * arg_end: Implements the error handling utilities - * - * This file is part of the argtable3 library. - * - * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of STEWART HEITMANN nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -#include "argtable3.h" - -#ifndef ARG_AMALGAMATION -#include "argtable3_private.h" -#endif - -#include - -static void arg_end_resetfn(struct arg_end* parent) { - ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent)); - parent->count = 0; -} - -static void arg_end_errorfn(void* parent, arg_dstr_t ds, int error, const char* argval, const char* progname) { - /* suppress unreferenced formal parameter warning */ - (void)parent; - - progname = progname ? progname : ""; - argval = argval ? argval : ""; - - arg_dstr_catf(ds, "%s: ", progname); - switch (error) { - case ARG_ELIMIT: - arg_dstr_cat(ds, "too many errors to display"); - break; - case ARG_EMALLOC: - arg_dstr_cat(ds, "insufficient memory"); - break; - case ARG_ENOMATCH: - arg_dstr_catf(ds, "unexpected argument \"%s\"", argval); - break; - case ARG_EMISSARG: - arg_dstr_catf(ds, "option \"%s\" requires an argument", argval); - break; - case ARG_ELONGOPT: - arg_dstr_catf(ds, "invalid option \"%s\"", argval); - break; - default: - arg_dstr_catf(ds, "invalid option \"-%c\"", error); - break; - } - - arg_dstr_cat(ds, "\n"); -} - -struct arg_end* arg_end(int maxcount) { - size_t nbytes; - struct arg_end* result; - - nbytes = sizeof(struct arg_end) + (size_t)maxcount * sizeof(int) /* storage for int error[maxcount] array*/ - + (size_t)maxcount * sizeof(void*) /* storage for void* parent[maxcount] array */ - + (size_t)maxcount * sizeof(char*); /* storage for char* argval[maxcount] array */ - - result = (struct arg_end*)xmalloc(nbytes); - - /* init the arg_hdr struct */ - result->hdr.flag = ARG_TERMINATOR; - result->hdr.shortopts = NULL; - result->hdr.longopts = NULL; - result->hdr.datatype = NULL; - result->hdr.glossary = NULL; - result->hdr.mincount = 1; - result->hdr.maxcount = maxcount; - result->hdr.parent = result; - result->hdr.resetfn = (arg_resetfn*)arg_end_resetfn; - result->hdr.scanfn = NULL; - result->hdr.checkfn = NULL; - result->hdr.errorfn = (arg_errorfn*)arg_end_errorfn; - - /* store error[maxcount] array immediately after struct arg_end */ - result->error = (int*)(result + 1); - - /* store parent[maxcount] array immediately after error[] array */ - result->parent = (void**)(result->error + maxcount); - - /* store argval[maxcount] array immediately after parent[] array */ - result->argval = (const char**)(result->parent + maxcount); - - ARG_TRACE(("arg_end(%d) returns %p\n", maxcount, result)); - return result; -} - -void arg_print_errors_ds(arg_dstr_t ds, struct arg_end* end, const char* progname) { - int i; - ARG_TRACE(("arg_errors()\n")); - for (i = 0; i < end->count; i++) { - struct arg_hdr* errorparent = (struct arg_hdr*)(end->parent[i]); - if (errorparent->errorfn) - errorparent->errorfn(end->parent[i], ds, end->error[i], end->argval[i], progname); - } -} - -void arg_print_errors(FILE* fp, struct arg_end* end, const char* progname) { - arg_dstr_t ds = arg_dstr_create(); - arg_print_errors_ds(ds, end, progname); - fputs(arg_dstr_cstr(ds), fp); - arg_dstr_destroy(ds); -} -/******************************************************************************* - * arg_file: Implements the file command-line option - * - * This file is part of the argtable3 library. - * - * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of STEWART HEITMANN nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -#include "argtable3.h" - -#ifndef ARG_AMALGAMATION -#include "argtable3_private.h" -#endif - -#include -#include - -#ifdef WIN32 -#define FILESEPARATOR1 '\\' -#define FILESEPARATOR2 '/' -#else -#define FILESEPARATOR1 '/' -#define FILESEPARATOR2 '/' -#endif - -static void arg_file_resetfn(struct arg_file* parent) { - ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent)); - parent->count = 0; -} - -/* Returns ptr to the base filename within *filename */ -static const char* arg_basename(const char* filename) { - const char *result = NULL, *result1, *result2; - - /* Find the last occurrence of eother file separator character. */ - /* Two alternative file separator chars are supported as legal */ - /* file separators but not both together in the same filename. */ - result1 = (filename ? strrchr(filename, FILESEPARATOR1) : NULL); - result2 = (filename ? strrchr(filename, FILESEPARATOR2) : NULL); - - if (result2) - result = result2 + 1; /* using FILESEPARATOR2 (the alternative file separator) */ - - if (result1) - result = result1 + 1; /* using FILESEPARATOR1 (the preferred file separator) */ - - if (!result) - result = filename; /* neither file separator was found so basename is the whole filename */ - - /* special cases of "." and ".." are not considered basenames */ - if (result && (strcmp(".", result) == 0 || strcmp("..", result) == 0)) - result = filename + strlen(filename); - - return result; -} - -/* Returns ptr to the file extension within *basename */ -static const char* arg_extension(const char* basename) { - /* find the last occurrence of '.' in basename */ - const char* result = (basename ? strrchr(basename, '.') : NULL); - - /* if no '.' was found then return pointer to end of basename */ - if (basename && !result) - result = basename + strlen(basename); - - /* special case: basenames with a single leading dot (eg ".foo") are not considered as true extensions */ - if (basename && result == basename) - result = basename + strlen(basename); - - /* special case: empty extensions (eg "foo.","foo..") are not considered as true extensions */ - if (basename && result && strlen(result) == 1) - result = basename + strlen(basename); - - return result; -} - -static int arg_file_scanfn(struct arg_file* parent, const char* argval) { - int errorcode = 0; - - if (parent->count == parent->hdr.maxcount) { - /* maximum number of arguments exceeded */ - errorcode = ARG_ERR_MAXCOUNT; - } else if (!argval) { - /* a valid argument with no argument value was given. */ - /* This happens when an optional argument value was invoked. */ - /* leave parent arguiment value unaltered but still count the argument. */ - parent->count++; - } else { - parent->filename[parent->count] = argval; - parent->basename[parent->count] = arg_basename(argval); - parent->extension[parent->count] = - arg_extension(parent->basename[parent->count]); /* only seek extensions within the basename (not the file path)*/ - parent->count++; - } - - ARG_TRACE(("%s4:scanfn(%p) returns %d\n", __FILE__, parent, errorcode)); - return errorcode; -} - -static int arg_file_checkfn(struct arg_file* parent) { - int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0; - - ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode)); - return errorcode; -} - -static void arg_file_errorfn(struct arg_file* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) { - const char* shortopts = parent->hdr.shortopts; - const char* longopts = parent->hdr.longopts; - const char* datatype = parent->hdr.datatype; - - /* make argval NULL safe */ - argval = argval ? argval : ""; - - arg_dstr_catf(ds, "%s: ", progname); - switch (errorcode) { - case ARG_ERR_MINCOUNT: - arg_dstr_cat(ds, "missing option "); - arg_print_option_ds(ds, shortopts, longopts, datatype, "\n"); - break; - - case ARG_ERR_MAXCOUNT: - arg_dstr_cat(ds, "excess option "); - arg_print_option_ds(ds, shortopts, longopts, argval, "\n"); - break; - - default: - arg_dstr_catf(ds, "unknown error at \"%s\"\n", argval); - } -} - -struct arg_file* arg_file0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) { - return arg_filen(shortopts, longopts, datatype, 0, 1, glossary); -} - -struct arg_file* arg_file1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) { - return arg_filen(shortopts, longopts, datatype, 1, 1, glossary); -} - -struct arg_file* arg_filen(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary) { - size_t nbytes; - struct arg_file* result; - int i; - - /* foolproof things by ensuring maxcount is not less than mincount */ - maxcount = (maxcount < mincount) ? mincount : maxcount; - - nbytes = sizeof(struct arg_file) /* storage for struct arg_file */ - + sizeof(char*) * (size_t)maxcount /* storage for filename[maxcount] array */ - + sizeof(char*) * (size_t)maxcount /* storage for basename[maxcount] array */ - + sizeof(char*) * (size_t)maxcount; /* storage for extension[maxcount] array */ - - result = (struct arg_file*)xmalloc(nbytes); - - /* init the arg_hdr struct */ - result->hdr.flag = ARG_HASVALUE; - result->hdr.shortopts = shortopts; - result->hdr.longopts = longopts; - result->hdr.glossary = glossary; - result->hdr.datatype = datatype ? datatype : ""; - result->hdr.mincount = mincount; - result->hdr.maxcount = maxcount; - result->hdr.parent = result; - result->hdr.resetfn = (arg_resetfn*)arg_file_resetfn; - result->hdr.scanfn = (arg_scanfn*)arg_file_scanfn; - result->hdr.checkfn = (arg_checkfn*)arg_file_checkfn; - result->hdr.errorfn = (arg_errorfn*)arg_file_errorfn; - - /* store the filename,basename,extension arrays immediately after the arg_file struct */ - result->filename = (const char**)(result + 1); - result->basename = result->filename + maxcount; - result->extension = result->basename + maxcount; - result->count = 0; - - /* foolproof the string pointers by initialising them with empty strings */ - for (i = 0; i < maxcount; i++) { - result->filename[i] = ""; - result->basename[i] = ""; - result->extension[i] = ""; - } - - ARG_TRACE(("arg_filen() returns %p\n", result)); - return result; -} -/* $NetBSD: getopt.h,v 1.4 2000/07/07 10:43:54 ad Exp $ */ -/* $FreeBSD$ */ - -/*- - * SPDX-License-Identifier: BSD-2-Clause-NetBSD - * - * Copyright (c) 2000 The NetBSD Foundation, Inc. - * All rights reserved. - * - * This code is derived from software contributed to The NetBSD Foundation - * by Dieter Baron and Thomas Klausner. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#if ARG_REPLACE_GETOPT == 1 - -#ifndef _GETOPT_H_ -#define _GETOPT_H_ - -/* - * GNU-like getopt_long()/getopt_long_only() with 4.4BSD optreset extension. - * getopt() is declared here too for GNU programs. - */ -#define no_argument 0 -#define required_argument 1 -#define optional_argument 2 - -struct option { - /* name of long option */ - const char *name; - /* - * one of no_argument, required_argument, and optional_argument: - * whether option takes an argument - */ - int has_arg; - /* if not NULL, set *flag to val when option found */ - int *flag; - /* if flag not NULL, value to set *flag to; else return value */ - int val; -}; - -#ifdef __cplusplus -extern "C" { -#endif - -int getopt_long(int, char * const *, const char *, - const struct option *, int *); -int getopt_long_only(int, char * const *, const char *, - const struct option *, int *); -#ifndef _GETOPT_DECLARED -#define _GETOPT_DECLARED -int getopt(int, char * const [], const char *); - -extern char *optarg; /* getopt(3) external variables */ -extern int optind, opterr, optopt; -#endif -#ifndef _OPTRESET_DECLARED -#define _OPTRESET_DECLARED -extern int optreset; /* getopt(3) external variable */ -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* !_GETOPT_H_ */ - -#endif /* ARG_REPLACE_GETOPT == 1 */ -/* $OpenBSD: getopt_long.c,v 1.26 2013/06/08 22:47:56 millert Exp $ */ -/* $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $ */ - -/* - * Copyright (c) 2002 Todd C. Miller - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Sponsored in part by the Defense Advanced Research Projects - * Agency (DARPA) and Air Force Research Laboratory, Air Force - * Materiel Command, USAF, under agreement number F39502-99-1-0512. - */ -/*- - * Copyright (c) 2000 The NetBSD Foundation, Inc. - * All rights reserved. - * - * This code is derived from software contributed to The NetBSD Foundation - * by Dieter Baron and Thomas Klausner. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include "argtable3.h" - -#if ARG_REPLACE_GETOPT == 1 - -#ifndef ARG_AMALGAMATION -#endif - -#include -#include -#include - -#define GNU_COMPATIBLE /* Be more compatible, configure's use us! */ - -int opterr = 1; /* if error message should be printed */ -int optind = 1; /* index into parent argv vector */ -int optopt = '?'; /* character checked for validity */ -int optreset; /* reset getopt */ -char *optarg; /* argument associated with option */ - -#define PRINT_ERROR ((opterr) && (*options != ':')) - -#define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */ -#define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */ -#define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */ - -/* return values */ -#define BADCH (int)'?' -#define BADARG ((*options == ':') ? (int)':' : (int)'?') -#define INORDER (int)1 - -#define EMSG "" - -#ifdef GNU_COMPATIBLE -#define NO_PREFIX (-1) -#define D_PREFIX 0 -#define DD_PREFIX 1 -#define W_PREFIX 2 -#endif - -static int getopt_internal(int, char * const *, const char *, - const struct option *, int *, int); -static int parse_long_options(char * const *, const char *, - const struct option *, int *, int, int); -static int gcd(int, int); -static void permute_args(int, int, int, char * const *); - -static char *place = EMSG; /* option letter processing */ - -/* XXX: set optreset to 1 rather than these two */ -static int nonopt_start = -1; /* first non option argument (for permute) */ -static int nonopt_end = -1; /* first option after non options (for permute) */ - -/* Error messages */ -static const char recargchar[] = "option requires an argument -- %c"; -static const char illoptchar[] = "illegal option -- %c"; /* From P1003.2 */ -#ifdef GNU_COMPATIBLE -static int dash_prefix = NO_PREFIX; -static const char gnuoptchar[] = "invalid option -- %c"; - -static const char recargstring[] = "option `%s%s' requires an argument"; -static const char ambig[] = "option `%s%.*s' is ambiguous"; -static const char noarg[] = "option `%s%.*s' doesn't allow an argument"; -static const char illoptstring[] = "unrecognized option `%s%s'"; -#else -static const char recargstring[] = "option requires an argument -- %s"; -static const char ambig[] = "ambiguous option -- %.*s"; -static const char noarg[] = "option doesn't take an argument -- %.*s"; -static const char illoptstring[] = "unknown option -- %s"; -#endif - -#ifdef _WIN32 - -/* - * Windows needs warnx(). We change the definition though: - * 1. (another) global is defined, opterrmsg, which holds the error message - * 2. errors are always printed out on stderr w/o the program name - * Note that opterrmsg always gets set no matter what opterr is set to. The - * error message will not be printed if opterr is 0 as usual. - */ - -#include -#include - -#define MAX_OPTERRMSG_SIZE 128 - -extern char opterrmsg[MAX_OPTERRMSG_SIZE]; -char opterrmsg[MAX_OPTERRMSG_SIZE]; /* buffer for the last error message */ - -static void warnx(const char* fmt, ...) { - va_list ap; - va_start(ap, fmt); - - /* - * Make sure opterrmsg is always zero-terminated despite the _vsnprintf() - * implementation specifics and manually suppress the warning. - */ - memset(opterrmsg, 0, sizeof(opterrmsg)); - if (fmt != NULL) -#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__)) - _vsnprintf_s(opterrmsg, sizeof(opterrmsg), sizeof(opterrmsg) - 1, fmt, ap); -#else - _vsnprintf(opterrmsg, sizeof(opterrmsg) - 1, fmt, ap); -#endif - - va_end(ap); - -#ifdef _MSC_VER -#pragma warning(suppress : 6053) -#endif - fprintf(stderr, "%s\n", opterrmsg); -} - -#else -#include -#endif /*_WIN32*/ -/* - * Compute the greatest common divisor of a and b. - */ -static int -gcd(int a, int b) -{ - int c; - - c = a % b; - while (c != 0) { - a = b; - b = c; - c = a % b; - } - - return (b); -} - -/* - * Exchange the block from nonopt_start to nonopt_end with the block - * from nonopt_end to opt_end (keeping the same order of arguments - * in each block). - */ -static void -permute_args(int panonopt_start, int panonopt_end, int opt_end, - char * const *nargv) -{ - int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos; - char *swap; - - /* - * compute lengths of blocks and number and size of cycles - */ - nnonopts = panonopt_end - panonopt_start; - nopts = opt_end - panonopt_end; - ncycle = gcd(nnonopts, nopts); - cyclelen = (opt_end - panonopt_start) / ncycle; - - for (i = 0; i < ncycle; i++) { - cstart = panonopt_end+i; - pos = cstart; - for (j = 0; j < cyclelen; j++) { - if (pos >= panonopt_end) - pos -= nnonopts; - else - pos += nopts; - swap = nargv[pos]; - /* LINTED const cast */ - ((char **) nargv)[pos] = nargv[cstart]; - /* LINTED const cast */ - ((char **)nargv)[cstart] = swap; - } - } -} - -/* - * parse_long_options -- - * Parse long options in argc/argv argument vector. - * Returns -1 if short_too is set and the option does not match long_options. - */ -static int -parse_long_options(char * const *nargv, const char *options, - const struct option *long_options, int *idx, int short_too, int flags) -{ - char *current_argv, *has_equal; -#ifdef GNU_COMPATIBLE - char *current_dash; -#endif - size_t current_argv_len; - int i, match, exact_match, second_partial_match; - - current_argv = place; -#ifdef GNU_COMPATIBLE - switch (dash_prefix) { - case D_PREFIX: - current_dash = "-"; - break; - case DD_PREFIX: - current_dash = "--"; - break; - case W_PREFIX: - current_dash = "-W "; - break; - default: - current_dash = ""; - break; - } -#endif - match = -1; - exact_match = 0; - second_partial_match = 0; - - optind++; - - if ((has_equal = strchr(current_argv, '=')) != NULL) { - /* argument found (--option=arg) */ - current_argv_len = (size_t)(has_equal - current_argv); - has_equal++; - } else - current_argv_len = strlen(current_argv); - - for (i = 0; long_options[i].name; i++) { - /* find matching long option */ - if (strncmp(current_argv, long_options[i].name, - current_argv_len)) - continue; - - if (strlen(long_options[i].name) == current_argv_len) { - /* exact match */ - match = i; - exact_match = 1; - break; - } - /* - * If this is a known short option, don't allow - * a partial match of a single character. - */ - if (short_too && current_argv_len == 1) - continue; - - if (match == -1) /* first partial match */ - match = i; - else if ((flags & FLAG_LONGONLY) || - long_options[i].has_arg != - long_options[match].has_arg || - long_options[i].flag != long_options[match].flag || - long_options[i].val != long_options[match].val) - second_partial_match = 1; - } - if (!exact_match && second_partial_match) { - /* ambiguous abbreviation */ - if (PRINT_ERROR) - warnx(ambig, -#ifdef GNU_COMPATIBLE - current_dash, -#endif - (int)current_argv_len, - current_argv); - optopt = 0; - return (BADCH); - } - if (match != -1) { /* option found */ - if (long_options[match].has_arg == no_argument - && has_equal) { - if (PRINT_ERROR) - warnx(noarg, -#ifdef GNU_COMPATIBLE - current_dash, -#endif - (int)current_argv_len, - current_argv); - /* - * XXX: GNU sets optopt to val regardless of flag - */ - if (long_options[match].flag == NULL) - optopt = long_options[match].val; - else - optopt = 0; -#ifdef GNU_COMPATIBLE - return (BADCH); -#else - return (BADARG); -#endif - } - if (long_options[match].has_arg == required_argument || - long_options[match].has_arg == optional_argument) { - if (has_equal) - optarg = has_equal; - else if (long_options[match].has_arg == - required_argument) { - /* - * optional argument doesn't use next nargv - */ - optarg = nargv[optind++]; - } - } - if ((long_options[match].has_arg == required_argument) - && (optarg == NULL)) { - /* - * Missing argument; leading ':' indicates no error - * should be generated. - */ - if (PRINT_ERROR) - warnx(recargstring, -#ifdef GNU_COMPATIBLE - current_dash, -#endif - current_argv); - /* - * XXX: GNU sets optopt to val regardless of flag - */ - if (long_options[match].flag == NULL) - optopt = long_options[match].val; - else - optopt = 0; - --optind; - return (BADARG); - } - } else { /* unknown option */ - if (short_too) { - --optind; - return (-1); - } - if (PRINT_ERROR) - warnx(illoptstring, -#ifdef GNU_COMPATIBLE - current_dash, -#endif - current_argv); - optopt = 0; - return (BADCH); - } - if (idx) - *idx = match; - if (long_options[match].flag) { - *long_options[match].flag = long_options[match].val; - return (0); - } else - return (long_options[match].val); -} - -/* - * getopt_internal -- - * Parse argc/argv argument vector. Called by user level routines. - */ -static int -getopt_internal(int nargc, char * const *nargv, const char *options, - const struct option *long_options, int *idx, int flags) -{ - char *oli; /* option letter list index */ - int optchar, short_too; - static int posixly_correct = -1; - - if (options == NULL) - return (-1); - - /* - * XXX Some GNU programs (like cvs) set optind to 0 instead of - * XXX using optreset. Work around this braindamage. - */ - if (optind == 0) - optind = optreset = 1; - - /* - * Disable GNU extensions if POSIXLY_CORRECT is set or options - * string begins with a '+'. - */ - if (posixly_correct == -1 || optreset) { -#if defined(_WIN32) && ((defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))) - size_t requiredSize; - getenv_s(&requiredSize, NULL, 0, "POSIXLY_CORRECT"); - posixly_correct = requiredSize != 0; -#else - posixly_correct = (getenv("POSIXLY_CORRECT") != NULL); -#endif - } - - if (*options == '-') - flags |= FLAG_ALLARGS; - else if (posixly_correct || *options == '+') - flags &= ~FLAG_PERMUTE; - if (*options == '+' || *options == '-') - options++; - - optarg = NULL; - if (optreset) - nonopt_start = nonopt_end = -1; -start: - if (optreset || !*place) { /* update scanning pointer */ - optreset = 0; - if (optind >= nargc) { /* end of argument vector */ - place = EMSG; - if (nonopt_end != -1) { - /* do permutation, if we have to */ - permute_args(nonopt_start, nonopt_end, - optind, nargv); - optind -= nonopt_end - nonopt_start; - } - else if (nonopt_start != -1) { - /* - * If we skipped non-options, set optind - * to the first of them. - */ - optind = nonopt_start; - } - nonopt_start = nonopt_end = -1; - return (-1); - } - if (*(place = nargv[optind]) != '-' || -#ifdef GNU_COMPATIBLE - place[1] == '\0') { -#else - (place[1] == '\0' && strchr(options, '-') == NULL)) { -#endif - place = EMSG; /* found non-option */ - if (flags & FLAG_ALLARGS) { - /* - * GNU extension: - * return non-option as argument to option 1 - */ - optarg = nargv[optind++]; - return (INORDER); - } - if (!(flags & FLAG_PERMUTE)) { - /* - * If no permutation wanted, stop parsing - * at first non-option. - */ - return (-1); - } - /* do permutation */ - if (nonopt_start == -1) - nonopt_start = optind; - else if (nonopt_end != -1) { - permute_args(nonopt_start, nonopt_end, - optind, nargv); - nonopt_start = optind - - (nonopt_end - nonopt_start); - nonopt_end = -1; - } - optind++; - /* process next argument */ - goto start; - } - if (nonopt_start != -1 && nonopt_end == -1) - nonopt_end = optind; - - /* - * If we have "-" do nothing, if "--" we are done. - */ - if (place[1] != '\0' && *++place == '-' && place[1] == '\0') { - optind++; - place = EMSG; - /* - * We found an option (--), so if we skipped - * non-options, we have to permute. - */ - if (nonopt_end != -1) { - permute_args(nonopt_start, nonopt_end, - optind, nargv); - optind -= nonopt_end - nonopt_start; - } - nonopt_start = nonopt_end = -1; - return (-1); - } - } - - /* - * Check long options if: - * 1) we were passed some - * 2) the arg is not just "-" - * 3) either the arg starts with -- we are getopt_long_only() - */ - if (long_options != NULL && place != nargv[optind] && - (*place == '-' || (flags & FLAG_LONGONLY))) { - short_too = 0; -#ifdef GNU_COMPATIBLE - dash_prefix = D_PREFIX; -#endif - if (*place == '-') { - place++; /* --foo long option */ - if (*place == '\0') - return (BADARG); /* malformed option */ -#ifdef GNU_COMPATIBLE - dash_prefix = DD_PREFIX; -#endif - } else if (*place != ':' && strchr(options, *place) != NULL) - short_too = 1; /* could be short option too */ - - optchar = parse_long_options(nargv, options, long_options, - idx, short_too, flags); - if (optchar != -1) { - place = EMSG; - return (optchar); - } - } - - if ((optchar = (int)*place++) == (int)':' || - (optchar == (int)'-' && *place != '\0') || - (oli = strchr(options, optchar)) == NULL) { - /* - * If the user specified "-" and '-' isn't listed in - * options, return -1 (non-option) as per POSIX. - * Otherwise, it is an unknown option character (or ':'). - */ - if (optchar == (int)'-' && *place == '\0') - return (-1); - if (!*place) - ++optind; -#ifdef GNU_COMPATIBLE - if (PRINT_ERROR) - warnx(posixly_correct ? illoptchar : gnuoptchar, - optchar); -#else - if (PRINT_ERROR) - warnx(illoptchar, optchar); -#endif - optopt = optchar; - return (BADCH); - } - if (long_options != NULL && optchar == 'W' && oli[1] == ';') { - /* -W long-option */ - if (*place) /* no space */ - /* NOTHING */; - else if (++optind >= nargc) { /* no arg */ - place = EMSG; - if (PRINT_ERROR) - warnx(recargchar, optchar); - optopt = optchar; - return (BADARG); - } else /* white space */ - place = nargv[optind]; -#ifdef GNU_COMPATIBLE - dash_prefix = W_PREFIX; -#endif - optchar = parse_long_options(nargv, options, long_options, - idx, 0, flags); - place = EMSG; - return (optchar); - } - if (*++oli != ':') { /* doesn't take argument */ - if (!*place) - ++optind; - } else { /* takes (optional) argument */ - optarg = NULL; - if (*place) /* no white space */ - optarg = place; - else if (oli[1] != ':') { /* arg not optional */ - if (++optind >= nargc) { /* no arg */ - place = EMSG; - if (PRINT_ERROR) - warnx(recargchar, optchar); - optopt = optchar; - return (BADARG); - } else - optarg = nargv[optind]; - } - place = EMSG; - ++optind; - } - /* dump back option letter */ - return (optchar); -} - -/* - * getopt -- - * Parse argc/argv argument vector. - * - * [eventually this will replace the BSD getopt] - */ -int -getopt(int nargc, char * const *nargv, const char *options) -{ - - /* - * We don't pass FLAG_PERMUTE to getopt_internal() since - * the BSD getopt(3) (unlike GNU) has never done this. - * - * Furthermore, since many privileged programs call getopt() - * before dropping privileges it makes sense to keep things - * as simple (and bug-free) as possible. - */ - return (getopt_internal(nargc, nargv, options, NULL, NULL, 0)); -} - -/* - * getopt_long -- - * Parse argc/argv argument vector. - */ -int -getopt_long(int nargc, char * const *nargv, const char *options, - const struct option *long_options, int *idx) -{ - - return (getopt_internal(nargc, nargv, options, long_options, idx, - FLAG_PERMUTE)); -} - -/* - * getopt_long_only -- - * Parse argc/argv argument vector. - */ -int -getopt_long_only(int nargc, char * const *nargv, const char *options, - const struct option *long_options, int *idx) -{ - - return (getopt_internal(nargc, nargv, options, long_options, idx, - FLAG_PERMUTE|FLAG_LONGONLY)); -} - -#endif /* ARG_REPLACE_GETOPT == 1 */ -/******************************************************************************* - * arg_hashtable: Implements the hash table utilities - * - * This file is part of the argtable3 library. - * - * Copyright (C) 2013-2019 Tom G. Huang - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of STEWART HEITMANN nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -#ifndef ARG_AMALGAMATION -#include "argtable3_private.h" -#endif - -#include -#include -#include -#include - -/* - * This hash table module is adapted from the C hash table implementation by - * Christopher Clark. Here is the copyright notice from the library: - * - * Copyright (c) 2002, Christopher Clark - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of the original author; nor the names of any contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * Credit for primes table: Aaron Krowne - * http://br.endernet.org/~akrowne/ - * http://planetmath.org/encyclopedia/GoodHashTablePrimes.html - */ -static const unsigned int primes[] = {53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, - 24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469, - 12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741}; -const unsigned int prime_table_length = sizeof(primes) / sizeof(primes[0]); -const float max_load_factor = (float)0.65; - -static unsigned int enhanced_hash(arg_hashtable_t* h, const void* k) { - /* - * Aim to protect against poor hash functions by adding logic here. - * The logic is taken from Java 1.4 hash table source. - */ - unsigned int i = h->hashfn(k); - i += ~(i << 9); - i ^= ((i >> 14) | (i << 18)); /* >>> */ - i += (i << 4); - i ^= ((i >> 10) | (i << 22)); /* >>> */ - return i; -} - -static unsigned int index_for(unsigned int tablelength, unsigned int hashvalue) { - return (hashvalue % tablelength); -} - -arg_hashtable_t* arg_hashtable_create(unsigned int minsize, unsigned int (*hashfn)(const void*), int (*eqfn)(const void*, const void*)) { - arg_hashtable_t* h; - unsigned int pindex; - unsigned int size = primes[0]; - - /* Check requested hash table isn't too large */ - if (minsize > (1u << 30)) - return NULL; - - /* - * Enforce size as prime. The reason is to avoid clustering of values - * into a small number of buckets (yes, distribution). A more even - * distributed hash table will perform more consistently. - */ - for (pindex = 0; pindex < prime_table_length; pindex++) { - if (primes[pindex] > minsize) { - size = primes[pindex]; - break; - } - } - - h = (arg_hashtable_t*)xmalloc(sizeof(arg_hashtable_t)); - h->table = (struct arg_hashtable_entry**)xmalloc(sizeof(struct arg_hashtable_entry*) * size); - memset(h->table, 0, size * sizeof(struct arg_hashtable_entry*)); - h->tablelength = size; - h->primeindex = pindex; - h->entrycount = 0; - h->hashfn = hashfn; - h->eqfn = eqfn; - h->loadlimit = (unsigned int)ceil(size * (double)max_load_factor); - return h; -} - -static int arg_hashtable_expand(arg_hashtable_t* h) { - /* Double the size of the table to accommodate more entries */ - struct arg_hashtable_entry** newtable; - struct arg_hashtable_entry* e; - unsigned int newsize; - unsigned int i; - unsigned int index; - - /* Check we're not hitting max capacity */ - if (h->primeindex == (prime_table_length - 1)) - return 0; - newsize = primes[++(h->primeindex)]; - - newtable = (struct arg_hashtable_entry**)xmalloc(sizeof(struct arg_hashtable_entry*) * newsize); - memset(newtable, 0, newsize * sizeof(struct arg_hashtable_entry*)); - /* - * This algorithm is not 'stable': it reverses the list - * when it transfers entries between the tables - */ - for (i = 0; i < h->tablelength; i++) { - while (NULL != (e = h->table[i])) { - h->table[i] = e->next; - index = index_for(newsize, e->h); - e->next = newtable[index]; - newtable[index] = e; - } - } - - xfree(h->table); - h->table = newtable; - h->tablelength = newsize; - h->loadlimit = (unsigned int)ceil(newsize * (double)max_load_factor); - return -1; -} - -unsigned int arg_hashtable_count(arg_hashtable_t* h) { - return h->entrycount; -} - -void arg_hashtable_insert(arg_hashtable_t* h, void* k, void* v) { - /* This method allows duplicate keys - but they shouldn't be used */ - unsigned int index; - struct arg_hashtable_entry* e; - if ((h->entrycount + 1) > h->loadlimit) { - /* - * Ignore the return value. If expand fails, we should - * still try cramming just this value into the existing table - * -- we may not have memory for a larger table, but one more - * element may be ok. Next time we insert, we'll try expanding again. - */ - arg_hashtable_expand(h); - } - e = (struct arg_hashtable_entry*)xmalloc(sizeof(struct arg_hashtable_entry)); - e->h = enhanced_hash(h, k); - index = index_for(h->tablelength, e->h); - e->k = k; - e->v = v; - e->next = h->table[index]; - h->table[index] = e; - h->entrycount++; -} - -void* arg_hashtable_search(arg_hashtable_t* h, const void* k) { - struct arg_hashtable_entry* e; - unsigned int hashvalue; - unsigned int index; - - hashvalue = enhanced_hash(h, k); - index = index_for(h->tablelength, hashvalue); - e = h->table[index]; - while (e != NULL) { - /* Check hash value to short circuit heavier comparison */ - if ((hashvalue == e->h) && (h->eqfn(k, e->k))) - return e->v; - e = e->next; - } - return NULL; -} - -void arg_hashtable_remove(arg_hashtable_t* h, const void* k) { - /* - * TODO: consider compacting the table when the load factor drops enough, - * or provide a 'compact' method. - */ - - struct arg_hashtable_entry* e; - struct arg_hashtable_entry** pE; - unsigned int hashvalue; - unsigned int index; - - hashvalue = enhanced_hash(h, k); - index = index_for(h->tablelength, hashvalue); - pE = &(h->table[index]); - e = *pE; - while (NULL != e) { - /* Check hash value to short circuit heavier comparison */ - if ((hashvalue == e->h) && (h->eqfn(k, e->k))) { - *pE = e->next; - h->entrycount--; - xfree(e->k); - xfree(e->v); - xfree(e); - return; - } - pE = &(e->next); - e = e->next; - } -} - -void arg_hashtable_destroy(arg_hashtable_t* h, int free_values) { - unsigned int i; - struct arg_hashtable_entry *e, *f; - struct arg_hashtable_entry** table = h->table; - if (free_values) { - for (i = 0; i < h->tablelength; i++) { - e = table[i]; - while (NULL != e) { - f = e; - e = e->next; - xfree(f->k); - xfree(f->v); - xfree(f); - } - } - } else { - for (i = 0; i < h->tablelength; i++) { - e = table[i]; - while (NULL != e) { - f = e; - e = e->next; - xfree(f->k); - xfree(f); - } - } - } - xfree(h->table); - xfree(h); -} - -arg_hashtable_itr_t* arg_hashtable_itr_create(arg_hashtable_t* h) { - unsigned int i; - unsigned int tablelength; - - arg_hashtable_itr_t* itr = (arg_hashtable_itr_t*)xmalloc(sizeof(arg_hashtable_itr_t)); - itr->h = h; - itr->e = NULL; - itr->parent = NULL; - tablelength = h->tablelength; - itr->index = tablelength; - if (0 == h->entrycount) - return itr; - - for (i = 0; i < tablelength; i++) { - if (h->table[i] != NULL) { - itr->e = h->table[i]; - itr->index = i; - break; - } - } - return itr; -} - -void arg_hashtable_itr_destroy(arg_hashtable_itr_t* itr) { - xfree(itr); -} - -void* arg_hashtable_itr_key(arg_hashtable_itr_t* i) { - return i->e->k; -} - -void* arg_hashtable_itr_value(arg_hashtable_itr_t* i) { - return i->e->v; -} - -int arg_hashtable_itr_advance(arg_hashtable_itr_t* itr) { - unsigned int j; - unsigned int tablelength; - struct arg_hashtable_entry** table; - struct arg_hashtable_entry* next; - - if (itr->e == NULL) - return 0; /* stupidity check */ - - next = itr->e->next; - if (NULL != next) { - itr->parent = itr->e; - itr->e = next; - return -1; - } - - tablelength = itr->h->tablelength; - itr->parent = NULL; - if (tablelength <= (j = ++(itr->index))) { - itr->e = NULL; - return 0; - } - - table = itr->h->table; - while (NULL == (next = table[j])) { - if (++j >= tablelength) { - itr->index = tablelength; - itr->e = NULL; - return 0; - } - } - - itr->index = j; - itr->e = next; - return -1; -} - -int arg_hashtable_itr_remove(arg_hashtable_itr_t* itr) { - struct arg_hashtable_entry* remember_e; - struct arg_hashtable_entry* remember_parent; - int ret; - - /* Do the removal */ - if ((itr->parent) == NULL) { - /* element is head of a chain */ - itr->h->table[itr->index] = itr->e->next; - } else { - /* element is mid-chain */ - itr->parent->next = itr->e->next; - } - /* itr->e is now outside the hashtable */ - remember_e = itr->e; - itr->h->entrycount--; - xfree(remember_e->k); - xfree(remember_e->v); - - /* Advance the iterator, correcting the parent */ - remember_parent = itr->parent; - ret = arg_hashtable_itr_advance(itr); - if (itr->parent == remember_e) { - itr->parent = remember_parent; - } - xfree(remember_e); - return ret; -} - -int arg_hashtable_itr_search(arg_hashtable_itr_t* itr, arg_hashtable_t* h, void* k) { - struct arg_hashtable_entry* e; - struct arg_hashtable_entry* parent; - unsigned int hashvalue; - unsigned int index; - - hashvalue = enhanced_hash(h, k); - index = index_for(h->tablelength, hashvalue); - - e = h->table[index]; - parent = NULL; - while (e != NULL) { - /* Check hash value to short circuit heavier comparison */ - if ((hashvalue == e->h) && (h->eqfn(k, e->k))) { - itr->index = index; - itr->e = e; - itr->parent = parent; - itr->h = h; - return -1; - } - parent = e; - e = e->next; - } - return 0; -} - -int arg_hashtable_change(arg_hashtable_t* h, void* k, void* v) { - struct arg_hashtable_entry* e; - unsigned int hashvalue; - unsigned int index; - - hashvalue = enhanced_hash(h, k); - index = index_for(h->tablelength, hashvalue); - e = h->table[index]; - while (e != NULL) { - /* Check hash value to short circuit heavier comparison */ - if ((hashvalue == e->h) && (h->eqfn(k, e->k))) { - xfree(e->v); - e->v = v; - return -1; - } - e = e->next; - } - return 0; -} -/******************************************************************************* - * arg_int: Implements the int command-line option - * - * This file is part of the argtable3 library. - * - * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of STEWART HEITMANN nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -#include "argtable3.h" - -#ifndef ARG_AMALGAMATION -#include "argtable3_private.h" -#endif - -#include -#include -#include - -static void arg_int_resetfn(struct arg_int* parent) { - ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent)); - parent->count = 0; -} - -/* strtol0x() is like strtol() except that the numeric string is */ -/* expected to be prefixed by "0X" where X is a user supplied char. */ -/* The string may optionally be prefixed by white space and + or - */ -/* as in +0X123 or -0X123. */ -/* Once the prefix has been scanned, the remainder of the numeric */ -/* string is converted using strtol() with the given base. */ -/* eg: to parse hex str="-0X12324", specify X='X' and base=16. */ -/* eg: to parse oct str="+0o12324", specify X='O' and base=8. */ -/* eg: to parse bin str="-0B01010", specify X='B' and base=2. */ -/* Failure of conversion is indicated by result where *endptr==str. */ -static long int strtol0X(const char* str, const char** endptr, char X, int base) { - long int val; /* stores result */ - int s = 1; /* sign is +1 or -1 */ - const char* ptr = str; /* ptr to current position in str */ - - /* skip leading whitespace */ - while (isspace((int)(*ptr))) - ptr++; - /* printf("1) %s\n",ptr); */ - - /* scan optional sign character */ - switch (*ptr) { - case '+': - ptr++; - s = 1; - break; - case '-': - ptr++; - s = -1; - break; - default: - s = 1; - break; - } - /* printf("2) %s\n",ptr); */ - - /* '0X' prefix */ - if ((*ptr++) != '0') { - /* printf("failed to detect '0'\n"); */ - *endptr = str; - return 0; - } - /* printf("3) %s\n",ptr); */ - if (toupper(*ptr++) != toupper(X)) { - /* printf("failed to detect '%c'\n",X); */ - *endptr = str; - return 0; - } - /* printf("4) %s\n",ptr); */ - - /* attempt conversion on remainder of string using strtol() */ - val = strtol(ptr, (char**)endptr, base); - if (*endptr == ptr) { - /* conversion failed */ - *endptr = str; - return 0; - } - - /* success */ - return s * val; -} - -/* Returns 1 if str matches suffix (case insensitive). */ -/* Str may contain trailing whitespace, but nothing else. */ -static int detectsuffix(const char* str, const char* suffix) { - /* scan pairwise through strings until mismatch detected */ - while (toupper(*str) == toupper(*suffix)) { - /* printf("'%c' '%c'\n", *str, *suffix); */ - - /* return 1 (success) if match persists until the string terminator */ - if (*str == '\0') - return 1; - - /* next chars */ - str++; - suffix++; - } - /* printf("'%c' '%c' mismatch\n", *str, *suffix); */ - - /* return 0 (fail) if the matching did not consume the entire suffix */ - if (*suffix != 0) - return 0; /* failed to consume entire suffix */ - - /* skip any remaining whitespace in str */ - while (isspace((int)(*str))) - str++; - - /* return 1 (success) if we have reached end of str else return 0 (fail) */ - return (*str == '\0') ? 1 : 0; -} - -static int arg_int_scanfn(struct arg_int* parent, const char* argval) { - int errorcode = 0; - - if (parent->count == parent->hdr.maxcount) { - /* maximum number of arguments exceeded */ - errorcode = ARG_ERR_MAXCOUNT; - } else if (!argval) { - /* a valid argument with no argument value was given. */ - /* This happens when an optional argument value was invoked. */ - /* leave parent arguiment value unaltered but still count the argument. */ - parent->count++; - } else { - long int val; - const char* end; - - /* attempt to extract hex integer (eg: +0x123) from argval into val conversion */ - val = strtol0X(argval, &end, 'X', 16); - if (end == argval) { - /* hex failed, attempt octal conversion (eg +0o123) */ - val = strtol0X(argval, &end, 'O', 8); - if (end == argval) { - /* octal failed, attempt binary conversion (eg +0B101) */ - val = strtol0X(argval, &end, 'B', 2); - if (end == argval) { - /* binary failed, attempt decimal conversion with no prefix (eg 1234) */ - val = strtol(argval, (char**)&end, 10); - if (end == argval) { - /* all supported number formats failed */ - return ARG_ERR_BADINT; - } - } - } - } - - /* Safety check for integer overflow. WARNING: this check */ - /* achieves nothing on machines where size(int)==size(long). */ - if (val > INT_MAX || val < INT_MIN) - errorcode = ARG_ERR_OVERFLOW; - - /* Detect any suffixes (KB,MB,GB) and multiply argument value appropriately. */ - /* We need to be mindful of integer overflows when using such big numbers. */ - if (detectsuffix(end, "KB")) /* kilobytes */ - { - if (val > (INT_MAX / 1024) || val < (INT_MIN / 1024)) - errorcode = ARG_ERR_OVERFLOW; /* Overflow would occur if we proceed */ - else - val *= 1024; /* 1KB = 1024 */ - } else if (detectsuffix(end, "MB")) /* megabytes */ - { - if (val > (INT_MAX / 1048576) || val < (INT_MIN / 1048576)) - errorcode = ARG_ERR_OVERFLOW; /* Overflow would occur if we proceed */ - else - val *= 1048576; /* 1MB = 1024*1024 */ - } else if (detectsuffix(end, "GB")) /* gigabytes */ - { - if (val > (INT_MAX / 1073741824) || val < (INT_MIN / 1073741824)) - errorcode = ARG_ERR_OVERFLOW; /* Overflow would occur if we proceed */ - else - val *= 1073741824; /* 1GB = 1024*1024*1024 */ - } else if (!detectsuffix(end, "")) - errorcode = ARG_ERR_BADINT; /* invalid suffix detected */ - - /* if success then store result in parent->ival[] array */ - if (errorcode == 0) - parent->ival[parent->count++] = (int)val; - } - - /* printf("%s:scanfn(%p,%p) returns %d\n",__FILE__,parent,argval,errorcode); */ - return errorcode; -} - -static int arg_int_checkfn(struct arg_int* parent) { - int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0; - /*printf("%s:checkfn(%p) returns %d\n",__FILE__,parent,errorcode);*/ - return errorcode; -} - -static void arg_int_errorfn(struct arg_int* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) { - const char* shortopts = parent->hdr.shortopts; - const char* longopts = parent->hdr.longopts; - const char* datatype = parent->hdr.datatype; - - /* make argval NULL safe */ - argval = argval ? argval : ""; - - arg_dstr_catf(ds, "%s: ", progname); - switch (errorcode) { - case ARG_ERR_MINCOUNT: - arg_dstr_cat(ds, "missing option "); - arg_print_option_ds(ds, shortopts, longopts, datatype, "\n"); - break; - - case ARG_ERR_MAXCOUNT: - arg_dstr_cat(ds, "excess option "); - arg_print_option_ds(ds, shortopts, longopts, argval, "\n"); - break; - - case ARG_ERR_BADINT: - arg_dstr_catf(ds, "invalid argument \"%s\" to option ", argval); - arg_print_option_ds(ds, shortopts, longopts, datatype, "\n"); - break; - - case ARG_ERR_OVERFLOW: - arg_dstr_cat(ds, "integer overflow at option "); - arg_print_option_ds(ds, shortopts, longopts, datatype, " "); - arg_dstr_catf(ds, "(%s is too large)\n", argval); - break; - } -} - -struct arg_int* arg_int0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) { - return arg_intn(shortopts, longopts, datatype, 0, 1, glossary); -} - -struct arg_int* arg_int1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) { - return arg_intn(shortopts, longopts, datatype, 1, 1, glossary); -} - -struct arg_int* arg_intn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary) { - size_t nbytes; - struct arg_int* result; - - /* foolproof things by ensuring maxcount is not less than mincount */ - maxcount = (maxcount < mincount) ? mincount : maxcount; - - nbytes = sizeof(struct arg_int) /* storage for struct arg_int */ - + (size_t)maxcount * sizeof(int); /* storage for ival[maxcount] array */ - - result = (struct arg_int*)xmalloc(nbytes); - - /* init the arg_hdr struct */ - result->hdr.flag = ARG_HASVALUE; - result->hdr.shortopts = shortopts; - result->hdr.longopts = longopts; - result->hdr.datatype = datatype ? datatype : ""; - result->hdr.glossary = glossary; - result->hdr.mincount = mincount; - result->hdr.maxcount = maxcount; - result->hdr.parent = result; - result->hdr.resetfn = (arg_resetfn*)arg_int_resetfn; - result->hdr.scanfn = (arg_scanfn*)arg_int_scanfn; - result->hdr.checkfn = (arg_checkfn*)arg_int_checkfn; - result->hdr.errorfn = (arg_errorfn*)arg_int_errorfn; - - /* store the ival[maxcount] array immediately after the arg_int struct */ - result->ival = (int*)(result + 1); - result->count = 0; - - ARG_TRACE(("arg_intn() returns %p\n", result)); - return result; -} -/******************************************************************************* - * arg_lit: Implements the literature command-line option - * - * This file is part of the argtable3 library. - * - * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of STEWART HEITMANN nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -#include "argtable3.h" - -#ifndef ARG_AMALGAMATION -#include "argtable3_private.h" -#endif - -#include - -static void arg_lit_resetfn(struct arg_lit* parent) { - ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent)); - parent->count = 0; -} - -static int arg_lit_scanfn(struct arg_lit* parent, const char* argval) { - int errorcode = 0; - if (parent->count < parent->hdr.maxcount) - parent->count++; - else - errorcode = ARG_ERR_MAXCOUNT; - - ARG_TRACE(("%s:scanfn(%p,%s) returns %d\n", __FILE__, parent, argval, errorcode)); - return errorcode; -} - -static int arg_lit_checkfn(struct arg_lit* parent) { - int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0; - ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode)); - return errorcode; -} - -static void arg_lit_errorfn(struct arg_lit* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) { - const char* shortopts = parent->hdr.shortopts; - const char* longopts = parent->hdr.longopts; - const char* datatype = parent->hdr.datatype; - - switch (errorcode) { - case ARG_ERR_MINCOUNT: - arg_dstr_catf(ds, "%s: missing option ", progname); - arg_print_option_ds(ds, shortopts, longopts, datatype, "\n"); - arg_dstr_cat(ds, "\n"); - break; - - case ARG_ERR_MAXCOUNT: - arg_dstr_catf(ds, "%s: extraneous option ", progname); - arg_print_option_ds(ds, shortopts, longopts, datatype, "\n"); - break; - } - - ARG_TRACE(("%s:errorfn(%p, %p, %d, %s, %s)\n", __FILE__, parent, ds, errorcode, argval, progname)); -} - -struct arg_lit* arg_lit0(const char* shortopts, const char* longopts, const char* glossary) { - return arg_litn(shortopts, longopts, 0, 1, glossary); -} - -struct arg_lit* arg_lit1(const char* shortopts, const char* longopts, const char* glossary) { - return arg_litn(shortopts, longopts, 1, 1, glossary); -} - -struct arg_lit* arg_litn(const char* shortopts, const char* longopts, int mincount, int maxcount, const char* glossary) { - struct arg_lit* result; - - /* foolproof things by ensuring maxcount is not less than mincount */ - maxcount = (maxcount < mincount) ? mincount : maxcount; - - result = (struct arg_lit*)xmalloc(sizeof(struct arg_lit)); - - /* init the arg_hdr struct */ - result->hdr.flag = 0; - result->hdr.shortopts = shortopts; - result->hdr.longopts = longopts; - result->hdr.datatype = NULL; - result->hdr.glossary = glossary; - result->hdr.mincount = mincount; - result->hdr.maxcount = maxcount; - result->hdr.parent = result; - result->hdr.resetfn = (arg_resetfn*)arg_lit_resetfn; - result->hdr.scanfn = (arg_scanfn*)arg_lit_scanfn; - result->hdr.checkfn = (arg_checkfn*)arg_lit_checkfn; - result->hdr.errorfn = (arg_errorfn*)arg_lit_errorfn; - - /* init local variables */ - result->count = 0; - - ARG_TRACE(("arg_litn() returns %p\n", result)); - return result; -} -/******************************************************************************* - * arg_rem: Implements the rem command-line option - * - * This file is part of the argtable3 library. - * - * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of STEWART HEITMANN nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -#include "argtable3.h" - -#ifndef ARG_AMALGAMATION -#include "argtable3_private.h" -#endif - -#include - -struct arg_rem* arg_rem(const char* datatype, const char* glossary) { - struct arg_rem* result = (struct arg_rem*)xmalloc(sizeof(struct arg_rem)); - - result->hdr.flag = 0; - result->hdr.shortopts = NULL; - result->hdr.longopts = NULL; - result->hdr.datatype = datatype; - result->hdr.glossary = glossary; - result->hdr.mincount = 1; - result->hdr.maxcount = 1; - result->hdr.parent = result; - result->hdr.resetfn = NULL; - result->hdr.scanfn = NULL; - result->hdr.checkfn = NULL; - result->hdr.errorfn = NULL; - - ARG_TRACE(("arg_rem() returns %p\n", result)); - return result; -} -/******************************************************************************* - * arg_rex: Implements the regex command-line option - * - * This file is part of the argtable3 library. - * - * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of STEWART HEITMANN nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -#include "argtable3.h" - -#ifndef ARG_AMALGAMATION -#include "argtable3_private.h" -#endif - -#include -#include - -#ifndef _TREX_H_ -#define _TREX_H_ - -/* - * This module uses the T-Rex regular expression library to implement the regex - * logic. Here is the copyright notice of the library: - * - * Copyright (C) 2003-2006 Alberto Demichelis - * - * This software is provided 'as-is', without any express - * or implied warranty. In no event will the authors be held - * liable for any damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for - * any purpose, including commercial applications, and to alter - * it and redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; - * you must not claim that you wrote the original software. - * If you use this software in a product, an acknowledgment - * in the product documentation would be appreciated but - * is not required. - * - * 2. Altered source versions must be plainly marked as such, - * and must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any - * source distribution. - */ - -#ifdef __cplusplus -extern "C" { -#endif - -#define TRexChar char -#define MAX_CHAR 0xFF -#define _TREXC(c) (c) -#define trex_strlen strlen -#define trex_printf printf - -#ifndef TREX_API -#define TREX_API extern -#endif - -#define TRex_True 1 -#define TRex_False 0 - -#define TREX_ICASE ARG_REX_ICASE - -typedef unsigned int TRexBool; -typedef struct TRex TRex; - -typedef struct { - const TRexChar* begin; - int len; -} TRexMatch; - -#if defined(__clang__) -TREX_API TRex* trex_compile(const TRexChar* pattern, const TRexChar** error, int flags) __attribute__((optnone)); -#elif defined(__GNUC__) -TREX_API TRex* trex_compile(const TRexChar* pattern, const TRexChar** error, int flags) __attribute__((optimize(0))); -#else -TREX_API TRex* trex_compile(const TRexChar* pattern, const TRexChar** error, int flags); -#endif -TREX_API void trex_free(TRex* exp); -TREX_API TRexBool trex_match(TRex* exp, const TRexChar* text); -TREX_API TRexBool trex_search(TRex* exp, const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end); -TREX_API TRexBool -trex_searchrange(TRex* exp, const TRexChar* text_begin, const TRexChar* text_end, const TRexChar** out_begin, const TRexChar** out_end); -TREX_API int trex_getsubexpcount(TRex* exp); -TREX_API TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch* subexp); - -#ifdef __cplusplus -} -#endif - -#endif - -struct privhdr { - const char* pattern; - int flags; -}; - -static void arg_rex_resetfn(struct arg_rex* parent) { - ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent)); - parent->count = 0; -} - -static int arg_rex_scanfn(struct arg_rex* parent, const char* argval) { - int errorcode = 0; - const TRexChar* error = NULL; - TRex* rex = NULL; - TRexBool is_match = TRex_False; - - if (parent->count == parent->hdr.maxcount) { - /* maximum number of arguments exceeded */ - errorcode = ARG_ERR_MAXCOUNT; - } else if (!argval) { - /* a valid argument with no argument value was given. */ - /* This happens when an optional argument value was invoked. */ - /* leave parent argument value unaltered but still count the argument. */ - parent->count++; - } else { - struct privhdr* priv = (struct privhdr*)parent->hdr.priv; - - /* test the current argument value for a match with the regular expression */ - /* if a match is detected, record the argument value in the arg_rex struct */ - - rex = trex_compile(priv->pattern, &error, priv->flags); - is_match = trex_match(rex, argval); - if (!is_match) - errorcode = ARG_ERR_REGNOMATCH; - else - parent->sval[parent->count++] = argval; - - trex_free(rex); - } - - ARG_TRACE(("%s:scanfn(%p) returns %d\n", __FILE__, parent, errorcode)); - return errorcode; -} - -static int arg_rex_checkfn(struct arg_rex* parent) { - int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0; -#if 0 - struct privhdr *priv = (struct privhdr*)parent->hdr.priv; - - /* free the regex "program" we constructed in resetfn */ - regfree(&(priv->regex)); - - /*printf("%s:checkfn(%p) returns %d\n",__FILE__,parent,errorcode);*/ -#endif - return errorcode; -} - -static void arg_rex_errorfn(struct arg_rex* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) { - const char* shortopts = parent->hdr.shortopts; - const char* longopts = parent->hdr.longopts; - const char* datatype = parent->hdr.datatype; - - /* make argval NULL safe */ - argval = argval ? argval : ""; - - arg_dstr_catf(ds, "%s: ", progname); - switch (errorcode) { - case ARG_ERR_MINCOUNT: - arg_dstr_cat(ds, "missing option "); - arg_print_option_ds(ds, shortopts, longopts, datatype, "\n"); - break; - - case ARG_ERR_MAXCOUNT: - arg_dstr_cat(ds, "excess option "); - arg_print_option_ds(ds, shortopts, longopts, argval, "\n"); - break; - - case ARG_ERR_REGNOMATCH: - arg_dstr_cat(ds, "illegal value "); - arg_print_option_ds(ds, shortopts, longopts, argval, "\n"); - break; - - default: { - #if 0 - char errbuff[256]; - regerror(errorcode, NULL, errbuff, sizeof(errbuff)); - printf("%s\n", errbuff); - #endif - } break; - } -} - -struct arg_rex* arg_rex0(const char* shortopts, const char* longopts, const char* pattern, const char* datatype, int flags, const char* glossary) { - return arg_rexn(shortopts, longopts, pattern, datatype, 0, 1, flags, glossary); -} - -struct arg_rex* arg_rex1(const char* shortopts, const char* longopts, const char* pattern, const char* datatype, int flags, const char* glossary) { - return arg_rexn(shortopts, longopts, pattern, datatype, 1, 1, flags, glossary); -} - -struct arg_rex* arg_rexn(const char* shortopts, - const char* longopts, - const char* pattern, - const char* datatype, - int mincount, - int maxcount, - int flags, - const char* glossary) { - size_t nbytes; - struct arg_rex* result; - struct privhdr* priv; - int i; - const TRexChar* error = NULL; - TRex* rex = NULL; - - if (!pattern) { - printf("argtable: ERROR - illegal regular expression pattern \"(NULL)\"\n"); - printf("argtable: Bad argument table.\n"); - return NULL; - } - - /* foolproof things by ensuring maxcount is not less than mincount */ - maxcount = (maxcount < mincount) ? mincount : maxcount; - - nbytes = sizeof(struct arg_rex) /* storage for struct arg_rex */ - + sizeof(struct privhdr) /* storage for private arg_rex data */ - + (size_t)maxcount * sizeof(char*); /* storage for sval[maxcount] array */ - - /* init the arg_hdr struct */ - result = (struct arg_rex*)xmalloc(nbytes); - result->hdr.flag = ARG_HASVALUE; - result->hdr.shortopts = shortopts; - result->hdr.longopts = longopts; - result->hdr.datatype = datatype ? datatype : pattern; - result->hdr.glossary = glossary; - result->hdr.mincount = mincount; - result->hdr.maxcount = maxcount; - result->hdr.parent = result; - result->hdr.resetfn = (arg_resetfn*)arg_rex_resetfn; - result->hdr.scanfn = (arg_scanfn*)arg_rex_scanfn; - result->hdr.checkfn = (arg_checkfn*)arg_rex_checkfn; - result->hdr.errorfn = (arg_errorfn*)arg_rex_errorfn; - - /* store the arg_rex_priv struct immediately after the arg_rex struct */ - result->hdr.priv = result + 1; - priv = (struct privhdr*)(result->hdr.priv); - priv->pattern = pattern; - priv->flags = flags; - - /* store the sval[maxcount] array immediately after the arg_rex_priv struct */ - result->sval = (const char**)(priv + 1); - result->count = 0; - - /* foolproof the string pointers by initializing them to reference empty strings */ - for (i = 0; i < maxcount; i++) - result->sval[i] = ""; - - /* here we construct and destroy a regex representation of the regular - * expression for no other reason than to force any regex errors to be - * trapped now rather than later. If we don't, then errors may go undetected - * until an argument is actually parsed. - */ - - rex = trex_compile(priv->pattern, &error, priv->flags); - if (rex == NULL) { - ARG_LOG(("argtable: %s \"%s\"\n", error ? error : _TREXC("undefined"), priv->pattern)); - ARG_LOG(("argtable: Bad argument table.\n")); - } - - trex_free(rex); - - ARG_TRACE(("arg_rexn() returns %p\n", result)); - return result; -} - -/* see copyright notice in trex.h */ -#include -#include -#include -#include - -#ifdef _UINCODE -#define scisprint iswprint -#define scstrlen wcslen -#define scprintf wprintf -#define _SC(x) L(x) -#else -#define scisprint isprint -#define scstrlen strlen -#define scprintf printf -#define _SC(x) (x) -#endif - -#ifdef ARG_REX_DEBUG -#include - -static const TRexChar* g_nnames[] = {_SC("NONE"), _SC("OP_GREEDY"), _SC("OP_OR"), _SC("OP_EXPR"), _SC("OP_NOCAPEXPR"), - _SC("OP_DOT"), _SC("OP_CLASS"), _SC("OP_CCLASS"), _SC("OP_NCLASS"), _SC("OP_RANGE"), - _SC("OP_CHAR"), _SC("OP_EOL"), _SC("OP_BOL"), _SC("OP_WB")}; - -#endif -#define OP_GREEDY (MAX_CHAR + 1) /* * + ? {n} */ -#define OP_OR (MAX_CHAR + 2) -#define OP_EXPR (MAX_CHAR + 3) /* parentesis () */ -#define OP_NOCAPEXPR (MAX_CHAR + 4) /* parentesis (?:) */ -#define OP_DOT (MAX_CHAR + 5) -#define OP_CLASS (MAX_CHAR + 6) -#define OP_CCLASS (MAX_CHAR + 7) -#define OP_NCLASS (MAX_CHAR + 8) /* negates class the [^ */ -#define OP_RANGE (MAX_CHAR + 9) -#define OP_CHAR (MAX_CHAR + 10) -#define OP_EOL (MAX_CHAR + 11) -#define OP_BOL (MAX_CHAR + 12) -#define OP_WB (MAX_CHAR + 13) - -#define TREX_SYMBOL_ANY_CHAR ('.') -#define TREX_SYMBOL_GREEDY_ONE_OR_MORE ('+') -#define TREX_SYMBOL_GREEDY_ZERO_OR_MORE ('*') -#define TREX_SYMBOL_GREEDY_ZERO_OR_ONE ('?') -#define TREX_SYMBOL_BRANCH ('|') -#define TREX_SYMBOL_END_OF_STRING ('$') -#define TREX_SYMBOL_BEGINNING_OF_STRING ('^') -#define TREX_SYMBOL_ESCAPE_CHAR ('\\') - -typedef int TRexNodeType; - -typedef struct tagTRexNode { - TRexNodeType type; - int left; - int right; - int next; -} TRexNode; - -struct TRex { - const TRexChar* _eol; - const TRexChar* _bol; - const TRexChar* _p; - int _first; - int _op; - TRexNode* _nodes; - int _nallocated; - int _nsize; - int _nsubexpr; - TRexMatch* _matches; - int _currsubexp; - void* _jmpbuf; - const TRexChar** _error; - int _flags; -}; - -static int trex_list(TRex* exp); - -static int trex_newnode(TRex* exp, TRexNodeType type) { - TRexNode n; - int newid; - n.type = type; - n.next = n.right = n.left = -1; - if (type == OP_EXPR) - n.right = exp->_nsubexpr++; - if (exp->_nallocated < (exp->_nsize + 1)) { - exp->_nallocated *= 2; - exp->_nodes = (TRexNode*)xrealloc(exp->_nodes, (size_t)exp->_nallocated * sizeof(TRexNode)); - } - exp->_nodes[exp->_nsize++] = n; - newid = exp->_nsize - 1; - return (int)newid; -} - -static void trex_error(TRex* exp, const TRexChar* error) { - if (exp->_error) - *exp->_error = error; - longjmp(*((jmp_buf*)exp->_jmpbuf), -1); -} - -static void trex_expect(TRex* exp, int n) { - if ((*exp->_p) != n) - trex_error(exp, _SC("expected paren")); - exp->_p++; -} - -static TRexChar trex_escapechar(TRex* exp) { - if (*exp->_p == TREX_SYMBOL_ESCAPE_CHAR) { - exp->_p++; - switch (*exp->_p) { - case 'v': - exp->_p++; - return '\v'; - case 'n': - exp->_p++; - return '\n'; - case 't': - exp->_p++; - return '\t'; - case 'r': - exp->_p++; - return '\r'; - case 'f': - exp->_p++; - return '\f'; - default: - return (*exp->_p++); - } - } else if (!scisprint((int)(*exp->_p))) - trex_error(exp, _SC("letter expected")); - return (*exp->_p++); -} - -static int trex_charclass(TRex* exp, int classid) { - int n = trex_newnode(exp, OP_CCLASS); - exp->_nodes[n].left = classid; - return n; -} - -static int trex_charnode(TRex* exp, TRexBool isclass) { - TRexChar t; - if (*exp->_p == TREX_SYMBOL_ESCAPE_CHAR) { - exp->_p++; - switch (*exp->_p) { - case 'n': - exp->_p++; - return trex_newnode(exp, '\n'); - case 't': - exp->_p++; - return trex_newnode(exp, '\t'); - case 'r': - exp->_p++; - return trex_newnode(exp, '\r'); - case 'f': - exp->_p++; - return trex_newnode(exp, '\f'); - case 'v': - exp->_p++; - return trex_newnode(exp, '\v'); - case 'a': - case 'A': - case 'w': - case 'W': - case 's': - case 'S': - case 'd': - case 'D': - case 'x': - case 'X': - case 'c': - case 'C': - case 'p': - case 'P': - case 'l': - case 'u': { - t = *exp->_p; - exp->_p++; - return trex_charclass(exp, t); - } - case 'b': - case 'B': - if (!isclass) { - int node = trex_newnode(exp, OP_WB); - exp->_nodes[node].left = *exp->_p; - exp->_p++; - return node; - } - /* fall through */ - default: - t = *exp->_p; - exp->_p++; - return trex_newnode(exp, t); - } - } else if (!scisprint((int)(*exp->_p))) { - trex_error(exp, _SC("letter expected")); - } - t = *exp->_p; - exp->_p++; - return trex_newnode(exp, t); -} -static int trex_class(TRex* exp) { - int ret = -1; - int first = -1, chain; - if (*exp->_p == TREX_SYMBOL_BEGINNING_OF_STRING) { - ret = trex_newnode(exp, OP_NCLASS); - exp->_p++; - } else - ret = trex_newnode(exp, OP_CLASS); - - if (*exp->_p == ']') - trex_error(exp, _SC("empty class")); - chain = ret; - while (*exp->_p != ']' && exp->_p != exp->_eol) { - if (*exp->_p == '-' && first != -1) { - int r, t; - if (*exp->_p++ == ']') - trex_error(exp, _SC("unfinished range")); - r = trex_newnode(exp, OP_RANGE); - if (first > *exp->_p) - trex_error(exp, _SC("invalid range")); - if (exp->_nodes[first].type == OP_CCLASS) - trex_error(exp, _SC("cannot use character classes in ranges")); - exp->_nodes[r].left = exp->_nodes[first].type; - t = trex_escapechar(exp); - exp->_nodes[r].right = t; - exp->_nodes[chain].next = r; - chain = r; - first = -1; - } else { - if (first != -1) { - int c = first; - exp->_nodes[chain].next = c; - chain = c; - first = trex_charnode(exp, TRex_True); - } else { - first = trex_charnode(exp, TRex_True); - } - } - } - if (first != -1) { - int c = first; - exp->_nodes[chain].next = c; - chain = c; - first = -1; - } - /* hack? */ - exp->_nodes[ret].left = exp->_nodes[ret].next; - exp->_nodes[ret].next = -1; - return ret; -} - -static int trex_parsenumber(TRex* exp) { - int ret = *exp->_p - '0'; - int positions = 10; - exp->_p++; - while (isdigit((int)(*exp->_p))) { - ret = ret * 10 + (*exp->_p++ - '0'); - if (positions == 1000000000) - trex_error(exp, _SC("overflow in numeric constant")); - positions *= 10; - }; - return ret; -} - -static int trex_element(TRex* exp) { - int ret = -1; - switch (*exp->_p) { - case '(': { - int expr, newn; - exp->_p++; - - if (*exp->_p == '?') { - exp->_p++; - trex_expect(exp, ':'); - expr = trex_newnode(exp, OP_NOCAPEXPR); - } else - expr = trex_newnode(exp, OP_EXPR); - newn = trex_list(exp); - exp->_nodes[expr].left = newn; - ret = expr; - trex_expect(exp, ')'); - } break; - case '[': - exp->_p++; - ret = trex_class(exp); - trex_expect(exp, ']'); - break; - case TREX_SYMBOL_END_OF_STRING: - exp->_p++; - ret = trex_newnode(exp, OP_EOL); - break; - case TREX_SYMBOL_ANY_CHAR: - exp->_p++; - ret = trex_newnode(exp, OP_DOT); - break; - default: - ret = trex_charnode(exp, TRex_False); - break; - } - - { - TRexBool isgreedy = TRex_False; - unsigned short p0 = 0, p1 = 0; - switch (*exp->_p) { - case TREX_SYMBOL_GREEDY_ZERO_OR_MORE: - p0 = 0; - p1 = 0xFFFF; - exp->_p++; - isgreedy = TRex_True; - break; - case TREX_SYMBOL_GREEDY_ONE_OR_MORE: - p0 = 1; - p1 = 0xFFFF; - exp->_p++; - isgreedy = TRex_True; - break; - case TREX_SYMBOL_GREEDY_ZERO_OR_ONE: - p0 = 0; - p1 = 1; - exp->_p++; - isgreedy = TRex_True; - break; - case '{': - exp->_p++; - if (!isdigit((int)(*exp->_p))) - trex_error(exp, _SC("number expected")); - p0 = (unsigned short)trex_parsenumber(exp); - /*******************************/ - switch (*exp->_p) { - case '}': - p1 = p0; - exp->_p++; - break; - case ',': - exp->_p++; - p1 = 0xFFFF; - if (isdigit((int)(*exp->_p))) { - p1 = (unsigned short)trex_parsenumber(exp); - } - trex_expect(exp, '}'); - break; - default: - trex_error(exp, _SC(", or } expected")); - } - /*******************************/ - isgreedy = TRex_True; - break; - } - if (isgreedy) { - int nnode = trex_newnode(exp, OP_GREEDY); - exp->_nodes[nnode].left = ret; - exp->_nodes[nnode].right = ((p0) << 16) | p1; - ret = nnode; - } - } - if ((*exp->_p != TREX_SYMBOL_BRANCH) && (*exp->_p != ')') && (*exp->_p != TREX_SYMBOL_GREEDY_ZERO_OR_MORE) && - (*exp->_p != TREX_SYMBOL_GREEDY_ONE_OR_MORE) && (*exp->_p != '\0')) { - int nnode = trex_element(exp); - exp->_nodes[ret].next = nnode; - } - - return ret; -} - -static int trex_list(TRex* exp) { - int ret = -1, e; - if (*exp->_p == TREX_SYMBOL_BEGINNING_OF_STRING) { - exp->_p++; - ret = trex_newnode(exp, OP_BOL); - } - e = trex_element(exp); - if (ret != -1) { - exp->_nodes[ret].next = e; - } else - ret = e; - - if (*exp->_p == TREX_SYMBOL_BRANCH) { - int temp, tright; - exp->_p++; - temp = trex_newnode(exp, OP_OR); - exp->_nodes[temp].left = ret; - tright = trex_list(exp); - exp->_nodes[temp].right = tright; - ret = temp; - } - return ret; -} - -static TRexBool trex_matchcclass(int cclass, TRexChar c) { - switch (cclass) { - case 'a': - return isalpha(c) ? TRex_True : TRex_False; - case 'A': - return !isalpha(c) ? TRex_True : TRex_False; - case 'w': - return (isalnum(c) || c == '_') ? TRex_True : TRex_False; - case 'W': - return (!isalnum(c) && c != '_') ? TRex_True : TRex_False; - case 's': - return isspace(c) ? TRex_True : TRex_False; - case 'S': - return !isspace(c) ? TRex_True : TRex_False; - case 'd': - return isdigit(c) ? TRex_True : TRex_False; - case 'D': - return !isdigit(c) ? TRex_True : TRex_False; - case 'x': - return isxdigit(c) ? TRex_True : TRex_False; - case 'X': - return !isxdigit(c) ? TRex_True : TRex_False; - case 'c': - return iscntrl(c) ? TRex_True : TRex_False; - case 'C': - return !iscntrl(c) ? TRex_True : TRex_False; - case 'p': - return ispunct(c) ? TRex_True : TRex_False; - case 'P': - return !ispunct(c) ? TRex_True : TRex_False; - case 'l': - return islower(c) ? TRex_True : TRex_False; - case 'u': - return isupper(c) ? TRex_True : TRex_False; - } - return TRex_False; /*cannot happen*/ -} - -static TRexBool trex_matchclass(TRex* exp, TRexNode* node, TRexChar c) { - do { - switch (node->type) { - case OP_RANGE: - if (exp->_flags & TREX_ICASE) { - if (c >= toupper(node->left) && c <= toupper(node->right)) - return TRex_True; - if (c >= tolower(node->left) && c <= tolower(node->right)) - return TRex_True; - } else { - if (c >= node->left && c <= node->right) - return TRex_True; - } - break; - case OP_CCLASS: - if (trex_matchcclass(node->left, c)) - return TRex_True; - break; - default: - if (exp->_flags & TREX_ICASE) { - if (c == tolower(node->type) || c == toupper(node->type)) - return TRex_True; - } else { - if (c == node->type) - return TRex_True; - } - } - } while ((node->next != -1) && ((node = &exp->_nodes[node->next]) != NULL)); - return TRex_False; -} - -static const TRexChar* trex_matchnode(TRex* exp, TRexNode* node, const TRexChar* str, TRexNode* next) { - TRexNodeType type = node->type; - switch (type) { - case OP_GREEDY: { - /* TRexNode *greedystop = (node->next != -1) ? &exp->_nodes[node->next] : NULL; */ - TRexNode* greedystop = NULL; - int p0 = (node->right >> 16) & 0x0000FFFF, p1 = node->right & 0x0000FFFF, nmaches = 0; - const TRexChar *s = str, *good = str; - - if (node->next != -1) { - greedystop = &exp->_nodes[node->next]; - } else { - greedystop = next; - } - - while ((nmaches == 0xFFFF || nmaches < p1)) { - const TRexChar* stop; - if ((s = trex_matchnode(exp, &exp->_nodes[node->left], s, greedystop)) == NULL) - break; - nmaches++; - good = s; - if (greedystop) { - /* checks that 0 matches satisfy the expression(if so skips) */ - /* if not would always stop(for instance if is a '?') */ - if (greedystop->type != OP_GREEDY || (greedystop->type == OP_GREEDY && ((greedystop->right >> 16) & 0x0000FFFF) != 0)) { - TRexNode* gnext = NULL; - if (greedystop->next != -1) { - gnext = &exp->_nodes[greedystop->next]; - } else if (next && next->next != -1) { - gnext = &exp->_nodes[next->next]; - } - stop = trex_matchnode(exp, greedystop, s, gnext); - if (stop) { - /* if satisfied stop it */ - if (p0 == p1 && p0 == nmaches) - break; - else if (nmaches >= p0 && p1 == 0xFFFF) - break; - else if (nmaches >= p0 && nmaches <= p1) - break; - } - } - } - - if (s >= exp->_eol) - break; - } - if (p0 == p1 && p0 == nmaches) - return good; - else if (nmaches >= p0 && p1 == 0xFFFF) - return good; - else if (nmaches >= p0 && nmaches <= p1) - return good; - return NULL; - } - case OP_OR: { - const TRexChar* asd = str; - TRexNode* temp = &exp->_nodes[node->left]; - while ((asd = trex_matchnode(exp, temp, asd, NULL)) != NULL) { - if (temp->next != -1) - temp = &exp->_nodes[temp->next]; - else - return asd; - } - asd = str; - temp = &exp->_nodes[node->right]; - while ((asd = trex_matchnode(exp, temp, asd, NULL)) != NULL) { - if (temp->next != -1) - temp = &exp->_nodes[temp->next]; - else - return asd; - } - return NULL; - break; - } - case OP_EXPR: - case OP_NOCAPEXPR: { - TRexNode* n = &exp->_nodes[node->left]; - const TRexChar* cur = str; - int capture = -1; - if (node->type != OP_NOCAPEXPR && node->right == exp->_currsubexp) { - capture = exp->_currsubexp; - exp->_matches[capture].begin = cur; - exp->_currsubexp++; - } - - do { - TRexNode* subnext = NULL; - if (n->next != -1) { - subnext = &exp->_nodes[n->next]; - } else { - subnext = next; - } - if ((cur = trex_matchnode(exp, n, cur, subnext)) == NULL) { - if (capture != -1) { - exp->_matches[capture].begin = 0; - exp->_matches[capture].len = 0; - } - return NULL; - } - } while ((n->next != -1) && ((n = &exp->_nodes[n->next]) != NULL)); - - if (capture != -1) - exp->_matches[capture].len = (int)(cur - exp->_matches[capture].begin); - return cur; - } - case OP_WB: - if ((str == exp->_bol && !isspace((int)(*str))) || (str == exp->_eol && !isspace((int)(*(str - 1)))) || (!isspace((int)(*str)) && isspace((int)(*(str + 1)))) || - (isspace((int)(*str)) && !isspace((int)(*(str + 1))))) { - return (node->left == 'b') ? str : NULL; - } - return (node->left == 'b') ? NULL : str; - case OP_BOL: - if (str == exp->_bol) - return str; - return NULL; - case OP_EOL: - if (str == exp->_eol) - return str; - return NULL; - case OP_DOT: { - str++; - } - return str; - case OP_NCLASS: - case OP_CLASS: - if (trex_matchclass(exp, &exp->_nodes[node->left], *str) ? (type == OP_CLASS ? TRex_True : TRex_False) - : (type == OP_NCLASS ? TRex_True : TRex_False)) { - str++; - return str; - } - return NULL; - case OP_CCLASS: - if (trex_matchcclass(node->left, *str)) { - str++; - return str; - } - return NULL; - default: /* char */ - if (exp->_flags & TREX_ICASE) { - if (*str != tolower(node->type) && *str != toupper(node->type)) - return NULL; - } else { - if (*str != node->type) - return NULL; - } - str++; - return str; - } -} - -/* public api */ -TRex* trex_compile(const TRexChar* pattern, const TRexChar** error, int flags) { - TRex* exp = (TRex*)xmalloc(sizeof(TRex)); - exp->_eol = exp->_bol = NULL; - exp->_p = pattern; - exp->_nallocated = (int)(scstrlen(pattern) * sizeof(TRexChar)); - exp->_nodes = (TRexNode*)xmalloc((size_t)exp->_nallocated * sizeof(TRexNode)); - exp->_nsize = 0; - exp->_matches = 0; - exp->_nsubexpr = 0; - exp->_first = trex_newnode(exp, OP_EXPR); - exp->_error = error; - exp->_jmpbuf = xmalloc(sizeof(jmp_buf)); - exp->_flags = flags; - if (setjmp(*((jmp_buf*)exp->_jmpbuf)) == 0) { - int res = trex_list(exp); - exp->_nodes[exp->_first].left = res; - if (*exp->_p != '\0') - trex_error(exp, _SC("unexpected character")); -#ifdef ARG_REX_DEBUG - { - int nsize, i; - nsize = exp->_nsize; - scprintf(_SC("\n")); - for (i = 0; i < nsize; i++) { - if (exp->_nodes[i].type > MAX_CHAR) - scprintf(_SC("[%02d] %10s "), i, g_nnames[exp->_nodes[i].type - MAX_CHAR]); - else - scprintf(_SC("[%02d] %10c "), i, exp->_nodes[i].type); - scprintf(_SC("left %02d right %02d next %02d\n"), exp->_nodes[i].left, exp->_nodes[i].right, exp->_nodes[i].next); - } - scprintf(_SC("\n")); - } -#endif - exp->_matches = (TRexMatch*)xmalloc((size_t)exp->_nsubexpr * sizeof(TRexMatch)); - memset(exp->_matches, 0, (size_t)exp->_nsubexpr * sizeof(TRexMatch)); - } else { - trex_free(exp); - return NULL; - } - return exp; -} - -void trex_free(TRex* exp) { - if (exp) { - xfree(exp->_nodes); - xfree(exp->_jmpbuf); - xfree(exp->_matches); - xfree(exp); - } -} - -TRexBool trex_match(TRex* exp, const TRexChar* text) { - const TRexChar* res = NULL; - exp->_bol = text; - exp->_eol = text + scstrlen(text); - exp->_currsubexp = 0; - res = trex_matchnode(exp, exp->_nodes, text, NULL); - if (res == NULL || res != exp->_eol) - return TRex_False; - return TRex_True; -} - -TRexBool trex_searchrange(TRex* exp, const TRexChar* text_begin, const TRexChar* text_end, const TRexChar** out_begin, const TRexChar** out_end) { - const TRexChar* cur = NULL; - int node = exp->_first; - if (text_begin >= text_end) - return TRex_False; - exp->_bol = text_begin; - exp->_eol = text_end; - do { - cur = text_begin; - while (node != -1) { - exp->_currsubexp = 0; - cur = trex_matchnode(exp, &exp->_nodes[node], cur, NULL); - if (!cur) - break; - node = exp->_nodes[node].next; - } - text_begin++; - } while (cur == NULL && text_begin != text_end); - - if (cur == NULL) - return TRex_False; - - --text_begin; - - if (out_begin) - *out_begin = text_begin; - if (out_end) - *out_end = cur; - return TRex_True; -} - -TRexBool trex_search(TRex* exp, const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end) { - return trex_searchrange(exp, text, text + scstrlen(text), out_begin, out_end); -} - -int trex_getsubexpcount(TRex* exp) { - return exp->_nsubexpr; -} - -TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch* subexp) { - if (n < 0 || n >= exp->_nsubexpr) - return TRex_False; - *subexp = exp->_matches[n]; - return TRex_True; -} -/******************************************************************************* - * arg_str: Implements the str command-line option - * - * This file is part of the argtable3 library. - * - * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of STEWART HEITMANN nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -#include "argtable3.h" - -#ifndef ARG_AMALGAMATION -#include "argtable3_private.h" -#endif - -#include - -static void arg_str_resetfn(struct arg_str* parent) { - int i; - - ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent)); - for (i = 0; i < parent->count; i++) { - parent->sval[i] = ""; - } - parent->count = 0; -} - -static int arg_str_scanfn(struct arg_str* parent, const char* argval) { - int errorcode = 0; - - if (parent->count == parent->hdr.maxcount) { - /* maximum number of arguments exceeded */ - errorcode = ARG_ERR_MAXCOUNT; - } else if (!argval) { - /* a valid argument with no argument value was given. */ - /* This happens when an optional argument value was invoked. */ - /* leave parent argument value unaltered but still count the argument. */ - parent->count++; - } else { - parent->sval[parent->count++] = argval; - } - - ARG_TRACE(("%s:scanfn(%p) returns %d\n", __FILE__, parent, errorcode)); - return errorcode; -} - -static int arg_str_checkfn(struct arg_str* parent) { - int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0; - - ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode)); - return errorcode; -} - -static void arg_str_errorfn(struct arg_str* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) { - const char* shortopts = parent->hdr.shortopts; - const char* longopts = parent->hdr.longopts; - const char* datatype = parent->hdr.datatype; - - /* make argval NULL safe */ - argval = argval ? argval : ""; - - arg_dstr_catf(ds, "%s: ", progname); - switch (errorcode) { - case ARG_ERR_MINCOUNT: - arg_dstr_cat(ds, "missing option "); - arg_print_option_ds(ds, shortopts, longopts, datatype, "\n"); - break; - - case ARG_ERR_MAXCOUNT: - arg_dstr_cat(ds, "excess option "); - arg_print_option_ds(ds, shortopts, longopts, argval, "\n"); - break; - } -} - -struct arg_str* arg_str0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) { - return arg_strn(shortopts, longopts, datatype, 0, 1, glossary); -} - -struct arg_str* arg_str1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) { - return arg_strn(shortopts, longopts, datatype, 1, 1, glossary); -} - -struct arg_str* arg_strn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary) { - size_t nbytes; - struct arg_str* result; - int i; - - /* should not allow this stupid error */ - /* we should return an error code warning this logic error */ - /* foolproof things by ensuring maxcount is not less than mincount */ - maxcount = (maxcount < mincount) ? mincount : maxcount; - - nbytes = sizeof(struct arg_str) /* storage for struct arg_str */ - + (size_t)maxcount * sizeof(char*); /* storage for sval[maxcount] array */ - - result = (struct arg_str*)xmalloc(nbytes); - - /* init the arg_hdr struct */ - result->hdr.flag = ARG_HASVALUE; - result->hdr.shortopts = shortopts; - result->hdr.longopts = longopts; - result->hdr.datatype = datatype ? datatype : ""; - result->hdr.glossary = glossary; - result->hdr.mincount = mincount; - result->hdr.maxcount = maxcount; - result->hdr.parent = result; - result->hdr.resetfn = (arg_resetfn*)arg_str_resetfn; - result->hdr.scanfn = (arg_scanfn*)arg_str_scanfn; - result->hdr.checkfn = (arg_checkfn*)arg_str_checkfn; - result->hdr.errorfn = (arg_errorfn*)arg_str_errorfn; - - /* store the sval[maxcount] array immediately after the arg_str struct */ - result->sval = (const char**)(result + 1); - result->count = 0; - - /* foolproof the string pointers by initializing them to reference empty strings */ - for (i = 0; i < maxcount; i++) - result->sval[i] = ""; - - ARG_TRACE(("arg_strn() returns %p\n", result)); - return result; -} -/******************************************************************************* - * arg_utils: Implements memory, panic, and other utility functions - * - * This file is part of the argtable3 library. - * - * Copyright (C) 2013-2019 Tom G. Huang - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of STEWART HEITMANN nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -#include "argtable3.h" - -#ifndef ARG_AMALGAMATION -#include "argtable3_private.h" -#endif - -#include -#include -#include -#include - -static void panic(const char* fmt, ...); -static arg_panicfn* s_panic = panic; - -void dbg_printf(const char* fmt, ...) { - va_list args; - va_start(args, fmt); - vfprintf(stderr, fmt, args); - va_end(args); -} - -static void panic(const char* fmt, ...) { - va_list args; - char* s; - - va_start(args, fmt); - vfprintf(stderr, fmt, args); - va_end(args); - -#if defined(_MSC_VER) -#pragma warning(push) -#pragma warning(disable : 4996) -#endif - s = getenv("EF_DUMPCORE"); -#if defined(_MSC_VER) -#pragma warning(pop) -#endif - - if (s != NULL && *s != '\0') { - abort(); - } else { - exit(EXIT_FAILURE); - } -} - -void arg_set_panic(arg_panicfn* proc) { - s_panic = proc; -} - -void* xmalloc(size_t size) { - void* ret = malloc(size); - if (!ret) { - s_panic("Out of memory!\n"); - } - return ret; -} - -void* xcalloc(size_t count, size_t size) { - size_t allocated_count = count && size ? count : 1; - size_t allocated_size = count && size ? size : 1; - void* ret = calloc(allocated_count, allocated_size); - if (!ret) { - s_panic("Out of memory!\n"); - } - return ret; -} - -void* xrealloc(void* ptr, size_t size) { - size_t allocated_size = size ? size : 1; - void* ret = realloc(ptr, allocated_size); - if (!ret) { - s_panic("Out of memory!\n"); - } - return ret; -} - -void xfree(void* ptr) { - free(ptr); -} - -static void merge(void* data, int esize, int i, int j, int k, arg_comparefn* comparefn) { - char* a = (char*)data; - char* m; - int ipos, jpos, mpos; - - /* Initialize the counters used in merging. */ - ipos = i; - jpos = j + 1; - mpos = 0; - - /* Allocate storage for the merged elements. */ - m = (char*)xmalloc((size_t)(esize * ((k - i) + 1))); - - /* Continue while either division has elements to merge. */ - while (ipos <= j || jpos <= k) { - if (ipos > j) { - /* The left division has no more elements to merge. */ - while (jpos <= k) { - memcpy(&m[mpos * esize], &a[jpos * esize], (size_t)esize); - jpos++; - mpos++; - } - - continue; - } else if (jpos > k) { - /* The right division has no more elements to merge. */ - while (ipos <= j) { - memcpy(&m[mpos * esize], &a[ipos * esize], (size_t)esize); - ipos++; - mpos++; - } - - continue; - } - - /* Append the next ordered element to the merged elements. */ - if (comparefn(&a[ipos * esize], &a[jpos * esize]) < 0) { - memcpy(&m[mpos * esize], &a[ipos * esize], (size_t)esize); - ipos++; - mpos++; - } else { - memcpy(&m[mpos * esize], &a[jpos * esize], (size_t)esize); - jpos++; - mpos++; - } - } - - /* Prepare to pass back the merged data. */ - memcpy(&a[i * esize], m, (size_t)(esize * ((k - i) + 1))); - xfree(m); -} - -void arg_mgsort(void* data, int size, int esize, int i, int k, arg_comparefn* comparefn) { - int j; - - /* Stop the recursion when no more divisions can be made. */ - if (i < k) { - /* Determine where to divide the elements. */ - j = (int)(((i + k - 1)) / 2); - - /* Recursively sort the two divisions. */ - arg_mgsort(data, size, esize, i, j, comparefn); - arg_mgsort(data, size, esize, j + 1, k, comparefn); - merge(data, esize, i, j, k, comparefn); - } -} /******************************************************************************* * argtable3: Implements the main interfaces of the library * @@ -4690,6 +35,7 @@ void arg_mgsort(void* data, int size, int esize, int i, int k, arg_comparefn* co #ifndef ARG_AMALGAMATION #include "argtable3_private.h" #if ARG_REPLACE_GETOPT == 1 +#include "arg_getopt.h" #else #include #endif @@ -5158,11 +504,11 @@ static void arg_cat(char** pdest, const char* src, size_t* pndest) { char* end = dest + *pndest; /*locate null terminator of dest string */ - while (dest < end && *dest != 0) + while (dest < end-1 && *dest != 0) dest++; /* concat src string to dest string */ - while (dest < end && *src != 0) + while (dest < end-1 && *src != 0) *dest++ = *src++; /* null terminate dest string */ @@ -5512,6 +858,86 @@ void arg_print_glossary(FILE* fp, void** argtable, const char* format) { arg_dstr_destroy(ds); } +/** + * Print a piece of text formatted, which means in a column with a + * left and a right margin. The lines are wrapped at whitspaces next + * to right margin. The function does not indent the first line, but + * only the following ones. + * + * See description of arg_print_formatted below. + */ +static void arg_print_formatted_ds(arg_dstr_t ds, const unsigned lmargin, const unsigned rmargin, const char* text) { + const unsigned int textlen = (unsigned int)strlen(text); + unsigned int line_start = 0; + unsigned int line_end = textlen; + const unsigned int colwidth = (rmargin - lmargin) + 1; + + assert(strlen(text) < UINT_MAX); + + /* Someone doesn't like us... */ + if (line_end < line_start) { + arg_dstr_catf(ds, "%s\n", text); + } + + while (line_end > line_start) { + /* Eat leading white spaces. This is essential because while + wrapping lines, there will often be a whitespace at beginning + of line. Preserve newlines */ + while (isspace((int)(*(text + line_start))) && *(text + line_start) != '\n') { + line_start++; + } + + /* Find last whitespace, that fits into line */ + if (line_end - line_start > colwidth) { + line_end = line_start + colwidth; + + while ((line_end > line_start) && !isspace((int)(*(text + line_end)))) { + line_end--; + } + + /* If no whitespace could be found, eg. the text is one long word, break the word */ + if (line_end == line_start) { + /* Set line_end to previous value */ + line_end = line_start + colwidth; + } else { + /* Consume trailing spaces, except newlines */ + while ((line_end > line_start) && isspace((int)(*(text + line_end))) && *(text + line_start) != '\n') { + line_end--; + } + + /* Restore the last non-space character */ + line_end++; + } + } + + /* Output line of text */ + while (line_start < line_end) { + char c = *(text + line_start); + + /* If character is newline stop printing, skip this character, as a newline will be printed below. */ + if (c == '\n') { + line_start++; + break; + } + + arg_dstr_catc(ds, c); + line_start++; + } + arg_dstr_cat(ds, "\n"); + + /* Initialize another line */ + if (line_end < textlen) { + unsigned i; + + for (i = 0; i < lmargin; i++) { + arg_dstr_cat(ds, " "); + } + + line_end = textlen; + } + } /* lines of text */ +} + /** * Print a piece of text formatted, which means in a column with a * left and a right margin. The lines are wrapped at whitspaces next @@ -5544,63 +970,11 @@ void arg_print_glossary(FILE* fp, void** argtable, const char* format) { * * Author: Uli Fouquet */ -static void arg_print_formatted_ds(arg_dstr_t ds, const unsigned lmargin, const unsigned rmargin, const char* text) { - const unsigned int textlen = (unsigned int)strlen(text); - unsigned int line_start = 0; - unsigned int line_end = textlen; - const unsigned int colwidth = (rmargin - lmargin) + 1; - - assert(strlen(text) < UINT_MAX); - - /* Someone doesn't like us... */ - if (line_end < line_start) { - arg_dstr_catf(ds, "%s\n", text); - } - - while (line_end > line_start) { - /* Eat leading white spaces. This is essential because while - wrapping lines, there will often be a whitespace at beginning - of line */ - while (isspace((int)(*(text + line_start)))) { - line_start++; - } - - /* Find last whitespace, that fits into line */ - if (line_end - line_start > colwidth) { - line_end = line_start + colwidth; - - while ((line_end > line_start) && !isspace((int)(*(text + line_end)))) { - line_end--; - } - - /* Consume trailing spaces */ - while ((line_end > line_start) && isspace((int)(*(text + line_end)))) { - line_end--; - } - - /* Restore the last non-space character */ - line_end++; - } - - /* Output line of text */ - while (line_start < line_end) { - char c = *(text + line_start); - arg_dstr_catc(ds, c); - line_start++; - } - arg_dstr_cat(ds, "\n"); - - /* Initialize another line */ - if (line_end < textlen) { - unsigned i; - - for (i = 0; i < lmargin; i++) { - arg_dstr_cat(ds, " "); - } - - line_end = textlen; - } - } /* lines of text */ +void arg_print_formatted(FILE* fp, const unsigned lmargin, const unsigned rmargin, const char* text) { + arg_dstr_t ds = arg_dstr_create(); + arg_print_formatted_ds(ds, lmargin, rmargin, text); + fputs(arg_dstr_cstr(ds), fp); + arg_dstr_destroy(ds); } /** @@ -5730,3 +1104,1179 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { UNREFERENCED_PARAMETER(lpvReserved); } #endif +/******************************************************************************* + * arg_file: Implements the file command-line option + * + * This file is part of the argtable3 library. + * + * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of STEWART HEITMANN nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************/ + +#include "argtable3.h" + +#ifndef ARG_AMALGAMATION +#include "argtable3_private.h" +#endif + +#include +#include + +#ifdef WIN32 +#define FILESEPARATOR1 '\\' +#define FILESEPARATOR2 '/' +#else +#define FILESEPARATOR1 '/' +#define FILESEPARATOR2 '/' +#endif + +static void arg_file_resetfn(void* parent_) { + struct arg_file* parent = parent_; + ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent)); + parent->count = 0; +} + +/* Returns ptr to the base filename within *filename */ +static const char* arg_basename(const char* filename) { + const char *result = NULL, *result1, *result2; + + /* Find the last occurrence of eother file separator character. */ + /* Two alternative file separator chars are supported as legal */ + /* file separators but not both together in the same filename. */ + result1 = (filename ? strrchr(filename, FILESEPARATOR1) : NULL); + result2 = (filename ? strrchr(filename, FILESEPARATOR2) : NULL); + + if (result2) + result = result2 + 1; /* using FILESEPARATOR2 (the alternative file separator) */ + + if (result1) + result = result1 + 1; /* using FILESEPARATOR1 (the preferred file separator) */ + + if (!result) + result = filename; /* neither file separator was found so basename is the whole filename */ + + /* special cases of "." and ".." are not considered basenames */ + if (result && (strcmp(".", result) == 0 || strcmp("..", result) == 0)) + result = filename + strlen(filename); + + return result; +} + +/* Returns ptr to the file extension within *basename */ +static const char* arg_extension(const char* basename) { + /* find the last occurrence of '.' in basename */ + const char* result = (basename ? strrchr(basename, '.') : NULL); + + /* if no '.' was found then return pointer to end of basename */ + if (basename && !result) + result = basename + strlen(basename); + + /* special case: basenames with a single leading dot (eg ".foo") are not considered as true extensions */ + if (basename && result == basename) + result = basename + strlen(basename); + + /* special case: empty extensions (eg "foo.","foo..") are not considered as true extensions */ + if (basename && result && strlen(result) == 1) + result = basename + strlen(basename); + + return result; +} + +static int arg_file_scanfn(void* parent_, const char* argval) { + struct arg_file* parent = parent_; + int errorcode = 0; + + if (parent->count == parent->hdr.maxcount) { + /* maximum number of arguments exceeded */ + errorcode = ARG_ERR_MAXCOUNT; + } else if (!argval) { + /* a valid argument with no argument value was given. */ + /* This happens when an optional argument value was invoked. */ + /* leave parent arguiment value unaltered but still count the argument. */ + parent->count++; + } else { + parent->filename[parent->count] = argval; + parent->basename[parent->count] = arg_basename(argval); + parent->extension[parent->count] = + arg_extension(parent->basename[parent->count]); /* only seek extensions within the basename (not the file path)*/ + parent->count++; + } + + ARG_TRACE(("%s4:scanfn(%p) returns %d\n", __FILE__, parent, errorcode)); + return errorcode; +} + +static int arg_file_checkfn(void* parent_) { + struct arg_file* parent = parent_; + int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0; + + ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode)); + return errorcode; +} + +static void arg_file_errorfn(void* parent_, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) { + struct arg_file* parent = parent_; + const char* shortopts = parent->hdr.shortopts; + const char* longopts = parent->hdr.longopts; + const char* datatype = parent->hdr.datatype; + + /* make argval NULL safe */ + argval = argval ? argval : ""; + + arg_dstr_catf(ds, "%s: ", progname); + switch (errorcode) { + case ARG_ERR_MINCOUNT: + arg_dstr_cat(ds, "missing option "); + arg_print_option_ds(ds, shortopts, longopts, datatype, "\n"); + break; + + case ARG_ERR_MAXCOUNT: + arg_dstr_cat(ds, "excess option "); + arg_print_option_ds(ds, shortopts, longopts, argval, "\n"); + break; + + default: + arg_dstr_catf(ds, "unknown error at \"%s\"\n", argval); + } +} + +struct arg_file* arg_file0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) { + return arg_filen(shortopts, longopts, datatype, 0, 1, glossary); +} + +struct arg_file* arg_file1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) { + return arg_filen(shortopts, longopts, datatype, 1, 1, glossary); +} + +struct arg_file* arg_filen(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary) { + size_t nbytes; + struct arg_file* result; + int i; + + /* foolproof things by ensuring maxcount is not less than mincount */ + maxcount = (maxcount < mincount) ? mincount : maxcount; + + nbytes = sizeof(struct arg_file) /* storage for struct arg_file */ + + sizeof(char*) * (size_t)maxcount /* storage for filename[maxcount] array */ + + sizeof(char*) * (size_t)maxcount /* storage for basename[maxcount] array */ + + sizeof(char*) * (size_t)maxcount; /* storage for extension[maxcount] array */ + + result = (struct arg_file*)xmalloc(nbytes); + + /* init the arg_hdr struct */ + result->hdr.flag = ARG_HASVALUE; + result->hdr.shortopts = shortopts; + result->hdr.longopts = longopts; + result->hdr.glossary = glossary; + result->hdr.datatype = datatype ? datatype : ""; + result->hdr.mincount = mincount; + result->hdr.maxcount = maxcount; + result->hdr.parent = result; + result->hdr.resetfn = arg_file_resetfn; + result->hdr.scanfn = arg_file_scanfn; + result->hdr.checkfn = arg_file_checkfn; + result->hdr.errorfn = arg_file_errorfn; + + /* store the filename,basename,extension arrays immediately after the arg_file struct */ + result->filename = (const char**)(result + 1); + result->basename = result->filename + maxcount; + result->extension = result->basename + maxcount; + result->count = 0; + + /* foolproof the string pointers by initialising them with empty strings */ + for (i = 0; i < maxcount; i++) { + result->filename[i] = ""; + result->basename[i] = ""; + result->extension[i] = ""; + } + + ARG_TRACE(("arg_filen() returns %p\n", result)); + return result; +} +/******************************************************************************* + * arg_lit: Implements the literature command-line option + * + * This file is part of the argtable3 library. + * + * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of STEWART HEITMANN nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************/ + +#include "argtable3.h" + +#ifndef ARG_AMALGAMATION +#include "argtable3_private.h" +#endif + +#include + +static void arg_lit_resetfn(void* parent_) { + struct arg_lit* parent = parent_; + ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent)); + parent->count = 0; +} + +static int arg_lit_scanfn(void* parent_, const char* argval) { + struct arg_lit* parent = parent_; + int errorcode = 0; + if (parent->count < parent->hdr.maxcount) + parent->count++; + else + errorcode = ARG_ERR_MAXCOUNT; + + ARG_TRACE(("%s:scanfn(%p,%s) returns %d\n", __FILE__, parent, argval, errorcode)); + return errorcode; +} + +static int arg_lit_checkfn(void* parent_) { + struct arg_lit* parent = parent_; + int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0; + ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode)); + return errorcode; +} + +static void arg_lit_errorfn(void* parent_, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) { + struct arg_lit* parent = parent_; + const char* shortopts = parent->hdr.shortopts; + const char* longopts = parent->hdr.longopts; + const char* datatype = parent->hdr.datatype; + + switch (errorcode) { + case ARG_ERR_MINCOUNT: + arg_dstr_catf(ds, "%s: missing option ", progname); + arg_print_option_ds(ds, shortopts, longopts, datatype, "\n"); + arg_dstr_cat(ds, "\n"); + break; + + case ARG_ERR_MAXCOUNT: + arg_dstr_catf(ds, "%s: extraneous option ", progname); + arg_print_option_ds(ds, shortopts, longopts, datatype, "\n"); + break; + } + + ARG_TRACE(("%s:errorfn(%p, %p, %d, %s, %s)\n", __FILE__, parent, ds, errorcode, argval, progname)); +} + +struct arg_lit* arg_lit0(const char* shortopts, const char* longopts, const char* glossary) { + return arg_litn(shortopts, longopts, 0, 1, glossary); +} + +struct arg_lit* arg_lit1(const char* shortopts, const char* longopts, const char* glossary) { + return arg_litn(shortopts, longopts, 1, 1, glossary); +} + +struct arg_lit* arg_litn(const char* shortopts, const char* longopts, int mincount, int maxcount, const char* glossary) { + struct arg_lit* result; + + /* foolproof things by ensuring maxcount is not less than mincount */ + maxcount = (maxcount < mincount) ? mincount : maxcount; + + result = (struct arg_lit*)xmalloc(sizeof(struct arg_lit)); + + /* init the arg_hdr struct */ + result->hdr.flag = 0; + result->hdr.shortopts = shortopts; + result->hdr.longopts = longopts; + result->hdr.datatype = NULL; + result->hdr.glossary = glossary; + result->hdr.mincount = mincount; + result->hdr.maxcount = maxcount; + result->hdr.parent = result; + result->hdr.resetfn = arg_lit_resetfn; + result->hdr.scanfn = arg_lit_scanfn; + result->hdr.checkfn = arg_lit_checkfn; + result->hdr.errorfn = arg_lit_errorfn; + + /* init local variables */ + result->count = 0; + + ARG_TRACE(("arg_litn() returns %p\n", result)); + return result; +} +/******************************************************************************* + * arg_int: Implements the int command-line option + * + * This file is part of the argtable3 library. + * + * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of STEWART HEITMANN nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************/ + +#include "argtable3.h" + +#ifndef ARG_AMALGAMATION +#include "argtable3_private.h" +#endif + +#include +#include +#include + +static void arg_int_resetfn(void* parent_) { + struct arg_int* parent = parent_; + ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent)); + parent->count = 0; +} + +/* strtol0x() is like strtol() except that the numeric string is */ +/* expected to be prefixed by "0X" where X is a user supplied char. */ +/* The string may optionally be prefixed by white space and + or - */ +/* as in +0X123 or -0X123. */ +/* Once the prefix has been scanned, the remainder of the numeric */ +/* string is converted using strtol() with the given base. */ +/* eg: to parse hex str="-0X12324", specify X='X' and base=16. */ +/* eg: to parse oct str="+0o12324", specify X='O' and base=8. */ +/* eg: to parse bin str="-0B01010", specify X='B' and base=2. */ +/* Failure of conversion is indicated by result where *endptr==str. */ +static long int strtol0X(const char* str, const char** endptr, char X, int base) { + long int val; /* stores result */ + int s = 1; /* sign is +1 or -1 */ + const char* ptr = str; /* ptr to current position in str */ + + /* skip leading whitespace */ + while (isspace((int)(*ptr))) + ptr++; + /* printf("1) %s\n",ptr); */ + + /* scan optional sign character */ + switch (*ptr) { + case '+': + ptr++; + s = 1; + break; + case '-': + ptr++; + s = -1; + break; + default: + s = 1; + break; + } + /* printf("2) %s\n",ptr); */ + + /* '0X' prefix */ + if ((*ptr++) != '0') { + /* printf("failed to detect '0'\n"); */ + *endptr = str; + return 0; + } + /* printf("3) %s\n",ptr); */ + if (toupper(*ptr++) != toupper(X)) { + /* printf("failed to detect '%c'\n",X); */ + *endptr = str; + return 0; + } + /* printf("4) %s\n",ptr); */ + + /* attempt conversion on remainder of string using strtol() */ + val = strtol(ptr, (char**)endptr, base); + if (*endptr == ptr) { + /* conversion failed */ + *endptr = str; + return 0; + } + + /* success */ + return s * val; +} + +/* Returns 1 if str matches suffix (case insensitive). */ +/* Str may contain trailing whitespace, but nothing else. */ +static int detectsuffix(const char* str, const char* suffix) { + /* scan pairwise through strings until mismatch detected */ + while (toupper(*str) == toupper(*suffix)) { + /* printf("'%c' '%c'\n", *str, *suffix); */ + + /* return 1 (success) if match persists until the string terminator */ + if (*str == '\0') + return 1; + + /* next chars */ + str++; + suffix++; + } + /* printf("'%c' '%c' mismatch\n", *str, *suffix); */ + + /* return 0 (fail) if the matching did not consume the entire suffix */ + if (*suffix != 0) + return 0; /* failed to consume entire suffix */ + + /* skip any remaining whitespace in str */ + while (isspace((int)(*str))) + str++; + + /* return 1 (success) if we have reached end of str else return 0 (fail) */ + return (*str == '\0') ? 1 : 0; +} + +static int arg_int_scanfn(void* parent_, const char* argval) { + struct arg_int* parent = parent_; + int errorcode = 0; + + if (parent->count == parent->hdr.maxcount) { + /* maximum number of arguments exceeded */ + errorcode = ARG_ERR_MAXCOUNT; + } else if (!argval) { + /* a valid argument with no argument value was given. */ + /* This happens when an optional argument value was invoked. */ + /* leave parent arguiment value unaltered but still count the argument. */ + parent->count++; + } else { + long int val; + const char* end; + + /* attempt to extract hex integer (eg: +0x123) from argval into val conversion */ + val = strtol0X(argval, &end, 'X', 16); + if (end == argval) { + /* hex failed, attempt octal conversion (eg +0o123) */ + val = strtol0X(argval, &end, 'O', 8); + if (end == argval) { + /* octal failed, attempt binary conversion (eg +0B101) */ + val = strtol0X(argval, &end, 'B', 2); + if (end == argval) { + /* binary failed, attempt decimal conversion with no prefix (eg 1234) */ + val = strtol(argval, (char**)&end, 10); + if (end == argval) { + /* all supported number formats failed */ + return ARG_ERR_BADINT; + } + } + } + } + + /* Safety check for integer overflow. WARNING: this check */ + /* achieves nothing on machines where size(int)==size(long). */ + if (val > INT_MAX || val < INT_MIN) + errorcode = ARG_ERR_OVERFLOW; + + /* Detect any suffixes (KB,MB,GB) and multiply argument value appropriately. */ + /* We need to be mindful of integer overflows when using such big numbers. */ + if (detectsuffix(end, "KB")) /* kilobytes */ + { + if (val > (INT_MAX / 1024) || val < (INT_MIN / 1024)) + errorcode = ARG_ERR_OVERFLOW; /* Overflow would occur if we proceed */ + else + val *= 1024; /* 1KB = 1024 */ + } else if (detectsuffix(end, "MB")) /* megabytes */ + { + if (val > (INT_MAX / 1048576) || val < (INT_MIN / 1048576)) + errorcode = ARG_ERR_OVERFLOW; /* Overflow would occur if we proceed */ + else + val *= 1048576; /* 1MB = 1024*1024 */ + } else if (detectsuffix(end, "GB")) /* gigabytes */ + { + if (val > (INT_MAX / 1073741824) || val < (INT_MIN / 1073741824)) + errorcode = ARG_ERR_OVERFLOW; /* Overflow would occur if we proceed */ + else + val *= 1073741824; /* 1GB = 1024*1024*1024 */ + } else if (!detectsuffix(end, "")) + errorcode = ARG_ERR_BADINT; /* invalid suffix detected */ + + /* if success then store result in parent->ival[] array */ + if (errorcode == 0) + parent->ival[parent->count++] = (int)val; + } + + /* printf("%s:scanfn(%p,%p) returns %d\n",__FILE__,parent,argval,errorcode); */ + return errorcode; +} + +static int arg_int_checkfn(void* parent_) { + struct arg_int* parent = parent_; + int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0; + /*printf("%s:checkfn(%p) returns %d\n",__FILE__,parent,errorcode);*/ + return errorcode; +} + +static void arg_int_errorfn(void* parent_, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) { + struct arg_int* parent = parent_; + const char* shortopts = parent->hdr.shortopts; + const char* longopts = parent->hdr.longopts; + const char* datatype = parent->hdr.datatype; + + /* make argval NULL safe */ + argval = argval ? argval : ""; + + arg_dstr_catf(ds, "%s: ", progname); + switch (errorcode) { + case ARG_ERR_MINCOUNT: + arg_dstr_cat(ds, "missing option "); + arg_print_option_ds(ds, shortopts, longopts, datatype, "\n"); + break; + + case ARG_ERR_MAXCOUNT: + arg_dstr_cat(ds, "excess option "); + arg_print_option_ds(ds, shortopts, longopts, argval, "\n"); + break; + + case ARG_ERR_BADINT: + arg_dstr_catf(ds, "invalid argument \"%s\" to option ", argval); + arg_print_option_ds(ds, shortopts, longopts, datatype, "\n"); + break; + + case ARG_ERR_OVERFLOW: + arg_dstr_cat(ds, "integer overflow at option "); + arg_print_option_ds(ds, shortopts, longopts, datatype, " "); + arg_dstr_catf(ds, "(%s is too large)\n", argval); + break; + } +} + +struct arg_int* arg_int0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) { + return arg_intn(shortopts, longopts, datatype, 0, 1, glossary); +} + +struct arg_int* arg_int1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) { + return arg_intn(shortopts, longopts, datatype, 1, 1, glossary); +} + +struct arg_int* arg_intn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary) { + size_t nbytes; + struct arg_int* result; + + /* foolproof things by ensuring maxcount is not less than mincount */ + maxcount = (maxcount < mincount) ? mincount : maxcount; + + nbytes = sizeof(struct arg_int) /* storage for struct arg_int */ + + (size_t)maxcount * sizeof(int); /* storage for ival[maxcount] array */ + + result = (struct arg_int*)xmalloc(nbytes); + + /* init the arg_hdr struct */ + result->hdr.flag = ARG_HASVALUE; + result->hdr.shortopts = shortopts; + result->hdr.longopts = longopts; + result->hdr.datatype = datatype ? datatype : ""; + result->hdr.glossary = glossary; + result->hdr.mincount = mincount; + result->hdr.maxcount = maxcount; + result->hdr.parent = result; + result->hdr.resetfn = arg_int_resetfn; + result->hdr.scanfn = arg_int_scanfn; + result->hdr.checkfn = arg_int_checkfn; + result->hdr.errorfn = arg_int_errorfn; + + /* store the ival[maxcount] array immediately after the arg_int struct */ + result->ival = (int*)(result + 1); + result->count = 0; + + ARG_TRACE(("arg_intn() returns %p\n", result)); + return result; +} +/******************************************************************************* + * arg_end: Implements the error handling utilities + * + * This file is part of the argtable3 library. + * + * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of STEWART HEITMANN nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************/ + +#include "argtable3.h" + +#ifndef ARG_AMALGAMATION +#include "argtable3_private.h" +#endif + +#include + +static void arg_end_resetfn(void* parent_) { + struct arg_end* parent = parent_; + ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent)); + parent->count = 0; +} + +static void arg_end_errorfn(void* parent, arg_dstr_t ds, int error, const char* argval, const char* progname) { + /* suppress unreferenced formal parameter warning */ + (void)parent; + + progname = progname ? progname : ""; + argval = argval ? argval : ""; + + arg_dstr_catf(ds, "%s: ", progname); + switch (error) { + case ARG_ELIMIT: + arg_dstr_cat(ds, "too many errors to display"); + break; + case ARG_EMALLOC: + arg_dstr_cat(ds, "insufficient memory"); + break; + case ARG_ENOMATCH: + arg_dstr_catf(ds, "unexpected argument \"%s\"", argval); + break; + case ARG_EMISSARG: + arg_dstr_catf(ds, "option \"%s\" requires an argument", argval); + break; + case ARG_ELONGOPT: + arg_dstr_catf(ds, "invalid option \"%s\"", argval); + break; + default: + arg_dstr_catf(ds, "invalid option \"-%c\"", error); + break; + } + + arg_dstr_cat(ds, "\n"); +} + +struct arg_end* arg_end(int maxcount) { + size_t nbytes; + struct arg_end* result; + + nbytes = sizeof(struct arg_end) + (size_t)maxcount * sizeof(int) /* storage for int error[maxcount] array*/ + + (size_t)maxcount * sizeof(void*) /* storage for void* parent[maxcount] array */ + + (size_t)maxcount * sizeof(char*); /* storage for char* argval[maxcount] array */ + + result = (struct arg_end*)xmalloc(nbytes); + + /* init the arg_hdr struct */ + result->hdr.flag = ARG_TERMINATOR; + result->hdr.shortopts = NULL; + result->hdr.longopts = NULL; + result->hdr.datatype = NULL; + result->hdr.glossary = NULL; + result->hdr.mincount = 1; + result->hdr.maxcount = maxcount; + result->hdr.parent = result; + result->hdr.resetfn = arg_end_resetfn; + result->hdr.scanfn = NULL; + result->hdr.checkfn = NULL; + result->hdr.errorfn = arg_end_errorfn; + + /* store error[maxcount] array immediately after struct arg_end */ + result->error = (int*)(result + 1); + + /* store parent[maxcount] array immediately after error[] array */ + result->parent = (void**)(result->error + maxcount); + + /* store argval[maxcount] array immediately after parent[] array */ + result->argval = (const char**)(result->parent + maxcount); + + ARG_TRACE(("arg_end(%d) returns %p\n", maxcount, result)); + return result; +} + +void arg_print_errors_ds(arg_dstr_t ds, struct arg_end* end, const char* progname) { + int i; + ARG_TRACE(("arg_errors()\n")); + for (i = 0; i < end->count; i++) { + struct arg_hdr* errorparent = (struct arg_hdr*)(end->parent[i]); + if (errorparent->errorfn) + errorparent->errorfn(end->parent[i], ds, end->error[i], end->argval[i], progname); + } +} + +void arg_print_errors(FILE* fp, struct arg_end* end, const char* progname) { + arg_dstr_t ds = arg_dstr_create(); + arg_print_errors_ds(ds, end, progname); + fputs(arg_dstr_cstr(ds), fp); + arg_dstr_destroy(ds); +} +/******************************************************************************* + * arg_dstr: Implements the dynamic string utilities + * + * This file is part of the argtable3 library. + * + * Copyright (C) 2013-2019 Tom G. Huang + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of STEWART HEITMANN nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************/ + +#include "argtable3.h" + +#ifndef ARG_AMALGAMATION +#include "argtable3_private.h" +#endif + +#include +#include +#include +#include + +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#endif + +#define START_VSNBUFF 16 + +#if defined(_MSC_VER) + #define arg_vsnprintf _vsnprintf +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define arg_vsnprintf vsnprintf +#else +/** + * A C89-compatible replacement for vsnprintf(). + * + * Writes at most (size - 1) characters to str and always null-terminates, + * unless size is 0. The output is truncated if necessary. + * + * @param str Output buffer. + * @param size Size of output buffer. + * @param format printf-style format string. + * @param ap va_list of arguments. + * @return The number of characters that would have been written, excluding the null byte. + */ +int arg_vsnprintf(char *str, size_t size, const char *format, va_list ap) { + char *temp_buffer; + int result; + size_t temp_size; + + if (str == NULL || size == 0) { + /* Just calculate required size using a temporary large buffer */ + temp_size = 65536; /* Large temporary buffer */ + temp_buffer = malloc(temp_size); + if (temp_buffer == NULL) { + return -1; + } + + result = vsprintf(temp_buffer, format, ap); + free(temp_buffer); + return result; + } + + if (size == 1) { + str[0] = '\0'; + return 0; + } + + /* Use a large temporary buffer to safely format */ + temp_size = size * 4; /* Start with 4x the target size */ + if (temp_size < 1024) { + temp_size = 1024; + } + + temp_buffer = malloc(temp_size); + if (temp_buffer == NULL) { + return -1; + } + + result = vsprintf(temp_buffer, format, ap); + if (result < 0) { + free(temp_buffer); + return -1; + } + + /* Copy to destination buffer, truncating if necessary */ + strncpy(str, temp_buffer, size - 1); + if ((size_t)result >= size) { + /* Truncate */ + str[size - 1] = '\0'; + } + + free(temp_buffer); + return result; /* Return the number of chars that would be written */ +} +#endif + +/* + * This dynamic string module is adapted from TclResult.c in the Tcl library. + * Here is the copyright notice from the library: + * + * This software is copyrighted by the Regents of the University of + * California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState + * Corporation and other parties. The following terms apply to all files + * associated with the software unless explicitly disclaimed in + * individual files. + * + * The authors hereby grant permission to use, copy, modify, distribute, + * and license this software and its documentation for any purpose, provided + * that existing copyright notices are retained in all copies and that this + * notice is included verbatim in any distributions. No written agreement, + * license, or royalty fee is required for any of the authorized uses. + * Modifications to this software may be copyrighted by their authors + * and need not follow the licensing terms described here, provided that + * the new terms are clearly indicated on the first page of each file where + * they apply. + * + * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY + * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY + * DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE + * IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE + * NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR + * MODIFICATIONS. + * + * GOVERNMENT USE: If you are acquiring this software on behalf of the + * U.S. government, the Government shall have only "Restricted Rights" + * in the software and related documentation as defined in the Federal + * Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you + * are acquiring the software on behalf of the Department of Defense, the + * software shall be classified as "Commercial Computer Software" and the + * Government shall have only "Restricted Rights" as defined in Clause + * 252.227-7014 (b) (3) of DFARs. Notwithstanding the foregoing, the + * authors grant the U.S. Government and others acting in its behalf + * permission to use and distribute the software in accordance with the + * terms specified in this license. + */ + +typedef struct _internal_arg_dstr { + char* data; + arg_dstr_freefn* free_proc; + char sbuf[ARG_DSTR_SIZE + 1]; + char* append_data; + int append_data_size; + int append_used; +} _internal_arg_dstr_t; + +static void setup_append_buf(arg_dstr_t res, int newSpace); + +arg_dstr_t arg_dstr_create(void) { + _internal_arg_dstr_t* h = (_internal_arg_dstr_t*)xmalloc(sizeof(_internal_arg_dstr_t)); + memset(h, 0, sizeof(_internal_arg_dstr_t)); + h->sbuf[0] = 0; + h->data = h->sbuf; + h->free_proc = ARG_DSTR_STATIC; + return h; +} + +void arg_dstr_destroy(arg_dstr_t ds) { + if (ds == NULL) + return; + + arg_dstr_reset(ds); + xfree(ds); + return; +} + +void arg_dstr_set(arg_dstr_t ds, char* str, arg_dstr_freefn* free_proc) { + int length; + register arg_dstr_freefn* old_free_proc = ds->free_proc; + char* old_result = ds->data; + + if (str == NULL) { + ds->sbuf[0] = 0; + ds->data = ds->sbuf; + ds->free_proc = ARG_DSTR_STATIC; + } else if (free_proc == ARG_DSTR_VOLATILE) { + length = (int)strlen(str); + if (length > ARG_DSTR_SIZE) { + ds->data = (char*)xmalloc((size_t)length + 1); + ds->free_proc = ARG_DSTR_DYNAMIC; + strncpy(ds->data, str, (size_t)length + 1); /* NOSONAR */ + assert(ds->data[length] == '\0'); + } else { + ds->data = ds->sbuf; + ds->free_proc = ARG_DSTR_STATIC; + strncpy(ds->data, str, sizeof(ds->sbuf) - 1); /* NOSONAR */ + ds->data[sizeof(ds->sbuf) - 1] = '\0'; + assert(ds->data[ARG_DSTR_SIZE] == '\0'); + } + } else { + ds->data = str; + ds->free_proc = free_proc; + } + + /* + * If the old result was dynamically-allocated, free it up. Do it here, + * rather than at the beginning, in case the new result value was part of + * the old result value. + */ + + if ((old_free_proc != 0) && (old_result != ds->data)) { + if (old_free_proc == ARG_DSTR_DYNAMIC) { + xfree(old_result); + } else { + (*old_free_proc)(old_result); + } + } + + if ((ds->append_data != NULL) && (ds->append_data_size > 0)) { + xfree(ds->append_data); + ds->append_data = NULL; + ds->append_data_size = 0; + } +} + +char* arg_dstr_cstr(arg_dstr_t ds) /* Interpreter whose result to return. */ +{ + return ds->data; +} + +void arg_dstr_cat(arg_dstr_t ds, const char* str) { + setup_append_buf(ds, (int)strlen(str) + 1); + memcpy(ds->data + strlen(ds->data), str, strlen(str)); +} + +void arg_dstr_catc(arg_dstr_t ds, char c) { + setup_append_buf(ds, 2); + memcpy(ds->data + strlen(ds->data), &c, 1); +} + +/* + * The logic of the `arg_dstr_catf` function is adapted from the `bformat` + * function in The Better String Library by Paul Hsieh. Here is the copyright + * notice from the library: + * + * Copyright (c) 2014, Paul Hsieh + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * * Neither the name of bstrlib nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +void arg_dstr_catf(arg_dstr_t ds, const char* fmt, ...) { + va_list arglist; + char* buff; + int n, r; + size_t slen; + + if (fmt == NULL) + return; + + /* Since the length is not determinable beforehand, a search is + performed using the truncating "vsnprintf" call (to avoid buffer + overflows) on increasing potential sizes for the output result. */ + + if ((n = (int)(2 * strlen(fmt))) < START_VSNBUFF) + n = START_VSNBUFF; + + buff = (char*)xmalloc((size_t)(n + 2)); + memset(buff, 0, (size_t)(n + 2)); + + for (;;) { + va_start(arglist, fmt); + r = arg_vsnprintf(buff, (size_t)(n + 1), fmt, arglist); + va_end(arglist); + + slen = strlen(buff); + if (slen < (size_t)n) + break; + + if (r > n) + n = r; + else + n += n; + + xfree(buff); + buff = (char*)xmalloc((size_t)(n + 2)); + memset(buff, 0, (size_t)(n + 2)); + } + + arg_dstr_cat(ds, buff); + xfree(buff); +} + +static void setup_append_buf(arg_dstr_t ds, int new_space) { + int total_space; + + /* + * Make the append buffer larger, if that's necessary, then copy the + * data into the append buffer and make the append buffer the official + * data. + */ + if (ds->data != ds->append_data) { + /* + * If the buffer is too big, then free it up so we go back to a + * smaller buffer. This avoids tying up memory forever after a large + * operation. + */ + if (ds->append_data_size > 500) { + xfree(ds->append_data); + ds->append_data = NULL; + ds->append_data_size = 0; + } + ds->append_used = (int)strlen(ds->data); + } else if (ds->data[ds->append_used] != 0) { + /* + * Most likely someone has modified a result created by + * arg_dstr_cat et al. so that it has a different size. Just + * recompute the size. + */ + ds->append_used = (int)strlen(ds->data); + } + + total_space = new_space + ds->append_used; + if (total_space >= ds->append_data_size) { + char* newbuf = NULL; + + if (total_space < 100) { + total_space = 200; + } else { + total_space *= 2; + } + newbuf = (char*)xmalloc((unsigned)total_space); + memset(newbuf, 0, (size_t)total_space); + strncpy(newbuf, ds->data, (size_t)total_space); /* NOSONAR */ + assert(newbuf[total_space - 1] == '\0'); + if (ds->append_data != NULL) { + xfree(ds->append_data); + } + + ds->append_data = newbuf; + ds->append_data_size = total_space; + } else if (ds->data != ds->append_data && ds->append_data != NULL) { + strncpy(ds->append_data, ds->data, (size_t)ds->append_data_size); /* NOSONAR */ + assert(ds->append_data[ds->append_data_size - 1] == '\0'); + } + + assert(ds->append_data != NULL); + arg_dstr_free(ds); + ds->data = ds->append_data; +} + +void arg_dstr_free(arg_dstr_t ds) { + if (ds->free_proc != NULL) { + if (ds->free_proc == ARG_DSTR_DYNAMIC) { + xfree(ds->data); + } else { + (*ds->free_proc)(ds->data); + } + ds->free_proc = NULL; + } +} + +void arg_dstr_reset(arg_dstr_t ds) { + arg_dstr_free(ds); + if ((ds->append_data != NULL) && (ds->append_data_size > 0)) { + xfree(ds->append_data); + ds->append_data = NULL; + ds->append_data_size = 0; + } + + ds->data = ds->sbuf; + ds->sbuf[0] = 0; +} + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif diff --git a/src/argtable3.h b/src/argtable3.h index a8ee95d..f414816 100644 --- a/src/argtable3.h +++ b/src/argtable3.h @@ -1,273 +1,2622 @@ -/******************************************************************************* - * argtable3: Declares the main interfaces of the library - * - * This file is part of the argtable3 library. - * - * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of STEWART HEITMANN nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -#ifndef ARGTABLE3 -#define ARGTABLE3 - -#include /* FILE */ -#include /* struct tm */ - -#ifdef __cplusplus -extern "C" { -#endif - -#define ARG_REX_ICASE 1 -#define ARG_DSTR_SIZE 200 -#define ARG_CMD_NAME_LEN 100 -#define ARG_CMD_DESCRIPTION_LEN 256 - -#ifndef ARG_REPLACE_GETOPT -#define ARG_REPLACE_GETOPT 1 /* use the embedded getopt as the system getopt(3) */ -#endif /* ARG_REPLACE_GETOPT */ - -/* bit masks for arg_hdr.flag */ -enum { ARG_TERMINATOR = 0x1, ARG_HASVALUE = 0x2, ARG_HASOPTVALUE = 0x4 }; - -#if defined(_WIN32) - #if defined(argtable3_EXPORTS) - #define ARG_EXTERN __declspec(dllexport) - #elif defined(argtable3_IMPORTS) - #define ARG_EXTERN __declspec(dllimport) - #else - #define ARG_EXTERN - #endif -#else - #define ARG_EXTERN -#endif - -typedef struct _internal_arg_dstr* arg_dstr_t; -typedef void* arg_cmd_itr_t; - -typedef void(arg_resetfn)(void* parent); -typedef int(arg_scanfn)(void* parent, const char* argval); -typedef int(arg_checkfn)(void* parent); -typedef void(arg_errorfn)(void* parent, arg_dstr_t ds, int error, const char* argval, const char* progname); -typedef void(arg_dstr_freefn)(char* buf); -typedef int(arg_cmdfn)(int argc, char* argv[], arg_dstr_t res); -typedef int(arg_comparefn)(const void* k1, const void* k2); - -/* - * The arg_hdr struct defines properties that are common to all arg_xxx structs. - * The argtable library requires each arg_xxx struct to have an arg_hdr - * struct as its first data member. - * The argtable library functions then use this data to identify the - * properties of the command line option, such as its option tags, - * datatype string, and glossary strings, and so on. - * Moreover, the arg_hdr struct contains pointers to custom functions that - * are provided by each arg_xxx struct which perform the tasks of parsing - * that particular arg_xxx arguments, performing post-parse checks, and - * reporting errors. - * These functions are private to the individual arg_xxx source code - * and are the pointer to them are initiliased by that arg_xxx struct's - * constructor function. The user could alter them after construction - * if desired, but the original intention is for them to be set by the - * constructor and left unaltered. - */ -typedef struct arg_hdr { - char flag; /* Modifier flags: ARG_TERMINATOR, ARG_HASVALUE. */ - const char* shortopts; /* String defining the short options */ - const char* longopts; /* String defiing the long options */ - const char* datatype; /* Description of the argument data type */ - const char* glossary; /* Description of the option as shown by arg_print_glossary function */ - int mincount; /* Minimum number of occurences of this option accepted */ - int maxcount; /* Maximum number of occurences if this option accepted */ - void* parent; /* Pointer to parent arg_xxx struct */ - arg_resetfn* resetfn; /* Pointer to parent arg_xxx reset function */ - arg_scanfn* scanfn; /* Pointer to parent arg_xxx scan function */ - arg_checkfn* checkfn; /* Pointer to parent arg_xxx check function */ - arg_errorfn* errorfn; /* Pointer to parent arg_xxx error function */ - void* priv; /* Pointer to private header data for use by arg_xxx functions */ -} arg_hdr_t; - -typedef struct arg_rem { - struct arg_hdr hdr; /* The mandatory argtable header struct */ -} arg_rem_t; - -typedef struct arg_lit { - struct arg_hdr hdr; /* The mandatory argtable header struct */ - int count; /* Number of matching command line args */ -} arg_lit_t; - -typedef struct arg_int { - struct arg_hdr hdr; /* The mandatory argtable header struct */ - int count; /* Number of matching command line args */ - int* ival; /* Array of parsed argument values */ -} arg_int_t; - -typedef struct arg_dbl { - struct arg_hdr hdr; /* The mandatory argtable header struct */ - int count; /* Number of matching command line args */ - double* dval; /* Array of parsed argument values */ -} arg_dbl_t; - -typedef struct arg_str { - struct arg_hdr hdr; /* The mandatory argtable header struct */ - int count; /* Number of matching command line args */ - const char** sval; /* Array of parsed argument values */ -} arg_str_t; - -typedef struct arg_rex { - struct arg_hdr hdr; /* The mandatory argtable header struct */ - int count; /* Number of matching command line args */ - const char** sval; /* Array of parsed argument values */ -} arg_rex_t; - -typedef struct arg_file { - struct arg_hdr hdr; /* The mandatory argtable header struct */ - int count; /* Number of matching command line args*/ - const char** filename; /* Array of parsed filenames (eg: /home/foo.bar) */ - const char** basename; /* Array of parsed basenames (eg: foo.bar) */ - const char** extension; /* Array of parsed extensions (eg: .bar) */ -} arg_file_t; - -typedef struct arg_date { - struct arg_hdr hdr; /* The mandatory argtable header struct */ - const char* format; /* strptime format string used to parse the date */ - int count; /* Number of matching command line args */ - struct tm* tmval; /* Array of parsed time values */ -} arg_date_t; - -enum { ARG_ELIMIT = 1, ARG_EMALLOC, ARG_ENOMATCH, ARG_ELONGOPT, ARG_EMISSARG }; -typedef struct arg_end { - struct arg_hdr hdr; /* The mandatory argtable header struct */ - int count; /* Number of errors encountered */ - int* error; /* Array of error codes */ - void** parent; /* Array of pointers to offending arg_xxx struct */ - const char** argval; /* Array of pointers to offending argv[] string */ -} arg_end_t; - -typedef struct arg_cmd_info { - char name[ARG_CMD_NAME_LEN]; - char description[ARG_CMD_DESCRIPTION_LEN]; - arg_cmdfn* proc; -} arg_cmd_info_t; - -/**** arg_xxx constructor functions *********************************/ - -ARG_EXTERN struct arg_rem* arg_rem(const char* datatype, const char* glossary); - -ARG_EXTERN struct arg_lit* arg_lit0(const char* shortopts, const char* longopts, const char* glossary); -ARG_EXTERN struct arg_lit* arg_lit1(const char* shortopts, const char* longopts, const char* glossary); -ARG_EXTERN struct arg_lit* arg_litn(const char* shortopts, const char* longopts, int mincount, int maxcount, const char* glossary); - -ARG_EXTERN struct arg_int* arg_int0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); -ARG_EXTERN struct arg_int* arg_int1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); -ARG_EXTERN struct arg_int* arg_intn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary); - -ARG_EXTERN struct arg_dbl* arg_dbl0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); -ARG_EXTERN struct arg_dbl* arg_dbl1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); -ARG_EXTERN struct arg_dbl* arg_dbln(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary); - -ARG_EXTERN struct arg_str* arg_str0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); -ARG_EXTERN struct arg_str* arg_str1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); -ARG_EXTERN struct arg_str* arg_strn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary); - -ARG_EXTERN struct arg_rex* arg_rex0(const char* shortopts, const char* longopts, const char* pattern, const char* datatype, int flags, const char* glossary); -ARG_EXTERN struct arg_rex* arg_rex1(const char* shortopts, const char* longopts, const char* pattern, const char* datatype, int flags, const char* glossary); -ARG_EXTERN struct arg_rex* arg_rexn(const char* shortopts, - const char* longopts, - const char* pattern, - const char* datatype, - int mincount, - int maxcount, - int flags, - const char* glossary); - -ARG_EXTERN struct arg_file* arg_file0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); -ARG_EXTERN struct arg_file* arg_file1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); -ARG_EXTERN struct arg_file* arg_filen(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary); - -ARG_EXTERN struct arg_date* arg_date0(const char* shortopts, const char* longopts, const char* format, const char* datatype, const char* glossary); -ARG_EXTERN struct arg_date* arg_date1(const char* shortopts, const char* longopts, const char* format, const char* datatype, const char* glossary); -ARG_EXTERN struct arg_date* arg_daten(const char* shortopts, const char* longopts, const char* format, const char* datatype, int mincount, int maxcount, const char* glossary); - -ARG_EXTERN struct arg_end* arg_end(int maxcount); - -#define ARG_DSTR_STATIC ((arg_dstr_freefn*)0) -#define ARG_DSTR_VOLATILE ((arg_dstr_freefn*)1) -#define ARG_DSTR_DYNAMIC ((arg_dstr_freefn*)3) - -/**** other functions *******************************************/ -ARG_EXTERN int arg_nullcheck(void** argtable); -ARG_EXTERN int arg_parse(int argc, char** argv, void** argtable); -ARG_EXTERN void arg_print_option(FILE* fp, const char* shortopts, const char* longopts, const char* datatype, const char* suffix); -ARG_EXTERN void arg_print_syntax(FILE* fp, void** argtable, const char* suffix); -ARG_EXTERN void arg_print_syntaxv(FILE* fp, void** argtable, const char* suffix); -ARG_EXTERN void arg_print_glossary(FILE* fp, void** argtable, const char* format); -ARG_EXTERN void arg_print_glossary_gnu(FILE* fp, void** argtable); -ARG_EXTERN void arg_print_errors(FILE* fp, struct arg_end* end, const char* progname); -ARG_EXTERN void arg_print_option_ds(arg_dstr_t ds, const char* shortopts, const char* longopts, const char* datatype, const char* suffix); -ARG_EXTERN void arg_print_syntax_ds(arg_dstr_t ds, void** argtable, const char* suffix); -ARG_EXTERN void arg_print_syntaxv_ds(arg_dstr_t ds, void** argtable, const char* suffix); -ARG_EXTERN void arg_print_glossary_ds(arg_dstr_t ds, void** argtable, const char* format); -ARG_EXTERN void arg_print_glossary_gnu_ds(arg_dstr_t ds, void** argtable); -ARG_EXTERN void arg_print_errors_ds(arg_dstr_t ds, struct arg_end* end, const char* progname); -ARG_EXTERN void arg_freetable(void** argtable, size_t n); - -ARG_EXTERN arg_dstr_t arg_dstr_create(void); -ARG_EXTERN void arg_dstr_destroy(arg_dstr_t ds); -ARG_EXTERN void arg_dstr_reset(arg_dstr_t ds); -ARG_EXTERN void arg_dstr_free(arg_dstr_t ds); -ARG_EXTERN void arg_dstr_set(arg_dstr_t ds, char* str, arg_dstr_freefn* free_proc); -ARG_EXTERN void arg_dstr_cat(arg_dstr_t ds, const char* str); -ARG_EXTERN void arg_dstr_catc(arg_dstr_t ds, char c); -ARG_EXTERN void arg_dstr_catf(arg_dstr_t ds, const char* fmt, ...); -ARG_EXTERN char* arg_dstr_cstr(arg_dstr_t ds); - -ARG_EXTERN void arg_cmd_init(void); -ARG_EXTERN void arg_cmd_uninit(void); -ARG_EXTERN void arg_cmd_register(const char* name, arg_cmdfn* proc, const char* description); -ARG_EXTERN void arg_cmd_unregister(const char* name); -ARG_EXTERN int arg_cmd_dispatch(const char* name, int argc, char* argv[], arg_dstr_t res); -ARG_EXTERN unsigned int arg_cmd_count(void); -ARG_EXTERN arg_cmd_info_t* arg_cmd_info(const char* name); -ARG_EXTERN arg_cmd_itr_t arg_cmd_itr_create(void); -ARG_EXTERN void arg_cmd_itr_destroy(arg_cmd_itr_t itr); -ARG_EXTERN int arg_cmd_itr_advance(arg_cmd_itr_t itr); -ARG_EXTERN char* arg_cmd_itr_key(arg_cmd_itr_t itr); -ARG_EXTERN arg_cmd_info_t* arg_cmd_itr_value(arg_cmd_itr_t itr); -ARG_EXTERN int arg_cmd_itr_search(arg_cmd_itr_t itr, void* k); -ARG_EXTERN void arg_mgsort(void* data, int size, int esize, int i, int k, arg_comparefn* comparefn); -ARG_EXTERN void arg_make_get_help_msg(arg_dstr_t res); -ARG_EXTERN void arg_make_help_msg(arg_dstr_t ds, char* cmd_name, void** argtable); -ARG_EXTERN void arg_make_syntax_err_msg(arg_dstr_t ds, void** argtable, struct arg_end* end); -ARG_EXTERN int arg_make_syntax_err_help_msg(arg_dstr_t ds, char* name, int help, int nerrors, void** argtable, struct arg_end* end, int* exitcode); -ARG_EXTERN void arg_set_module_name(const char* name); -ARG_EXTERN void arg_set_module_version(int major, int minor, int patch, const char* tag); - -/**** deprecated functions, for back-compatibility only ********/ -ARG_EXTERN void arg_free(void** argtable); - -#ifdef __cplusplus -} -#endif -#endif +/******************************************************************************* + * argtable3: Declares the main interfaces of the library + * + * This file is part of the argtable3 library. + * + * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of STEWART HEITMANN nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************/ + +#ifndef ARGTABLE3 +#define ARGTABLE3 + +#include /* FILE */ +#include /* struct tm */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define ARG_REX_ICASE 1 + +/* Maximum length of the command name */ +#ifndef ARG_CMD_NAME_LEN +#define ARG_CMD_NAME_LEN 100 +#endif /* ARG_CMD_NAME_LEN */ + +/* Maximum length of the command description */ +#ifndef ARG_CMD_DESCRIPTION_LEN +#define ARG_CMD_DESCRIPTION_LEN 256 +#endif /* ARG_CMD_DESCRIPTION_LEN */ + +/** + * Error codes returned by argument parsing and validation. + * + * These error codes are used by Argtable3 to indicate specific problems + * encountered during command-line parsing and validation. They are typically + * stored in the `error` array of the `arg_end_t` struct and can be used to + * generate detailed error messages for the user. + */ +enum { + ARG_ELIMIT = 1, /**< Too many occurrences of an option or argument */ + ARG_EMALLOC, /**< Memory allocation failure */ + ARG_ENOMATCH, /**< Argument value does not match the expected format or pattern */ + ARG_ELONGOPT, /**< Unknown or invalid long option encountered */ + ARG_EMISSARG /**< Missing required argument value */ +}; + +/** + * Bit masks for the `flag` field in the `arg_hdr` struct. + * + * The `arg_hdr_flag` enum defines bitwise flags that describe special + * properties of an argument entry in Argtable3. These flags are stored in the + * `flag` field of the `arg_hdr` struct and can be combined using bitwise OR. + * + * These flags help Argtable3 functions determine how to parse and process each + * argument entry. + */ +enum arg_hdr_flag { + ARG_TERMINATOR = 0x1, /**< Marks the end of an argument table (sentinel entry) */ + ARG_HASVALUE = 0x2, /**< Argument expects a value (e.g., `--output `) */ + ARG_HASOPTVALUE = 0x4 /**< Argument can optionally take a value (e.g., `--color[=WHEN]`) */ +}; + +#if defined(_WIN32) +#if defined(argtable3_EXPORTS) +#define ARG_EXTERN __declspec(dllexport) +#elif defined(argtable3_IMPORTS) +#define ARG_EXTERN __declspec(dllimport) +#else +#define ARG_EXTERN +#endif +#else +#define ARG_EXTERN +#endif + +typedef struct _internal_arg_dstr* arg_dstr_t; +typedef void* arg_cmd_itr_t; + +/** + * Function pointer type for resetting an argument structure to its initial state. + * + * The `arg_resetfn` type defines the signature for functions that reset an + * argument structure (such as `arg_lit_t`, `arg_int_t`, etc.) to its initial + * state. This is typically used internally by Argtable3 to clear any parsed + * values, counts, or state information before reusing the argument structure + * for another round of parsing. + * + * This function pointer is primarily intended for developers who want to + * implement and register new command-line option data types with Argtable3. + * If you are extending Argtable3 with custom argument types, you should + * provide a suitable reset function that matches this signature. + * + * The function receives a pointer to the parent argument structure and should + * reset all relevant fields to their default values. + * + * Example usage: + * ``` + * void my_arg_reset(void* parent) { + * arg_int_t* arg = (arg_int_t*)parent; + * arg->count = 0; + * // Reset other fields as needed... + * } + * ``` + * + * @param parent Pointer to the argument structure to reset. + */ +typedef void(arg_resetfn)(void* parent); + +/** + * Function pointer type for scanning and parsing a command-line argument value. + * + * The `arg_scanfn` type defines the signature for functions that parse a + * command-line argument value and store the result in the parent argument + * structure (such as `arg_int_t`, `arg_str_t`, etc.). This function is called + * by Argtable3 during argument parsing to convert the input string (`argval`) + * into the appropriate data type and store it in the corresponding field of the + * parent struct. + * + * This function pointer is primarily intended for developers who want to + * implement and register new command-line option data types with Argtable3. + * If you are extending Argtable3 with custom argument types, you should provide + * a suitable scan function that matches this signature. + * + * @param parent Pointer to the argument structure where the parsed value should + * be stored. + * @param argval The string value from the command line to be parsed. + * @return Returns 0 on success, or a nonzero error code if parsing fails. + */ +typedef int(arg_scanfn)(void* parent, const char* argval); + +/** + * Function pointer type for validating a parsed argument structure. + * + * The `arg_checkfn` type defines the signature for functions that perform + * post-parsing validation on an argument structure (such as `arg_int_t`, + * `arg_str_t`, etc.). This function is called by Argtable3 after all arguments + * have been parsed, allowing you to check for additional constraints or + * perform custom validation logic. + * + * This function pointer is primarily intended for developers who want to + * implement and register new command-line option data types with Argtable3. + * If you are extending Argtable3 with custom argument types, you should provide + * a suitable check function that matches this signature. + * + * @param parent Pointer to the argument structure to validate. + * @return Returns 0 if validation succeeds, or a nonzero error code if validation + * fails. + */ +typedef int(arg_checkfn)(void* parent); + +/** + * Function pointer type for reporting argument parsing or validation errors. + * + * The `arg_errorfn` type defines the signature for functions that generate + * error messages when an argument fails to parse or validate. This function is + * called by Argtable3 when an error is detected for a specific argument, and it + * is responsible for formatting and appending a descriptive error message to + * the provided dynamic string object (`arg_dstr_t`). + * + * This function pointer is primarily intended for developers who want to + * implement and register new command-line option data types with Argtable3. + * If you are extending Argtable3 with custom argument types, you should provide + * a suitable error reporting function that matches this signature. + * + * @param parent Pointer to the argument structure that caused the error. + * @param ds Dynamic string object to which the error message should be + * appended. + * @param error Error code indicating the type of error encountered. + * @param argval The offending argument value from the command line, or NULL if + * not applicable. + * @param progname The name of the program or command, used for context in the + * error message. + */ +typedef void(arg_errorfn)(void* parent, arg_dstr_t ds, int error, const char* argval, const char* progname); + +/** + * Function pointer type for freeing a dynamically allocated string buffer. + * + * The `arg_dstr_freefn` type defines the signature for functions that release + * memory allocated for a string buffer managed by a dynamic string object + * (`arg_dstr_t`). This allows custom memory management strategies to be used + * when setting or replacing the contents of a dynamic string. + * + * You can provide a custom free function when calling `arg_dstr_set`, or use + * one of the standard macros (`ARG_DSTR_STATIC`, `ARG_DSTR_VOLATILE`, + * `ARG_DSTR_DYNAMIC`) to control how the buffer is released. + * + * @param buf Pointer to the string buffer to be freed. + * + * @see arg_dstr_set, ARG_DSTR_STATIC, ARG_DSTR_VOLATILE, ARG_DSTR_DYNAMIC + */ +typedef void(arg_dstr_freefn)(char* buf); + +/** + * Function pointer type for sub-command handler functions. + * + * The `arg_cmdfn` type defines the signature for functions that implement the + * logic of a sub-command in a multi-command command-line application. When a + * sub-command is dispatched (for example, via `arg_cmd_dispatch`), the + * corresponding handler function is called with the command-line arguments, + * a dynamic string buffer for output or error messages, and an optional + * user-defined context pointer. + * + * This function pointer is primarily intended for developers who want to + * implement custom sub-commands and register them with Argtable3. The handler + * should return 0 on success, or a nonzero error code on failure. + * + * @param argc The number of command-line arguments for the sub-command. + * @param argv The array of command-line arguments for the sub-command. + * @param res Dynamic string buffer for output or error messages. + * @param ctx User-defined context pointer, as provided during registration. + * @return 0 on success, or a nonzero error code on failure. + */ +typedef int (*arg_cmdfn)(int argc, char* argv[], arg_dstr_t res, void* ctx); + +/** + * Function pointer type for custom comparison functions used in sorting. + * + * The `arg_comparefn` type defines the signature for functions that compare two + * elements, typically used with sorting algorithms such as `arg_mgsort`. The + * comparison function should return an integer less than, equal to, or greater + * than zero if the first argument is considered to be respectively less than, + * equal to, or greater than the second. + * + * This function pointer is primarily intended for developers who want to + * implement custom sorting or searching logic for arrays of arbitrary data + * types within Argtable3 or their own applications. + * + * @param k1 Pointer to the first element to compare. + * @param k2 Pointer to the second element to compare. + * @return Negative value if `k1` < `k2`, zero if `k1` == `k2`, positive value + * if `k1` > `k2`. + * + * @see arg_mgsort + */ +typedef int(arg_comparefn)(const void* k1, const void* k2); + +/** + * Defines common properties shared by all `arg_` structs. + * + * In the Argtable3 library, every `arg_` struct must begin with an + * `arg_hdr` struct as its first member. This allows Argtable3 functions to + * access shared metadata about the command-line option, such as its option + * tags, data type string, glossary text, and other attributes. + * + * The `arg_hdr` struct also contains pointers to type-specific functions + * provided by each `arg_` implementation. These functions handle tasks + * such as parsing the option, performing post-parse validation, and reporting + * errors. Although these function pointers are initialized by the constructor + * of the respective `arg_` struct, they can be modified by the user after + * construction if necessary. However, they are intended to remain unchanged + * once initialized. + */ +typedef struct arg_hdr { + char flag; /**< Modifier flags for this option (see `enum arg_hdr_flag`) */ + const char* shortopts; /**< String listing the short option characters (e.g., "hv") */ + const char* longopts; /**< String listing the long option names, comma-separated (e.g., "verbose,debug") */ + const char* datatype; /**< Description of the argument data type (e.g., "") */ + const char* glossary; /**< Description of the option as shown in the glossary/help output */ + int mincount; /**< Minimum number of occurrences of this option accepted */ + int maxcount; /**< Maximum number of occurrences of this option accepted */ + void* parent; /**< Pointer to the parent arg_ struct instance */ + arg_resetfn* resetfn; /**< Pointer to the type-specific reset function for this argument */ + arg_scanfn* scanfn; /**< Pointer to the type-specific scan (parsing) function */ + arg_checkfn* checkfn; /**< Pointer to the type-specific validation function */ + arg_errorfn* errorfn; /**< Pointer to the type-specific error reporting function */ + void* priv; /**< Pointer to private data for use by arg_ functions */ +} arg_hdr_t; + +/** + * Structure for storing remarks or custom lines in the syntax or glossary + * output. + * + * The `arg_rem` struct is used to add extra lines of text to the syntax or + * glossary output generated by Argtable3. Unlike other argument types, + * `arg_rem` does not correspond to a command-line argument and does not affect + * argument parsing. Instead, it is a dummy entry that allows you to insert + * remarks, explanations, or custom formatting into the help or usage messages. + * + * This is especially useful for providing additional context, grouping related + * options, or clarifying the usage of certain arguments in the generated + * documentation. + * + * Example usage: + * ``` + * // Add extra lines to the glossary for the --update option + * arg_lit_t *update = arg_litn("u", "update", 0, 1, "copy only when SOURCE files are"); + * arg_rem_t *update1 = arg_rem(NULL, " newer than destination files"); + * arg_rem_t *update2 = arg_rem(NULL, " or when destination files"); + * arg_rem_t *update3 = arg_rem(NULL, " are missing"); + * void *argtable[] = { update, update1, update2, update3, ... }; + * + * // Add a data type entry for a positional argument in the syntax + * arg_rem_t *dest = arg_rem("DEST|DIRECTORY", NULL); + * void *argtable[] = { ..., dest, ... }; + * ``` + * + * @see arg_rem() + */ +typedef struct arg_rem { + struct arg_hdr hdr; /**< The mandatory argtable header struct */ +} arg_rem_t; + +/** + * Structure for storing literal (boolean flag) argument information. + * + * The `arg_lit` struct is used to parse and store literal arguments (boolean + * flags) from the command line. It is suitable for options that do not take a + * value, such as `-h` for help or `--verbose` for enabling verbose output. Each + * occurrence of the flag increases the `count` field, allowing you to detect + * how many times the flag was specified. + * + * Example usage: + * ``` + * // Accepts a help flag and a verbose flag (which can be specified multiple times) + * arg_lit_t *help = arg_lit0("h", "help", "Display help"); + * arg_lit_t *verbose = arg_litn("v", "verbose", 0, 3, "Increase verbosity"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = { help, verbose, end }; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (help->count > 0) { + * printf("Help requested\n"); + * } + * if (verbose->count > 0) { + * printf("Verbosity level: %d\n", verbose->count); + * } + * ``` + * + * @see arg_lit0, arg_lit1, arg_litn + */ +typedef struct arg_lit { + struct arg_hdr hdr; /**< The mandatory argtable header struct */ + int count; /**< Number of times this flag appears on the command line */ +} arg_lit_t; + +/** + * Structure for storing int-typed argument information. + * + * The `arg_int` struct is used to parse and store integer arguments from the + * command line. It is suitable for options that accept numeric values without + * fractional parts, such as counts, indices, or other whole-number parameters. + * + * The `count` field stores the number of successfully matched integer + * arguments, and the `ival` array holds the parsed integer values as provided + * by the user. + * + * Example usage: + * ``` + * // Accepts one or more integer arguments + * arg_int_t *numbers = arg_intn("n", "number", "", 1, 5, "Input numbers"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = {numbers, end}; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors == 0 && numbers->count > 0) { + * for (int i = 0; i < numbers->count; ++i) { + * printf("Input number: %d\n", numbers->ival[i]); + * } + * } else { + * arg_print_errors(stdout, end, argv[0]); + * } + * ``` + * + * @see arg_int0, arg_int1, arg_intn + */ +typedef struct arg_int { + struct arg_hdr hdr; /**< The mandatory argtable header struct */ + int count; /**< Number of times this argument appears on the command line */ + int* ival; /**< Array of parsed integer argument values */ +} arg_int_t; + +/** + * Structure for storing double-typed argument information. + * + * The `arg_dbl` struct is used to parse and store double-precision + * floating-point arguments from the command line. It is suitable for options + * that accept numeric values with fractional parts, such as thresholds, ratios, + * or measurements. + * + * The `count` field stores the number of successfully matched double arguments, + * and the `dval` array holds the parsed double values as provided by the user. + * + * Example usage: + * ``` + * // Accepts one or more double arguments + * arg_dbl_t *values = arg_dbln("v", "value", "", 1, 5, "Input values"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = {values, end}; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors == 0 && values->count > 0) { + * for (int i = 0; i < values->count; ++i) { + * printf("Input value: %f\n", values->dval[i]); + * } + * } else { + * arg_print_errors(stdout, end, argv[0]); + * } + * ``` + * + * @see arg_dbl0, arg_dbl1, arg_dbln + */ +typedef struct arg_dbl { + struct arg_hdr hdr; /**< The mandatory argtable header struct */ + int count; /**< Number of times this argument appears on the command line */ + double* dval; /**< Array of parsed double argument values */ +} arg_dbl_t; + +/** + * Structure for storing string-typed argument information. + * + * The `arg_str` struct is used to parse and store string arguments from the + * command line. It is suitable for options that accept arbitrary text input, + * such as file names, user names, or other string values. + * + * The `count` field stores the number of successfully matched string arguments, + * and the `sval` array holds the parsed string values as provided by the user. + * + * Example usage: + * ``` + * // Accepts one or more string arguments + * arg_str_t *inputs = arg_strn(NULL, NULL, "", 1, 10, "Input strings"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = {inputs, end}; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors == 0 && inputs->count > 0) { + * for (int i = 0; i < inputs->count; ++i) { + * printf("Input string: %s\n", inputs->sval[i]); + * } + * } else { + * arg_print_errors(stdout, end, argv[0]); + * } + * ``` + * + * @see arg_str0, arg_str1, arg_strn + */ +typedef struct arg_str { + struct arg_hdr hdr; /**< The mandatory argtable header struct */ + int count; /**< Number of times this argument appears on the command line */ + const char** sval; /**< Array of parsed string argument values */ +} arg_str_t; + +/** + * Structure for storing regular expression-typed argument information. + * + * The `arg_rex` struct is used to parse and store command-line arguments that + * must match a specified regular expression pattern. This allows applications + * to validate input against complex patterns, such as email addresses, + * identifiers, or custom formats. + * + * The `pattern` is specified when constructing the argument and is used to + * check each input value. The `count` field stores the number of successfully + * matched arguments, and the `sval` array holds the matched strings. + * + * Example usage: + * ``` + * // Accepts one or more arguments matching a simple email pattern + * arg_rex_t *emails = arg_rexn(NULL, "email", "^[^@]+@[^@]+\\.[^@]+$", "", 1, 10, 0, "Email addresses"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = {emails, end}; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors == 0 && emails->count > 0) { + * for (int i = 0; i < emails->count; ++i) { + * printf("Matched email: %s\n", emails->sval[i]); + * } + * } else { + * arg_print_errors(stdout, end, argv[0]); + * } + * ``` + * + * @see arg_rex0, arg_rex1, arg_rexn + */ +typedef struct arg_rex { + struct arg_hdr hdr; /**< The mandatory argtable header struct */ + int count; /**< Number of times this argument appears on the command line */ + const char** sval; /**< Array of parsed string argument values */ +} arg_rex_t; + +/** + * Structure for storing file-typed argument information. + * + * The `arg_file` struct is used to parse and store file path arguments from the + * command line. It provides convenient access to the full filename, the + * basename (file name without path), and the file extension for each matched + * argument. This allows applications to easily process and validate + * file-related options. + * + * The `count` field stores the number of successfully matched file arguments. + * The `filename` array holds the full file paths as provided by the user, while + * the `basename` and `extension` arrays provide the corresponding file names + * and extensions, respectively. + * + * Example usage: + * ``` + * // Accepts one or more file arguments + * arg_file_t *files = arg_filen(NULL, NULL, "", 1, 100, "Input files"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = {files, end}; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors == 0 && files->count > 0) { + * for (int i = 0; i < files->count; ++i) { + * printf("File: %s, Basename: %s, Extension: %s\n", + * files->filename[i], files->basename[i], files->extension[i]); + * } + * } else { + * arg_print_errors(stdout, end, argv[0]); + * } + * ``` + * + * @see arg_file0, arg_file1, arg_filen + */ +typedef struct arg_file { + struct arg_hdr hdr; /**< The mandatory argtable header struct */ + int count; /**< Number of times this argument appears on the command line */ + const char** filename; /**< Array of parsed file path values (e.g., /home/foo.bar) */ + const char** basename; /**< Array of parsed base names (e.g., foo.bar) */ + const char** extension; /**< Array of parsed file extensions (e.g., .bar) */ +} arg_file_t; + +/** + * Structure for storing date-typed argument information. + * + * The `arg_date` struct is used to parse and store date or time arguments from + * the command line. It supports flexible date/time formats, which are specified + * using a `strptime`-style format string. Each successfully parsed date + * argument is converted into a `struct tm` value and stored in the `tmval` + * array. + * + * The `format` field defines the expected input format for date arguments, + * allowing you to accept a wide range of date/time styles. The `count` field + * stores the number of successfully matched arguments, and the `tmval` array + * holds the parsed results. + * + * Example usage: + * ``` + * // Accepts one required date argument in YYYY-MM-DD format + * arg_date_t *date = arg_date1(NULL, "date", "%Y-%m-%d", "", "Date in YYYY-MM-DD format"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = {date, end}; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors == 0 && date->count > 0) { + * printf("Parsed date: %04d-%02d-%02d\n", + * date->tmval[0].tm_year + 1900, date->tmval[0].tm_mon + 1, date->tmval[0].tm_mday); + * } else { + * arg_print_errors(stdout, end, argv[0]); + * } + * ``` + * + * @see arg_date0, arg_date1, arg_daten + */ +typedef struct arg_date { + struct arg_hdr hdr; /**< The mandatory argtable header struct */ + const char* format; /**< strptime format string used to parse the date */ + int count; /**< Number of times this argument appears on the command line */ + struct tm* tmval; /**< Array of parsed time values */ +} arg_date_t; + +/** + * Structure for collecting parser errors and terminating an argument table. + * + * The `arg_end` struct is used in Argtable3 to mark the end of an argument + * table and to collect information about any errors encountered during + * command-line parsing. It stores pointers to offending arguments in the input + * array, allowing the application to report detailed error messages to the + * user. + * + * Typically, an `arg_end_t` instance is created using the `arg_end` function + * and placed as the last element in the argument table array. After parsing, + * the structure contains information about missing required arguments, invalid + * values, or other parsing errors. + * + * Example usage: + * ``` + * arg_lit_t *help = arg_lit0("h", "help", "Display help"); + * arg_int_t *count = arg_int0("c", "count", "", "Number of times"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = {help, count, end}; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors > 0) { + * arg_print_errors(stdout, end, argv[0]); // handle errors... + * } + * ``` + */ +typedef struct arg_end { + struct arg_hdr hdr; /**< The mandatory argtable header struct */ + int count; /**< Number of errors encountered */ + int* error; /**< Array of error codes */ + void** parent; /**< Array of pointers to offending arg_ struct */ + const char** argval; /**< Array of pointers to offending argv[] string */ +} arg_end_t; + +/** + * Structure for storing sub-command information. + * + * The `arg_cmd_info` struct is used to represent metadata and handler + * information for a sub-command in a multi-command command-line application. + * Each sub-command can have its own name, description, handler function, and + * context pointer, allowing you to build flexible interfaces similar to tools + * like `git` or `docker`. + * + * The `name` field stores the sub-command name, while the `description` + * provides a short summary for help and usage messages. The `proc` field is a + * pointer to the function that implements the sub-command's behavior, and `ctx` + * is a user-defined context pointer that can be used to pass additional data to + * the handler. + * + * Example usage: + * ``` + * // Define a handler function for the "list" sub-command + * int list_cmd(int argc, char* argv[], arg_dstr_t res, void* ctx) { + * // Implementation for the "list" command + * return 0; + * } + * + * // Register the sub-command + * arg_cmd_register("list", list_cmd, "List all items", NULL); + * + * // Retrieve sub-command info + * arg_cmd_info_t* info = arg_cmd_info("list"); + * if (info) { + * printf("Sub-command: %s - %s\n", info->name, info->description); + * } + * ``` + * + * @see arg_cmd_register, arg_cmd_info, arg_cmd_dispatch + */ +typedef struct arg_cmd_info { + char name[ARG_CMD_NAME_LEN]; /**< Sub-command name */ + char description[ARG_CMD_DESCRIPTION_LEN]; /**< Short description of the sub-command */ + arg_cmdfn proc; /**< Sub-command handler function */ + void* ctx; /**< User-defined context pointer for the sub-command */ +} arg_cmd_info_t; + +/**** arg_ constructor functions *********************************/ + +/** + * Adds a remark or custom line to the syntax or glossary output. + * + * The `arg_rem` function allows you to insert extra lines of text into the + * syntax or glossary output generated by Argtable3. Instead of embedding + * newline characters directly in your argument table strings—which can make + * the code messy—you can add `arg_rem` structs to your argument table. These + * are dummy entries: they do not affect argument parsing, but their `datatype` + * and `glossary` strings are included in the output of `arg_print_syntax` and + * `arg_print_glossary`. + * + * The name `arg_rem` stands for *remark*, inspired by the `REM` statement in + * the BASIC programming language. + * + * For example, in the `mv` example program, we use `arg_rem` to add additional + * lines for the `-u|--update` option in the glossary: + * ``` + * arg_lit_t *update = arg_litn("u", "update", 0, 1, "copy only when SOURCE files are"); + * arg_rem_t *update1 = arg_rem(NULL, " newer than destination files"); + * arg_rem_t *update1 = arg_rem(NULL, " or when destination files"); + * arg_rem_t *update2 = arg_rem(NULL, " are missing"); + * ``` + * + * which will make the glossay look like: + * ``` + * -u, --update copy only when SOURCE files are + * newer than destination files + * or when the destination files + * are missing + * ``` + * + * We also use `arg_rem` to add a data type entry for the ordinary argument in + * the syntax: + * ``` + * arg_rem_t *dest = arg_rem ("DEST|DIRECTORY", NULL); + * ``` + * + * which will make the syntax look like: + * ``` + * $ mv --help + * Usage: mv [-bfiuv] [--backup=[CONTROL]] [--reply={yes,no,query}] + * [--strip-trailing-slashes] [-S SUFFIX] [--target-directory=DIRECTORY] + * [--help] [--version] SOURCE [SOURCE]... DEST|DIRECTORY + * ``` + * + * @param datatype The data type or positional argument string to display in the + * syntax output, or NULL if not needed. + * @param glossary The remark or extra line to display in the glossary output, + * or NULL if not needed. + * + * @return + * If successful, returns a pointer to the allocated `arg_rem_t`. Otherwise, + * returns `NULL` if there is insufficient memory available. + */ +ARG_EXTERN arg_rem_t* arg_rem(const char* datatype, const char* glossary); + +/** + * Creates a literal (boolean flag) argument for the command-line parser. + * + * The `arg_litn` function defines an option that does not take a value, such as + * a boolean flag (e.g., `-h` for help or `--verbose` for verbosity). You can + * specify the minimum and maximum number of times the flag can appear, making + * it suitable for optional, required, or repeatable flags. Each occurrence of + * the flag increases the `count` field in the resulting `arg_lit_t` struct. + * + * A classic example is the `tar` utility, which uses `--verbose` or `-v` to + * show the files being worked on as `tar` is creating an archive: + * ``` + * $ tar -cvf afiles.tar apple angst aspic + * apple + * angst + * aspic + * ``` + * + * Each occurrence of `--verbose` or `-v` on the command line increases the + * verbosity level by one. Therefore, if you need more details on the output, + * specify it twice: + * ``` + * $ tar -cvvf afiles.tar apple angst aspic + * -rw-r--r-- gray/staff 62373 2006-06-09 12:06 apple + * -rw-r--r-- gray/staff 11481 2006-06-09 12:06 angst + * -rw-r--r-- gray/staff 23152 2006-06-09 12:06 aspic + * ``` + * + * The `arg_litn` function allows you to specify both the minimum and maximum + * number of times a flag can appear. For convenience and backward + * compatibility, `arg_lit0` is provided as a helper for optional flags + * (where `mincount = 0` and `maxcount = 1`), and `arg_lit1` is a helper for + * required flags (where `mincount = 1` and `maxcount = 1`). While `arg_lit0` + * and `arg_lit1` are available, it is recommended to use `arg_litn` in new + * code as it is more explicit and flexible. + * + * Example usage: + * ``` + * arg_lit_t *list = arg_litn("lL",NULL, 0, 1, "list files"); + * arg_lit_t *verbose = arg_litn("v","verbose,debug", 0, 3, "verbosity level"); + * arg_lit_t *help = arg_litn("h","help", 0, 1, "print this help"); + * arg_lit_t *version = arg_litn(NULL,"version", 0, 1, "print version info"); + * ``` + * + * @param shortopts A string of single characters, each representing a short option + * name (e.g., `"v"` for `-v`). Pass `NULL` if no short option is + * desired. + * @param longopts A string of comma-separated long option names (e.g., + * `"verbose"` for `--verbose`). Pass `NULL` if no long option is + * desired. + * @param mincount The minimum number of times the flag must appear (set to 0 for + * optional). + * @param maxcount The maximum number of times the flag can appear (controls memory + * allocation). + * @param glossary A short description of the argument for the glossary/help + * output. Pass `NULL` to omit. + * + * @return + * If successful, returns a pointer to the allocated `arg_lit_t`. Returns + * `NULL` if there is insufficient memory. + */ +ARG_EXTERN arg_lit_t* arg_litn(const char* shortopts, const char* longopts, int mincount, int maxcount, const char* glossary); +ARG_EXTERN arg_lit_t* arg_lit0(const char* shortopts, const char* longopts, const char* glossary); +ARG_EXTERN arg_lit_t* arg_lit1(const char* shortopts, const char* longopts, const char* glossary); + +/** + * Creates an integer argument for the command-line parser. + * + * The `arg_intn` function defines an option that accepts integer values from + * the command line. You can specify the minimum and maximum number of times the + * argument can appear, making it suitable for optional, required, or repeatable + * integer options. Each occurrence of the option is parsed and stored in the + * `ival` array of the resulting `arg_int_t` struct, allowing you to retrieve + * all provided integer values after parsing. + * + * For convenience and backward compatibility, `arg_int0` is provided as a + * helper for optional integer arguments (where `mincount = 0` and + * `maxcount = 1`), and `arg_int1` is a helper for required integer arguments + * (where `mincount = 1` and `maxcount = 1`). While `arg_int0` and `arg_int1` + * are available, it is recommended to use `arg_intn` in new code as it is more + * explicit and flexible. + * + * Example usage: + * ``` + * // Accepts one or more integer arguments + * arg_int_t *numbers = arg_intn("n", "number", "", 1, 5, "Input numbers"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = { numbers, end }; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors == 0 && numbers->count > 0) { + * for (int i = 0; i < numbers->count; ++i) { + * printf("Input number: %d\n", numbers->ival[i]); + * } + * } else { + * arg_print_errors(stdout, end, argv[0]); + * } + * ``` + * + * @param shortopts A string of single characters, each representing a short + * option name (e.g., `"n"` for `-n`). Pass `NULL` if no short + * option is desired. + * @param longopts A string of comma-separated long option names (e.g., + * `"number"` for `--number`). Pass `NULL` if no long option is + * desired. + * @param datatype A string describing the expected data type (e.g., `""`), + * shown in help messages. + * @param mincount The minimum number of times the argument must appear (set to 0 + * for optional). + * @param maxcount The maximum number of times the argument can appear (controls + * memory allocation). + * @param glossary A short description of the argument for the glossary/help + * output. Pass `NULL` to omit. + * + * @return + * If successful, returns a pointer to the allocated `arg_int_t`. Returns + * `NULL` if there is insufficient memory. + */ +ARG_EXTERN arg_int_t* arg_intn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary); +ARG_EXTERN arg_int_t* arg_int0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); +ARG_EXTERN arg_int_t* arg_int1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); + +/** + * Creates a double-precision floating-point argument for the command-line parser. + * + * The `arg_dbln` function defines an option that accepts double-precision + * floating-point values from the command line. You can specify the minimum and + * maximum number of times the argument can appear, making it suitable for + * optional, required, or repeatable floating-point options. Each occurrence of + * the option is parsed and stored in the `dval` array of the resulting + * `arg_dbl_t` struct, allowing you to retrieve all provided double values after + * parsing. + * + * For convenience and backward compatibility, `arg_dbl0` is provided as a + * helper for optional double arguments (where `mincount = 0` and + * `maxcount = 1`), and `arg_dbl1` is a helper for required double arguments + * (where `mincount = 1` and `maxcount = 1`). While `arg_dbl0` and `arg_dbl1` + * are available, it is recommended to use `arg_dbln` in new code as it is more + * explicit and flexible. + * + * Example usage: + * ``` + * // Accepts one or more double arguments + * arg_dbl_t *values = arg_dbln("v", "value", "", 1, 5, "Input values"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = {values, end}; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors == 0 && values->count > 0) { + * for (int i = 0; i < values->count; ++i) { + * printf("Input value: %f\n", values->dval[i]); + * } + * } else { + * arg_print_errors(stdout, end, argv[0]); + * } + * ``` + * + * @param shortopts A string of single characters, each representing a short + * option name (e.g., `"v"` for `-v`). Pass `NULL` if no short + * option is desired. + * @param longopts A string of comma-separated long option names (e.g., + * `"value"` for `--value`). Pass `NULL` if no long option is + * desired. + * @param datatype A string describing the expected data type (e.g., + * `""`), shown in help messages. + * @param mincount The minimum number of times the argument must appear (set to + * 0 for optional). + * @param maxcount The maximum number of times the argument can appear + * (controls memory allocation). + * @param glossary A short description of the argument for the glossary/help + * output. Pass `NULL` to omit. + * + * @return + * If successful, returns a pointer to the allocated `arg_dbl_t`. Returns + * `NULL` if there is insufficient memory. + */ +ARG_EXTERN arg_dbl_t* arg_dbln(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary); +ARG_EXTERN arg_dbl_t* arg_dbl0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); +ARG_EXTERN arg_dbl_t* arg_dbl1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); + +/** + * Creates a string argument for the command-line parser. + * + * The `arg_strn` function defines an option that accepts string values from the + * command line. You can specify the minimum and maximum number of times the + * argument can appear, making it suitable for optional, required, or repeatable + * string options. Each occurrence of the option is parsed and stored in the + * `sval` array of the resulting `arg_str_t` struct, allowing you to retrieve + * all provided string values after parsing. + * + * For convenience and backward compatibility, `arg_str0` is provided as a + * helper for optional string arguments (where `mincount = 0` and + * `maxcount = 1`), and `arg_str1` is a helper for required string arguments + * (where `mincount = 1` and `maxcount = 1`). While `arg_str0` and `arg_str1` + * are available, it is recommended to use `arg_strn` in new code as it is more + * explicit and flexible. + * + * Example usage: + * ``` + * // Accepts one or more string arguments + * arg_str_t *inputs = arg_strn(NULL, NULL, "", 1, 10, "Input strings"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = { inputs, end }; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors == 0 && inputs->count > 0) { + * for (int i = 0; i < inputs->count; ++i) { + * printf("Input string: %s\n", inputs->sval[i]); + * } + * } else { + * arg_print_errors(stdout, end, argv[0]); + * } + * ``` + * + * @param shortopts A string of single characters, each representing a short + * option name (e.g., `"i"` for `-i`). Pass `NULL` if no short + * option is desired. + * @param longopts A string of comma-separated long option names (e.g., + * `"input"` for `--input`). Pass `NULL` if no long option is + * desired. + * @param datatype A string describing the expected data type (e.g., + * `""`), shown in help messages. + * @param mincount The minimum number of times the argument must appear (set to + * 0 for optional). + * @param maxcount The maximum number of times the argument can appear + * (controls memory allocation). + * @param glossary A short description of the argument for the glossary/help + * output. Pass `NULL` to omit. + * + * @return + * If successful, returns a pointer to the allocated `arg_str_t`. Returns + * `NULL` if there is insufficient memory. + */ +ARG_EXTERN arg_str_t* arg_strn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary); +ARG_EXTERN arg_str_t* arg_str0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); +ARG_EXTERN arg_str_t* arg_str1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); + +/** + * Creates a regular expression argument for the command-line parser. + * + * The `arg_rexn` function defines an option that accepts values matching a + * specified regular expression pattern. You can specify the minimum and maximum + * number of times the argument can appear, making it suitable for optional, + * required, or repeatable regex-matched options. Each occurrence of the option + * is parsed and stored in the `sval` array of the resulting `arg_rex_t` struct, + * allowing you to retrieve all provided values that match the regular expression + * after parsing. + * + * For convenience and backward compatibility, `arg_rex0` is provided as a + * helper for optional regex arguments (where `mincount = 0` and `maxcount = 1`), + * and `arg_rex1` is a helper for required regex arguments (where `mincount = 1` + * and `maxcount = 1`). While `arg_rex0` and `arg_rex1` are available, it is + * recommended to use `arg_rexn` in new code as it is more explicit and flexible. + * + * Example usage: + * ``` + * // Accepts one or more arguments matching a simple email pattern + * arg_rex_t *emails = arg_rexn(NULL, "email", "^[^@]+@[^@]+\\.[^@]+$", "", 1, 10, 0, "Email addresses"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = { emails, end }; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors == 0 && emails->count > 0) { + * for (int i = 0; i < emails->count; ++i) { + * printf("Matched email: %s\n", emails->sval[i]); + * } + * } else { + * arg_print_errors(stdout, end, argv[0]); + * } + * ``` + * + * @param shortopts A string of single characters, each representing a short + * option name (e.g., `"e"` for `-e`). Pass `NULL` if no short + * option is desired. + * @param longopts A string of comma-separated long option names (e.g., + * `"email"` for `--email`). Pass `NULL` if no long option is + * desired. + * @param pattern The regular expression pattern to match input values. + * @param datatype A string describing the expected data type (e.g., + * `""`), shown in help messages. + * @param mincount The minimum number of times the argument must appear (set to + * 0 for optional). + * @param maxcount The maximum number of times the argument can appear + * (controls memory allocation). + * @param flags Flags to modify regex matching behavior (e.g., + * `ARG_REX_ICASE` for case-insensitive). + * @param glossary A short description of the argument for the glossary/help + * output. Pass `NULL` to omit. + * + * @return + * If successful, returns a pointer to the allocated `arg_rex_t`. Returns + * `NULL` if there is insufficient memory. + */ +ARG_EXTERN arg_rex_t* arg_rexn(const char* shortopts, + const char* longopts, + const char* pattern, + const char* datatype, + int mincount, + int maxcount, + int flags, + const char* glossary); +ARG_EXTERN arg_rex_t* arg_rex0(const char* shortopts, + const char* longopts, + const char* pattern, + const char* datatype, + int flags, + const char* glossary); +ARG_EXTERN arg_rex_t* arg_rex1(const char* shortopts, + const char* longopts, + const char* pattern, + const char* datatype, + int flags, + const char* glossary); + +/** + * Creates a file path argument for the command-line parser. + * + * The `arg_filen` function defines an option that accepts file path values from + * the command line. You can specify the minimum and maximum number of times the + * argument can appear, making it suitable for optional, required, or repeatable + * file arguments. Each occurrence of the option is parsed and stored in the + * `filename` array of the resulting `arg_file_t` struct. The struct also + * provides convenient access to the basename and extension for each file. + * + * For convenience and backward compatibility, `arg_file0` is provided as a + * helper for optional file arguments (where `mincount = 0` and `maxcount = 1`), + * and `arg_file1` is a helper for required file arguments (where `mincount = 1` + * and `maxcount = 1`). While `arg_file0` and `arg_file1` are available, it is + * recommended to use `arg_filen` in new code as it is more explicit and flexible. + * + * Example usage: + * ``` + * // Accepts one or more file arguments + * arg_file_t *files = arg_filen(NULL, NULL, "", 1, 100, "Input files"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = { files, end }; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors == 0 && files->count > 0) { + * for (int i = 0; i < files->count; ++i) { + * printf("File: %s, Basename: %s, Extension: %s\n", + * files->filename[i], files->basename[i], files->extension[i]); + * } + * } else { + * arg_print_errors(stdout, end, argv[0]); + * } + * ``` + * + * @param shortopts A string of single characters, each representing a short + * option name (e.g., `"f"` for `-f`). Pass `NULL` if no short + * option is desired. + * @param longopts A string of comma-separated long option names (e.g., + * `"file"` for `--file`). Pass `NULL` if no long option is + * desired. + * @param datatype A string describing the expected data type (e.g., + * `""`), shown in help messages. + * @param mincount The minimum number of times the argument must appear (set to + * 0 for optional). + * @param maxcount The maximum number of times the argument can appear + * (controls memory allocation). + * @param glossary A short description of the argument for the glossary/help + * output. Pass `NULL` to omit. + * + * @return + * If successful, returns a pointer to the allocated `arg_file_t`. Returns + * `NULL` if there is insufficient memory. + */ +ARG_EXTERN arg_file_t* arg_filen(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary); +ARG_EXTERN arg_file_t* arg_file0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); +ARG_EXTERN arg_file_t* arg_file1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary); + +/** + * Creates a date/time argument for the command-line parser. + * + * The `arg_daten` function defines an option that accepts date or time values + * from the command line. You can specify the minimum and maximum number of + * times the argument can appear, making it suitable for optional, required, or + * repeatable date/time arguments. Each occurrence of the option is parsed using + * the specified `format` (a `strptime`-style format string) and stored as a + * `struct tm` value in the `tmval` array of the resulting `arg_date_t` struct, + * allowing you to retrieve all provided date/time values after parsing. + * + * For convenience and backward compatibility, `arg_date0` is provided as a + * helper for optional date arguments (where `mincount = 0` and `maxcount = 1`), + * and `arg_date1` is a helper for required date arguments (where `mincount = 1` + * and `maxcount = 1`). While `arg_date0` and `arg_date1` are available, it is + * recommended to use `arg_daten` in new code as it is more explicit and flexible. + * + * Example usage: + * ``` + * // Accepts one required date argument in YYYY-MM-DD format + * arg_date_t *date = arg_date1(NULL, "date", "%Y-%m-%d", "", "Date in YYYY-MM-DD format"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = { date, end }; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors == 0 && date->count > 0) { + * printf("Parsed date: %04d-%02d-%02d\n", + * date->tmval[0].tm_year + 1900, date->tmval[0].tm_mon + 1, date->tmval[0].tm_mday); + * } else { + * arg_print_errors(stdout, end, argv[0]); + * } + * ``` + * + * @param shortopts A string of single characters, each representing a short + * option name (e.g., `"d"` for `-d`). Pass `NULL` if no short + * option is desired. + * @param longopts A string of comma-separated long option names (e.g., + * `"date"` for `--date`). Pass `NULL` if no long option is + * desired. + * @param format A `strptime`-style format string describing the expected + * date/time input (e.g., `"%Y-%m-%d"`). + * @param datatype A string describing the expected data type (e.g., + * `""`), shown in help messages. + * @param mincount The minimum number of times the argument must appear (set to + * 0 for optional). + * @param maxcount The maximum number of times the argument can appear + * (controls memory allocation). + * @param glossary A short description of the argument for the glossary/help + * output. Pass `NULL` to omit. + * + * @return + * If successful, returns a pointer to the allocated `arg_date_t`. Returns + * `NULL` if there is insufficient memory. + */ +ARG_EXTERN arg_date_t* +arg_daten(const char* shortopts, const char* longopts, const char* format, const char* datatype, int mincount, int maxcount, const char* glossary); +ARG_EXTERN arg_date_t* arg_date0(const char* shortopts, const char* longopts, const char* format, const char* datatype, const char* glossary); +ARG_EXTERN arg_date_t* arg_date1(const char* shortopts, const char* longopts, const char* format, const char* datatype, const char* glossary); + +/** + * Creates an end-of-table marker and error collector for the argument table. + * + * The `arg_end` function is used to create an `arg_end_t` struct, which should + * be placed as the last element in the argument table array. This structure + * serves two purposes: it marks the end of the argument table for the parser, + * and it collects information about any errors encountered during command-line + * parsing. + * + * The `maxcount` parameter specifies the maximum number of errors that can be + * recorded. After parsing, the `arg_end_t` struct contains details about + * missing required arguments, invalid values, or other parsing errors, which + * can be reported to the user using functions like `arg_print_errors`. + * + * Example usage: + * ``` + * arg_lit_t *help = arg_lit0("h", "help", "Display help"); + * arg_int_t *count = arg_int0("c", "count", "", "Number of times"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = {help, count, end}; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors > 0) { + * arg_print_errors(stdout, end, argv[0]); + * // handle errors... + * } + * ``` + * + * @param maxcount The maximum number of errors to record during parsing. + * Choose a value large enough to capture all possible errors. + * @return + * If successful, returns a pointer to the allocated `arg_end_t`. Returns + * `NULL` if there is insufficient memory. + * + * @see arg_end_t, arg_parse, arg_print_errors + */ +ARG_EXTERN arg_end_t* arg_end(int maxcount); + +/**** other functions *******************************************/ + +/** + * Checks the argument table for null entries. + * + * The `arg_nullcheck` function scans the provided argument table array and + * returns 1 if any entry is NULL, or 0 if all entries are valid. This is useful + * for detecting memory allocation failures after constructing all argument + * table entries with `arg_` constructor functions, such as `arg_litn`. + * + * Instead of checking the return value of each constructor individually, you + * can call `arg_nullcheck` once after building the argument table to ensure + * that all arguments were allocated successfully. This helps make your code + * cleaner and more robust. + * + * Example usage: + * ``` + * arg_lit_t *list = arg_lit0("lL",NULL, "list files"); + * arg_lit_t *verbose = arg_lit0("v","verbose,debug", "verbose messages"); + * arg_lit_t *help = arg_lit0(NULL,"help", "print this help and exit"); + * arg_lit_t *version = arg_lit0(NULL,"version", "print version and exit"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = {list, verbose, help, version, end}; + * const char *progname = "myprog"; + * int exitcode = 0; + * + * if (arg_nullcheck(argtable) != 0) { + * printf("%s: insufficient memory\n", progname); + * exitcode = 1; + * goto exit; + * } + * ``` + * + * @param argtable Array of pointers to argument table structs. + * + * @return Returns 1 if any entry is NULL, 0 if all entries are valid. + */ +ARG_EXTERN int arg_nullcheck(void** argtable); + +/** + * Parses the command-line arguments according to the specified argument table. + * + * The `arg_parse` function processes the command-line arguments provided in + * `argv` and populates the fields of each argument structure in the `argtable` + * array. It checks for the presence, validity, and value of each option or + * positional argument as defined by the argument table. Any errors encountered + * during parsing, such as missing required arguments or invalid values, are + * recorded in the `arg_end_t` structure (typically the last entry in the table). + * + * After calling `arg_parse`, you can inspect the fields of each argument struct + * (such as `count`, `ival`, `dval`, `sval`, etc.) to retrieve the parsed + * values. If errors are detected (i.e., the return value is greater than zero), + * you can use `arg_print_errors` to display detailed error messages to the user. + * + * Example usage: + * ``` + * arg_lit_t *help = arg_lit0("h", "help", "Display help"); + * arg_int_t *count = arg_int0("c", "count", "", "Number of times"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = {help, count, end}; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors > 0) { + * arg_print_errors(stdout, end, argv[0]); + * // handle errors... + * } + * ``` + * + * @param argc The number of command-line arguments passed to the program. + * The value is always greater than or equal to 1. + * @param argv An array of null-terminated strings representing the + * command-line arguments. By convention, `argv[0]` is the + * program name, and `argv[1]` to `argv[argc-1]` are the + * arguments. `argv[argc]` is always NULL. + * @param argtable An array of pointers to argument table structs, each created + * by an `arg_` constructor. The last entry should be an + * `arg_end` struct. + * + * @return The number of errors found during parsing. Returns 0 if parsing was + * successful and no errors were detected. + */ +ARG_EXTERN int arg_parse(int argc, char** argv, void** argtable); + +/** + * Prints a formatted command-line option specification to a file stream. + * + * The `arg_print_option` function generates a formatted representation of a + * command-line option, including its short options, long options, data type, + * and an optional suffix. This is useful for displaying option syntax in help + * messages, usage output, or documentation. + * + * The formatted option is written to the specified file stream (`fp`). You can + * control the appearance of the option specification, making it easy to + * integrate with custom help or documentation systems. + * + * Example usage: + * ``` + * // Print option to stdout + * arg_print_option(stdout, "h", "help", NULL, NULL); + * ``` + * + * @param fp Output file stream to write to (e.g., `stdout` or `stderr`). + * @param shortopts String of short option characters (e.g., `"h"` for `-h`). + * @param longopts String of long option names, comma-separated (e.g., `"help"` for `--help`). + * @param datatype String describing the expected data type (e.g., `""`). + * @param suffix Optional string to append after the option specification. + */ +ARG_EXTERN void arg_print_option(FILE* fp, const char* shortopts, const char* longopts, const char* datatype, const char* suffix); + +/** + * Prints a formatted command-line option specification to a dynamic string. + * + * The `arg_print_option_ds` function generates a formatted representation of a + * command-line option, including its short options, long options, data type, + * and an optional suffix. This is useful for displaying option syntax in help + * messages, usage output, or documentation that is built using dynamic string + * buffers. + * + * The formatted option is written to the specified dynamic string object + * (`arg_dstr_t`). You can control the appearance of the option specification, + * making it easy to integrate with custom help or documentation systems that + * require string-based output. + * + * Example usage: + * ``` + * // Print option to a dynamic string + * arg_dstr_t ds = arg_dstr_create(); + * arg_print_option_ds(ds, "v", "verbose", "", NULL); + * printf("%s", arg_dstr_cstr(ds)); + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Dynamic string object to write to. + * @param shortopts String of short option characters (e.g., `"h"` for `-h`). + * @param longopts String of long option names, comma-separated (e.g., `"help"` for `--help`). + * @param datatype String describing the expected data type (e.g., `""`). + * @param suffix Optional string to append after the option specification. + */ +ARG_EXTERN void arg_print_option_ds(arg_dstr_t ds, const char* shortopts, const char* longopts, const char* datatype, const char* suffix); + +/** + * Prints a compact, single-line command-line syntax summary to a file stream. + * + * The `arg_print_syntax` function generates a concise, single-line usage + * summary for the command-line options and arguments defined in the argument + * table. This summary is useful for displaying quick usage information to + * users, such as in the output of a `--help` or usage message. + * + * The formatted syntax summary is written to the specified file stream (`fp`). + * You can append a custom `suffix` string to the end of the summary, for + * example, to indicate positional arguments. + * + * Example usage: + * ``` + * // Print compact syntax summary to stdout + * arg_print_syntax(stdout, argtable, "[FILES...]"); + * ``` + * + * @param fp Output file stream to write to (e.g., `stdout` or `stderr`). + * @param argtable Array of argument table structs describing the available + * options and arguments. + * @param suffix String to append at the end of the syntax summary (e.g., for + * positional arguments). + */ +ARG_EXTERN void arg_print_syntax(FILE* fp, void** argtable, const char* suffix); + +/** + * Prints a compact, single-line command-line syntax summary to a dynamic string. + * + * The `arg_print_syntax_ds` function generates a concise, single-line usage + * summary for the command-line options and arguments defined in the argument + * table. This summary is useful for displaying quick usage information to + * users, such as in the output of a `--help` or usage message, and is written + * to a dynamic string object (`arg_dstr_t`). + * + * You can append a custom `suffix` string to the end of the summary, for + * example, to indicate positional arguments. + * + * Example usage: + * ``` + * // Print compact syntax summary to a dynamic string + * arg_dstr_t ds = arg_dstr_create(); + * arg_print_syntax_ds(ds, argtable, "[FILES...]"); + * printf("%s", arg_dstr_cstr(ds)); + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Dynamic string object to write to. + * @param argtable Array of argument table structs describing the available + * options and arguments. + * @param suffix String to append at the end of the syntax summary (e.g., for + * positional arguments). + */ +ARG_EXTERN void arg_print_syntax_ds(arg_dstr_t ds, void** argtable, const char* suffix); + +/** + * Prints a verbose, multi-line command-line syntax summary to a file stream. + * + * The `arg_print_syntaxv` function generates a detailed, multi-line usage + * summary for the command-line options and arguments defined in the argument + * table. This verbose style provides more clarity than the compact single-line + * form, making it easier for users to understand complex command-line + * interfaces. + * + * The formatted syntax summary is written to the specified file stream (`fp`). + * You can append a custom `suffix` string to the end of the summary, for + * example, to indicate positional arguments. + * + * Example usage: + * ``` + * // Print verbose syntax summary to stdout + * arg_print_syntaxv(stdout, argtable, "[FILES...]"); + * ``` + * + * @param fp Output file stream to write to (e.g., `stdout` or `stderr`). + * @param argtable Array of argument table structs describing the available + * options and arguments. + * @param suffix String to append at the end of the syntax summary (e.g., for + * positional arguments). + */ +ARG_EXTERN void arg_print_syntaxv(FILE* fp, void** argtable, const char* suffix); + +/** + * Prints a verbose, multi-line command-line syntax summary to a dynamic string. + * + * The `arg_print_syntaxv_ds` function generates a detailed, multi-line usage + * summary for the command-line options and arguments defined in the argument + * table. This verbose style provides more clarity than the compact single-line + * form, making it easier for users to understand complex command-line + * interfaces. + * + * The formatted syntax summary is written to the specified dynamic string + * object (`arg_dstr_t`). You can append a custom `suffix` string to the end of + * the summary, for example, to indicate positional arguments. + * + * Example usage: + * ``` + * // Print verbose syntax summary to a dynamic string + * arg_dstr_t ds = arg_dstr_create(); + * arg_print_syntaxv_ds(ds, argtable, "[FILES...]"); + * printf("%s", arg_dstr_cstr(ds)); + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Dynamic string object to write to. + * @param argtable Array of argument table structs describing the available + * options and arguments. + * @param suffix String to append at the end of the syntax summary (e.g., for + * positional arguments). + */ +ARG_EXTERN void arg_print_syntaxv_ds(arg_dstr_t ds, void** argtable, const char* suffix); + +/** + * Prints the argument glossary in a customizable format to a file stream. + * + * The `arg_print_glossary` function generates a glossary of command-line + * options and arguments, formatted according to the specified format string. + * This glossary provides users with a summary of available options, their data + * types, and descriptions, making it easier to understand the command-line + * interface. + * + * The formatted glossary is written to the specified file stream (`fp`). The + * format string allows you to control the layout and appearance of each + * glossary entry, enabling integration with custom help or documentation + * systems. + * + * Example usage: + * ``` + * // Print glossary to stdout with a custom format + * arg_print_glossary(stdout, argtable, " %-20s %s\n"); + * ``` + * + * @param fp Output file stream to write to (e.g., `stdout` or `stderr`). + * @param argtable Array of argument table structs describing the available + * options and arguments. + * @param format Format string controlling the layout of each glossary entry. + */ +ARG_EXTERN void arg_print_glossary(FILE* fp, void** argtable, const char* format); + +/** + * Prints the argument glossary in a customizable format to a dynamic string. + * + * The `arg_print_glossary_ds` function generates a glossary of command-line + * options and arguments, formatted according to the specified format string. + * This glossary provides users with a summary of available options, their data + * types, and descriptions, making it easier to understand the command-line + * interface. + * + * The formatted glossary is written to the specified dynamic string object + * (`arg_dstr_t`). The format string allows you to control the layout and + * appearance of each glossary entry, enabling integration with custom help or + * documentation systems. + * + * Example usage: + * ``` + * // Print glossary to a dynamic string with a custom format + * arg_dstr_t ds = arg_dstr_create(); + * arg_print_glossary_ds(ds, argtable, " %-20s %s\n"); + * printf("%s", arg_dstr_cstr(ds)); + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Dynamic string object to write to. + * @param argtable Array of argument table structs describing the available + * options and arguments. + * @param format Format string controlling the layout of each glossary entry. + */ +ARG_EXTERN void arg_print_glossary_ds(arg_dstr_t ds, void** argtable, const char* format); + +/** + * Prints the argument glossary using strict GNU formatting conventions to a file + * stream. + * + * The `arg_print_glossary_gnu` function generates a glossary of command-line + * options and arguments, formatted to comply with GNU style conventions. In this + * format, long options are vertically aligned in a second column, and lines are + * wrapped at 80 characters for improved readability and consistency with GNU + * command-line tool documentation. + * + * The formatted glossary is written to the specified file stream (`fp`). This + * function is useful for generating help output that matches the look and feel + * of standard GNU utilities. + * + * Example usage: + * ``` + * // Print GNU-style glossary to stdout + * arg_print_glossary_gnu(stdout, argtable); + * ``` + * + * @param fp Output file stream to write to (e.g., `stdout` or `stderr`). + * @param argtable Array of argument table structs describing the available + * options and arguments. + */ +ARG_EXTERN void arg_print_glossary_gnu(FILE* fp, void** argtable); + +/** + * Prints the argument glossary using strict GNU formatting conventions to a + * dynamic string. + * + * The `arg_print_glossary_gnu_ds` function generates a glossary of command-line + * options and arguments, formatted to comply with GNU style conventions. In + * this format, long options are vertically aligned in a second column, and + * lines are wrapped at 80 characters for improved readability and consistency + * with GNU command-line tool documentation. + * + * The formatted glossary is written to the specified dynamic string object + * (`arg_dstr_t`). This function is useful for generating help output that + * matches the look and feel of standard GNU utilities, especially when you need + * the output as a string for further processing, logging, or GUI display. + * + * Example usage: + * ``` + * // Print GNU-style glossary to a dynamic string + * arg_dstr_t ds = arg_dstr_create(); + * arg_print_glossary_gnu_ds(ds, argtable); + * printf("%s", arg_dstr_cstr(ds)); + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Dynamic string object to write to. + * @param argtable Array of argument table structs describing the available + * options and arguments. + */ +ARG_EXTERN void arg_print_glossary_gnu_ds(arg_dstr_t ds, void** argtable); + +/** + * Prints the details of all errors stored in the end data structure. + * + * The `arg_print_errors` function writes formatted error messages for all + * errors recorded in the specified `arg_end_t` structure to the given file + * stream (`fp`). The `progname` string is prepended to each error message, + * making it suitable for displaying or logging error output in command-line + * applications. + * + * This function is useful for reporting parsing errors to the user after + * calling `arg_parse`. It provides clear feedback about missing required + * arguments, invalid values, or other issues encountered during command-line + * parsing. + * + * Example usage: + * ``` + * arg_lit_t *help = arg_lit0("h", "help", "Display help"); + * arg_int_t *count = arg_int0("c", "count", "", "Number of times"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = {help, count, end}; + * + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors > 0) { + * arg_print_errors(stderr, end, argv[0]); + * } + * ``` + * + * @param fp Output file stream to write to (e.g., `stdout` or `stderr`). + * @param end Pointer to the `arg_end` structure containing error details. + * @param progname The name of the program to prepend to each error message. + * + * @see arg_parse, arg_print_errors_ds, arg_dstr_create, arg_dstr_cstr + */ +ARG_EXTERN void arg_print_errors(FILE* fp, arg_end_t* end, const char* progname); + +/** + * Prints the details of all errors stored in the end data structure to a dynamic + * string. + * + * The `arg_print_errors_ds` function writes formatted error messages for all + * errors recorded in the specified `arg_end_t` structure to the provided + * dynamic string object (`arg_dstr_t`). The `progname` string is prepended to + * each error message, making it suitable for displaying or logging error output + * in applications that use dynamic string buffers instead of standard output + * streams. + * + * This function is useful for applications that want to capture error messages + * for later display, logging, or integration with GUI or web interfaces. + * + * Example usage: + * ``` + * arg_dstr_t ds = arg_dstr_create(); + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors > 0) { + * arg_print_errors_ds(ds, end, argv[0]); + * fprintf(stderr, "%s", arg_dstr_cstr(ds)); + * } + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Pointer to the dynamic string object to which the error + * messages are written. + * @param end Pointer to the `arg_end` structure containing error details. + * @param progname The name of the program to prepend to each error message. + * + * @see arg_print_errors, arg_parse, arg_dstr_create, arg_dstr_cstr + */ +ARG_EXTERN void arg_print_errors_ds(arg_dstr_t ds, arg_end_t* end, const char* progname); + +/** + * Prints a formatted block of text with specified left and right margins. + * + * The `arg_print_formatted` function outputs the given text to the specified + * file stream (`fp`), arranging it in a column with the provided left and right + * margins. This is useful for generating neatly aligned help messages, + * glossaries, or any output where column formatting is desired. + * + * The function automatically wraps lines as needed to ensure that text does not + * exceed the specified right margin, and indents each line according to the + * left margin. + * + * Example usage: + * ``` + * const char* msg = "This is a long help message that will be wrapped and " + * "indented according to the specified margins."; + * arg_print_formatted(stdout, 4, 60, msg); + * ``` + * + * @param fp Output file stream to write to (e.g., `stdout` or `stderr`). + * @param lmargin Left margin (number of spaces to indent each line). + * @param rmargin Right margin (maximum line width). + * @param text Text to be printed and formatted. + */ +ARG_EXTERN void arg_print_formatted(FILE* fp, const unsigned lmargin, const unsigned rmargin, const char* text); + +/** + * Deallocates or frees all non-null entries in the argument table. + * + * The `arg_freetable` function iterates over the specified argument table array + * and frees any non-null entries, releasing the memory allocated for each + * argument structure. This is useful for cleaning up all argument objects + * created by `arg_` constructor functions after you are done parsing and + * processing command-line arguments. + * + * You should call this function once for each argument table array before your + * program exits to prevent memory leaks. + * + * Example usage: + * ``` + * arg_lit_t *help = arg_lit0("h", "help", "Display help"); + * arg_int_t *count = arg_int0("c", "count", "", "Number of times"); + * arg_end_t *end = arg_end(20); + * void *argtable[] = { help, count, end }; + * + * // ... use argtable ... + * + * arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); + * ``` + * + * @param argtable An array of pointers to argument table structs. + * @param n The number of structs in the argument table. + * + * @see arg_free + */ +ARG_EXTERN void arg_freetable(void** argtable, size_t n); + +/** + * Creates a new dynamic string object. + * + * The `arg_dstr_create` function allocates and initializes a new dynamic string + * object (`arg_dstr_t`). This object can be used to efficiently build, modify, + * and manage strings of arbitrary length, such as help messages, error + * messages, or logs. + * + * The dynamic string automatically grows as needed to accommodate additional + * content appended via functions like `arg_dstr_cat`, `arg_dstr_catc`, or + * `arg_dstr_catf`. When you are finished using the dynamic string, release its + * resources with `arg_dstr_destroy` or `arg_dstr_free`. + * + * Example usage: + * ``` + * arg_dstr_t ds = arg_dstr_create(); + * arg_dstr_cat(ds, "Hello, "); + * arg_dstr_cat(ds, "world!"); + * printf("%s\n", arg_dstr_cstr(ds)); // Output: Hello, world! + * arg_dstr_destroy(ds); + * ``` + * + * @return A handle to the newly created dynamic string object, or `NULL` if + * allocation fails. + * + * @see arg_dstr_destroy, arg_dstr_cat, arg_dstr_catc, arg_dstr_catf, + * arg_dstr_cstr + */ +ARG_EXTERN arg_dstr_t arg_dstr_create(void); + +/** + * Destroys a dynamic string object and releases its resources. + * + * The `arg_dstr_destroy` function frees all memory and resources associated + * with the specified dynamic string object (`arg_dstr_t`). After calling this + * function, the dynamic string handle becomes invalid and must not be used + * unless reinitialized with `arg_dstr_create`. + * + * This function should be called when you are finished using a dynamic string + * to prevent memory leaks and ensure proper cleanup. + * + * The difference between `arg_dstr_destroy` and `arg_dstr_free` is that + * `arg_dstr_destroy` both frees the memory and invalidates the handle, making + * it safe for typical use cases where you want to fully release the dynamic + * string. `arg_dstr_free` only releases the memory, but does not necessarily + * invalidate the handle, and is intended for advanced or custom memory + * management scenarios. For most applications, `arg_dstr_destroy` is the + * preferred function to use. + * + * Example usage: + * ``` + * arg_dstr_t ds = arg_dstr_create(); + * arg_dstr_cat(ds, "Temporary string"); + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Pointer to the dynamic string object to destroy. + * + * @see arg_dstr_create, arg_dstr_free, arg_dstr_reset, arg_dstr_set + */ +ARG_EXTERN void arg_dstr_destroy(arg_dstr_t ds); + +/** + * Resets the dynamic string object to an empty state. + * + * The `arg_dstr_reset` function clears the contents of the specified dynamic + * string object (`arg_dstr_t`), making it an empty string but retaining the + * allocated memory for future use. This is useful when you want to reuse a + * dynamic string buffer without reallocating memory, such as when building + * multiple messages in a loop. + * + * Any previously stored string data is discarded, and the dynamic string is + * ready to accept new content via `arg_dstr_cat`, `arg_dstr_catc`, or + * `arg_dstr_catf`. + * + * Example usage: + * ``` + * arg_dstr_t ds = arg_dstr_create(); + * arg_dstr_cat(ds, "First message"); + * printf("%s\n", arg_dstr_cstr(ds)); // Output: First message + * arg_dstr_reset(ds); + * arg_dstr_cat(ds, "Second message"); + * printf("%s\n", arg_dstr_cstr(ds)); // Output: Second message + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Pointer to the dynamic string object to reset. + * + * @see arg_dstr_create, arg_dstr_cat, arg_dstr_catc, arg_dstr_catf, + * arg_dstr_cstr, arg_dstr_destroy + */ +ARG_EXTERN void arg_dstr_reset(arg_dstr_t ds); + +/** + * Frees the memory associated with a dynamic string object. + * + * The `arg_dstr_free` function releases all memory and resources allocated for + * the specified dynamic string object (`arg_dstr_t`). After calling this + * function, the dynamic string handle becomes invalid and must not be used + * unless reinitialized. + * + * The difference between `arg_dstr_free` and `arg_dstr_destroy` is that + * `arg_dstr_free` only releases the memory, but does not necessarily invalidate + * the handle. This is intended for advanced or custom memory management + * scenarios. In contrast, `arg_dstr_destroy` both frees the memory and + * invalidates the handle, making it safer and preferred for typical use cases + * where you want to fully release the dynamic string. + * + * For most applications, use `arg_dstr_destroy` to ensure proper cleanup and + * avoid accidental use of an invalid handle. + * + * Example usage: + * ``` + * arg_dstr_t ds = arg_dstr_create(); + * arg_dstr_cat(ds, "Temporary string"); + * arg_dstr_free(ds); // Frees the memory associated with ds + * ``` + * + * @param ds Pointer to the dynamic string object to free. + * + * @see arg_dstr_create, arg_dstr_destroy, arg_dstr_reset, arg_dstr_set + */ +ARG_EXTERN void arg_dstr_free(arg_dstr_t ds); + +#define ARG_DSTR_STATIC ((arg_dstr_freefn*)0) +#define ARG_DSTR_VOLATILE ((arg_dstr_freefn*)1) +#define ARG_DSTR_DYNAMIC ((arg_dstr_freefn*)3) + +/** + * Sets the contents of the dynamic string object to a specified string. + * + * The `arg_dstr_set` function replaces the current contents of the dynamic + * string object (`arg_dstr_t`) with the provided string. You can also specify a + * custom free function to control how the memory for the string is managed. + * This is useful when you want to take ownership of an existing string buffer + * or integrate with custom memory management schemes. + * + * The `free_proc` parameter determines how the memory for the string will be + * released when the dynamic string is reset or destroyed. You can use one of + * the following standard macros: + * + * - `ARG_DSTR_STATIC`: Indicates that the string is statically allocated or + * should not be freed. Use this when the string is a string literal or + * managed elsewhere and does not need to be freed by Argtable3. + * - `ARG_DSTR_VOLATILE`: Indicates that the string is temporary and should not + * be freed. Use this when the string is only valid for the current scope or + * will be replaced soon, and you do not want Argtable3 to free it. + * - `ARG_DSTR_DYNAMIC`: Indicates that the string was dynamically allocated + * (e.g., with `malloc` or `strdup`) and should be freed by Argtable3. Use + * this when you want Argtable3 to take ownership and automatically free the + * memory when the dynamic string is reset or destroyed. + * + * If you provide a custom free function, it will be called to release the + * string when appropriate. + * + * Example usage: + * ``` + * arg_dstr_t ds = arg_dstr_create(); + * char* buf = strdup("Hello, Argtable!"); + * arg_dstr_set(ds, buf, ARG_DSTR_DYNAMIC); // ds takes ownership of buf + * printf("%s\n", arg_dstr_cstr(ds)); // Output: Hello, Argtable! + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Pointer to the dynamic string object. + * @param str Pointer to the string to set as the new content. + * @param free_proc Pointer to a function that will be used to free the string, + * or one of the standard macros (`ARG_DSTR_STATIC`, + * `ARG_DSTR_VOLATILE`, `ARG_DSTR_DYNAMIC`). + * + * @see arg_dstr_create, arg_dstr_cat, arg_dstr_cstr, arg_dstr_destroy + */ +ARG_EXTERN void arg_dstr_set(arg_dstr_t ds, char* str, arg_dstr_freefn* free_proc); + +/** + * Appends a string to the dynamic string object. + * + * The `arg_dstr_cat` function appends the specified null-terminated string to + * the end of the dynamic string object (`arg_dstr_t`). This is useful for + * building up complex strings incrementally, such as constructing help + * messages, error messages, or logs. + * + * The dynamic string automatically grows as needed to accommodate the + * additional content. + * + * Example usage: + * ``` + * arg_dstr_t ds = arg_dstr_create(); + * arg_dstr_cat(ds, "Hello, "); + * arg_dstr_cat(ds, "world!"); + * printf("%s\n", arg_dstr_cstr(ds)); // Output: Hello, world! + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Pointer to the dynamic string object. + * @param str Null-terminated string to append. + * + * @see arg_dstr_create, arg_dstr_catc, arg_dstr_catf, arg_dstr_cstr, + * arg_dstr_destroy + */ +ARG_EXTERN void arg_dstr_cat(arg_dstr_t ds, const char* str); + +/** + * Appends a single character to the dynamic string object. + * + * The `arg_dstr_catc` function appends the specified character to the end of + * the dynamic string object (`arg_dstr_t`). This is useful for building up + * strings character by character, such as when formatting output, constructing + * error messages, or processing input streams. + * + * The dynamic string automatically grows as needed to accommodate additional + * characters. + * + * Example usage: + * ``` + * arg_dstr_t ds = arg_dstr_create(); + * arg_dstr_catc(ds, 'A'); + * arg_dstr_catc(ds, 'B'); + * arg_dstr_catc(ds, 'C'); + * printf("%s\n", arg_dstr_cstr(ds)); // Output: ABC + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Pointer to the dynamic string object. + * @param c The character to append. + * + * @see arg_dstr_create, arg_dstr_cat, arg_dstr_catf, arg_dstr_cstr, + * arg_dstr_destroy + */ +ARG_EXTERN void arg_dstr_catc(arg_dstr_t ds, char c); + +/** + * Appends a formatted string to the dynamic string object. + * + * The `arg_dstr_catf` function appends a formatted string, generated using + * `printf`-style formatting, to the end of the specified dynamic string object + * (`arg_dstr_t`). This allows you to efficiently build up complex strings with + * variable content, such as error messages, help text, or logs. + * + * The function accepts a format string and a variable number of arguments, + * similar to `printf`. The resulting formatted string is concatenated to the + * current contents of the dynamic string. + * + * Example usage: + * ``` + * arg_dstr_t ds = arg_dstr_create(); + * arg_dstr_catf(ds, "Error: invalid value '%s' for option --%s\n", value, optname); + * printf("%s", arg_dstr_cstr(ds)); + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Pointer to the dynamic string object. + * @param fmt Format string (as in `printf`). + * @param ... Additional arguments to format. + * + * @see arg_dstr_create, arg_dstr_cat, arg_dstr_cstr, arg_dstr_destroy + */ +ARG_EXTERN void arg_dstr_catf(arg_dstr_t ds, const char* fmt, ...); + +/** + * Retrieves the null-terminated string from a dynamic string object. + * + * The `arg_dstr_cstr` function returns a pointer to the internal + * null-terminated character buffer managed by the dynamic string object + * (`arg_dstr_t`). This allows you to access the current contents of the dynamic + * string for printing, logging, or further processing. + * + * The returned pointer remains valid until the dynamic string is reset, + * modified, or destroyed. Do not modify or free the returned string directly; + * use the appropriate Argtable3 dynamic string functions for memory management. + * + * Example usage: + * ``` + * arg_dstr_t ds = arg_dstr_create(); + * arg_dstr_cat(ds, "Hello, "); + * arg_dstr_cat(ds, "world!"); + * printf("%s\n", arg_dstr_cstr(ds)); // Output: Hello, world! + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Dynamic string object. + * @return Pointer to the internal null-terminated string buffer. + * + * @see arg_dstr_create, arg_dstr_cat, arg_dstr_destroy + */ +ARG_EXTERN char* arg_dstr_cstr(arg_dstr_t ds); + +/** + * Initializes the sub-command mechanism. + * + * The `arg_cmd_init` function sets up the internal data structures required for + * sub-command support in Argtable3. It must be called before registering, + * dispatching, or iterating over sub-commands in your application. + * + * This function is typically called once at program startup, before any + * sub-commands are registered. It ensures that the sub-command API is ready for + * use. After initialization, you can use functions such as `arg_cmd_register`, + * `arg_cmd_dispatch`, and `arg_cmd_itr_create`. + * + * When sub-command support is no longer needed (e.g., at program shutdown), + * call `arg_cmd_uninit` to release resources and prevent memory leaks. + * + * Example usage: + * ``` + * arg_cmd_init(); + * // Register and use sub-commands... + * arg_cmd_uninit(); + * ``` + * + * @see arg_cmd_uninit, arg_cmd_register, arg_cmd_unregister, arg_cmd_count + */ +ARG_EXTERN void arg_cmd_init(void); + +/** + * Releases resources and cleans up the sub-command mechanism. + * + * The `arg_cmd_uninit` function deinitializes the sub-command infrastructure, + * freeing any memory or resources allocated for sub-command registration, + * lookup, and iteration. After calling this function, all registered + * sub-commands are removed, and the sub-command API can no longer be used until + * `arg_cmd_init` is called again. + * + * This function should be called at program shutdown or when you no longer need + * sub-command support, to prevent memory leaks and ensure proper cleanup. + * + * Example usage: + * ``` + * arg_cmd_init(); + * // Register and use sub-commands... + * arg_cmd_uninit(); + * ``` + * + * @see arg_cmd_init, arg_cmd_register, arg_cmd_unregister, arg_cmd_count + */ +ARG_EXTERN void arg_cmd_uninit(void); + +/** + * Registers a new sub-command with the application. + * + * The `arg_cmd_register` function adds a sub-command to the application's + * sub-command table, associating it with a handler function, a description, and + * an optional context pointer. This enables applications to support multiple + * commands (such as `git` or `docker`-style interfaces), where each sub-command + * can have its own logic and help text. + * + * The handler function (`proc`) will be called when the sub-command is + * dispatched via `arg_cmd_dispatch`. The description is used in help and usage + * messages. The context pointer (`ctx`) can be used to pass user-defined data + * to the handler. + * + * If a sub-command with the same name already exists, its registration will be + * replaced with the new handler, description, and context. + * + * Example usage: + * ``` + * // Register a "list" sub-command + * arg_cmd_register("list", list_cmd, "List all items", NULL); + * + * // Register a "remove" sub-command with context + * arg_cmd_register("remove", remove_cmd, "Remove an item", my_context_ptr); + * ``` + * + * @param name The name of the sub-command (null-terminated string). + * @param proc Pointer to the handler function for the sub-command. + * @param description A short description of the sub-command for help output. + * @param ctx Optional user-defined context pointer (may be NULL). + * + * @see arg_cmd_unregister, arg_cmd_dispatch, arg_cmd_info, arg_cmd_count + */ +ARG_EXTERN void arg_cmd_register(const char* name, arg_cmdfn proc, const char* description, void* ctx); + +/** + * Unregisters a sub-command by name. + * + * The `arg_cmd_unregister` function removes a previously registered sub-command + * from the application's sub-command table. After calling this function, the + * specified sub-command will no longer be available for dispatch, iteration, or + * help output. + * + * This function is useful for applications that support dynamic registration + * and removal of sub-commands at runtime, such as plugin-based tools or + * interactive shells. + * + * If the sub-command with the given name does not exist, the function has no + * effect. + * + * Example usage: + * ``` + * arg_cmd_register("remove", remove_cmd, "Remove an item", NULL); + * // ... later ... + * arg_cmd_unregister("remove"); + * ``` + * + * @param name The name of the sub-command to unregister (null-terminated + * string). + * + * @see arg_cmd_register, arg_cmd_dispatch, arg_cmd_count, arg_cmd_info + */ +ARG_EXTERN void arg_cmd_unregister(const char* name); + +/** + * Dispatches a registered sub-command by name. + * + * The `arg_cmd_dispatch` function locates the sub-command with the specified + * name and invokes its handler function, passing the provided command-line + * arguments and a dynamic string buffer for output or error messages. + * + * This function is typically used in applications that support multiple + * sub-commands (such as `git` or `docker`-style interfaces), allowing you to + * delegate command-line processing to the appropriate handler based on the + * user's input. + * + * If the sub-command is found, its handler function is called with the given + * arguments and context. If the sub-command is not found, an error message may + * be written to the result buffer, and a nonzero error code is returned. + * + * Example usage: + * ``` + * // Register sub-commands + * arg_cmd_register("list", list_cmd, "List items", NULL); + * arg_cmd_register("add", add_cmd, "Add an item", NULL); + * + * // Dispatch based on argv[1] + * arg_dstr_t res = arg_dstr_create(); + * int ret = arg_cmd_dispatch(argv[1], argc - 1, argv + 1, res); + * if (ret != 0) { + * fprintf(stderr, "%s\n", arg_dstr_cstr(res)); + * } + * arg_dstr_destroy(res); + * ``` + * + * @param name The name of the sub-command to dispatch (null-terminated string). + * @param argc The number of command-line arguments for the sub-command. + * @param argv The array of command-line arguments for the sub-command. + * @param res Pointer to a dynamic string buffer for output or error messages. + * + * @return 0 if the sub-command was found and executed successfully, nonzero if + * the sub-command was not found or an error occurred. + * + * @see arg_cmd_register, arg_cmd_info, arg_cmd_count, arg_dstr_create, + * arg_dstr_cstr + */ +ARG_EXTERN int arg_cmd_dispatch(const char* name, int argc, char* argv[], arg_dstr_t res); + +/** + * Returns the number of registered sub-commands. + * + * The `arg_cmd_count` function returns the total number of sub-commands + * currently registered in the application. This is useful for applications that + * support multiple commands (such as `git` or `docker`-style interfaces) and + * need to enumerate, display, or manage the available sub-commands. + * + * You can use this function to determine the size of the sub-command table, + * iterate over all registered sub-commands, or display a summary of available + * commands to the user. + * + * Example usage: + * ``` + * unsigned int count = arg_cmd_count(); + * printf("There are %u sub-commands registered.\n", count); + * ``` + * + * @return The number of sub-commands currently registered. + * + * @see arg_cmd_register, arg_cmd_info, arg_cmd_itr_create + */ +ARG_EXTERN unsigned int arg_cmd_count(void); + +/** + * Retrieves information about a registered sub-command by name. + * + * The `arg_cmd_info` function returns a pointer to the `arg_cmd_info_t` + * structure for the sub-command with the specified name. This structure + * contains metadata such as the sub-command's name, description, handler + * function, and context pointer. + * + * This function is useful for querying details about a specific sub-command, + * such as when generating help output, dispatching commands, or inspecting + * available sub-commands in applications that support multiple commands (e.g., + * `git` or `docker`-style interfaces). + * + * If the sub-command is not found, the function returns `NULL`. + * + * Example usage: + * ``` + * arg_cmd_info_t* info = arg_cmd_info("list"); + * if (info) { + * printf("Sub-command: %s - %s\n", info->name, info->description); + * } + * ``` + * + * @param name The name of the sub-command to look up (null-terminated string). + * @return Pointer to the `arg_cmd_info_t` structure for the sub-command, or + * `NULL` if the sub-command is not found. + * + * @see arg_cmd_register, arg_cmd_count, arg_cmd_itr_create, arg_cmd_info_t + */ +ARG_EXTERN arg_cmd_info_t* arg_cmd_info(const char* name); + +/** + * Creates a new sub-command iterator for traversing registered sub-commands. + * + * The `arg_cmd_itr_create` function allocates and initializes a sub-command + * iterator, which can be used to traverse all registered sub-commands in the + * application. This iterator provides a convenient way to enumerate, search, or + * process sub-commands, especially in applications that support multiple + * commands (such as `git` or `docker`-style interfaces). + * + * After creating the iterator, you can use functions like `arg_cmd_itr_advance` + * to move through the sub-command table, and `arg_cmd_itr_key` or + * `arg_cmd_itr_value` to access the current sub-command's name or metadata. + * When finished, call `arg_cmd_itr_destroy` to release resources. + * + * Example usage: + * ``` + * arg_cmd_itr_t itr = arg_cmd_itr_create(); + * while (arg_cmd_itr_advance(itr)) { + * const char* key = arg_cmd_itr_key(itr); + * printf("Sub-command: %s\n", key); + * } + * arg_cmd_itr_destroy(itr); + * ``` + * + * @return A handle to the newly created sub-command iterator, or `NULL` if + * allocation fails. + * + * @see arg_cmd_itr_destroy, arg_cmd_itr_advance, arg_cmd_itr_key, + * arg_cmd_itr_value + */ +ARG_EXTERN arg_cmd_itr_t arg_cmd_itr_create(void); + +/** + * Destroys the sub-command iterator and releases associated resources. + * + * The `arg_cmd_itr_destroy` function deallocates any memory or resources + * associated with a sub-command iterator created by `arg_cmd_itr_create`. After + * calling this function, the iterator is no longer valid and must not be used. + * + * This function should be called when you are finished iterating over + * sub-commands to prevent memory leaks and ensure proper cleanup. + * + * Example usage: + * ``` + * arg_cmd_itr_t itr = arg_cmd_itr_create(); + * while (arg_cmd_itr_advance(itr)) { + * // process sub-commands + * } + * arg_cmd_itr_destroy(itr); + * ``` + * + * @param itr The sub-command iterator to destroy. + * + * @see arg_cmd_itr_create, arg_cmd_itr_advance, arg_cmd_itr_key, + * arg_cmd_itr_value + */ +ARG_EXTERN void arg_cmd_itr_destroy(arg_cmd_itr_t itr); + +/** + * Advances the sub-command iterator to the next entry. + * + * The `arg_cmd_itr_advance` function moves the sub-command iterator to the next + * sub-command in the table. This allows you to iterate over all registered + * sub-commands in your application, enabling tasks such as listing available + * commands, generating help output, or performing batch operations. + * + * This function is typically used in a loop, where you repeatedly call + * `arg_cmd_itr_advance` and retrieve the current sub-command's key or value + * using `arg_cmd_itr_key` or `arg_cmd_itr_value`. + * + * Example usage: + * ``` + * arg_cmd_itr_t itr = arg_cmd_itr_create(); + * while (arg_cmd_itr_advance(itr)) { + * const char* key = arg_cmd_itr_key(itr); + * printf("Sub-command: %s\n", key); + * } + * arg_cmd_itr_destroy(itr); + * ``` + * + * @param itr The sub-command iterator. + * @return 1 if the iterator was advanced to a valid entry, 0 if there are no + * more entries (end of the sub-command table). + * + * @see arg_cmd_itr_create, arg_cmd_itr_key, arg_cmd_itr_value, arg_cmd_info_t + */ +ARG_EXTERN int arg_cmd_itr_advance(arg_cmd_itr_t itr); + +/** + * Retrieves the key (name) of the sub-command at the current iterator position. + * + * The `arg_cmd_itr_key` function returns a pointer to the key (typically the + * sub-command name as a null-terminated string) at the current position of the + * sub-command iterator. This allows you to access the identifier for the + * sub-command currently referenced by the iterator, which is useful for + * displaying, comparing, or processing sub-commands in applications that + * support multiple commands. + * + * This function is typically used when iterating over all registered + * sub-commands or after searching for a specific sub-command using the + * iterator. + * + * Example usage: + * ``` + * arg_cmd_itr_t itr = arg_cmd_itr_create(); + * while (arg_cmd_itr_advance(itr)) { + * const char* key = arg_cmd_itr_key(itr); + * printf("Sub-command: %s\n", key); + * } + * arg_cmd_itr_destroy(itr); + * ``` + * + * @param itr The sub-command iterator. + * @return Pointer to the key (sub-command name) at the current iterator + * position, or `NULL` if the iterator is not valid or at the end. + * + * @see arg_cmd_itr_create, arg_cmd_itr_advance, arg_cmd_itr_value, + * arg_cmd_info_t + */ +ARG_EXTERN char* arg_cmd_itr_key(arg_cmd_itr_t itr); + +/** + * Retrieves the value (sub-command information) at the current iterator + * position. + * + * The `arg_cmd_itr_value` function returns a pointer to the `arg_cmd_info_t` + * structure at the current position of the sub-command iterator. This allows + * you to access metadata and handler information for the sub-command found or + * iterated to by the iterator. + * + * This function is typically used after advancing the iterator or searching for + * a specific sub-command, enabling you to inspect the sub-command's name, + * description, handler function, and context pointer. + * + * Example usage: + * ``` + * arg_cmd_itr_t itr = arg_cmd_itr_create(); + * if (arg_cmd_itr_search(itr, "list")) { + * arg_cmd_info_t* info = arg_cmd_itr_value(itr); + * printf("Found sub-command: %s - %s\n", info->name, info->description); + * } + * arg_cmd_itr_destroy(itr); + * ``` + * + * @param itr The sub-command iterator. + * @return Pointer to the `arg_cmd_info_t` structure at the current iterator + * position, or `NULL` if the iterator is not valid or at the end. + * + * @see arg_cmd_itr_create, arg_cmd_itr_advance, arg_cmd_itr_search, + * arg_cmd_info_t + */ +ARG_EXTERN arg_cmd_info_t* arg_cmd_itr_value(arg_cmd_itr_t itr); + +/** + * Searches for a sub-command by key using the sub-command iterator. + * + * The `arg_cmd_itr_search` function searches the sub-command table for a + * sub-command whose key matches the specified value, starting from the current + * position of the iterator. If a match is found, the iterator is positioned at + * the found entry. + * + * This function is useful for efficiently locating a specific sub-command in + * applications that support multiple commands (such as `git` or `docker`-style + * interfaces), especially when iterating over or managing a dynamic set of + * sub-commands. + * + * Example usage: + * ``` + * arg_cmd_itr_t itr = arg_cmd_itr_create(); + * if (arg_cmd_itr_search(itr, "list")) { + * arg_cmd_info_t* info = arg_cmd_itr_value(itr); + * printf("Found sub-command: %s - %s\n", info->name, info->description); + * } + * arg_cmd_itr_destroy(itr); + * ``` + * + * @param itr The sub-command iterator. + * @param k The key to search for (typically a string with the sub-command + * name). + * @return 1 if the key is found and the iterator is positioned at the entry, + * 0 otherwise. + * + * @see arg_cmd_itr_create, arg_cmd_itr_value, arg_cmd_info_t + */ +ARG_EXTERN int arg_cmd_itr_search(arg_cmd_itr_t itr, void* k); + +/** + * Sorts an array using a custom comparison function. + * + * The `arg_mgsort` function performs a merge sort on the specified array, + * allowing you to sort elements of any type using a user-provided comparison + * function. This is useful for sorting sub-command tables, argument arrays, or + * any other data structures used within Argtable3 or your application. + * + * The function is flexible and can sort arrays of arbitrary element size. The + * comparison function should return an integer less than, equal to, or greater + * than zero if the first argument is considered to be respectively less than, + * equal to, or greater than the second. + * + * Example usage: + * ``` + * // Sort an array of sub-command info structures by name + * arg_mgsort(cmd_array, cmd_count, sizeof(arg_cmd_info_t), 0, cmd_count - 1, compare_cmd_info); + * ``` + * + * @param data Pointer to the array to be sorted. + * @param size Number of elements in the array. + * @param esize Size of each element in bytes. + * @param i Starting index of the range to sort (typically 0). + * @param k Ending index of the range to sort (typically size - 1). + * @param comparefn Pointer to a comparison function that takes two `const + * void*` arguments and returns an int (like `strcmp` or + * `memcmp`). + * + * @see arg_cmd_info_t, arg_cmd_itr_t + */ +ARG_EXTERN void arg_mgsort(void* data, int size, int esize, int i, int k, arg_comparefn* comparefn); + +/** + * Generates and retrieves the default help message for the application. + * + * The `arg_make_get_help_msg` function constructs a standard help message + * describing the usage, options, and arguments for the main application or + * module. The generated help text is written to a dynamic string buffer, which + * can be displayed to the user, printed to the console, or included in + * documentation. + * + * This function is typically used to provide users with a quick reference to + * the application's command-line interface, especially when no specific command + * or argument table is provided. It is useful for displaying help output in + * response to `--help` or similar flags. + * + * The help message typically includes the application name and its usage + * syntax, a glossary of available options and arguments with descriptions, and + * any additional remarks or formatting defined in the argument table. + * + * Example usage: + * ``` + * arg_dstr_t ds = arg_dstr_create(); + * arg_make_get_help_msg(ds); + * printf("%s", arg_dstr_cstr(ds)); + * arg_dstr_destroy(ds); + * ``` + * + * @param res Dynamic string handle to store the generated help message. + * + * @see arg_make_help_msg, arg_dstr_create, arg_dstr_cstr + */ +ARG_EXTERN void arg_make_get_help_msg(arg_dstr_t res); + +/** + * Generates a formatted help message for the command-line interface. + * + * The `arg_make_help_msg` function constructs a comprehensive help message + * describing the usage, options, and arguments for a command-line application + * or sub-command. The generated help text is written to a dynamic string + * buffer, which can be displayed to the user, printed to the console, or + * included in documentation. + * + * The help message typically includes the command or sub-command name and its + * usage syntax, a glossary of available options and arguments with descriptions, + * and any additional formatting or custom remarks defined in the argument table. + * + * This function is useful for providing users with clear guidance on how to + * invoke the application and what options are available. It is commonly called + * when the user requests help (e.g., with `-h` or `--help`). + * + * Example usage: + * ``` + * arg_dstr_t ds = arg_dstr_create(); + * arg_make_help_msg(ds, "myapp", argtable); + * printf("%s", arg_dstr_cstr(ds)); + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Dynamic string to store the generated help message. + * @param cmd_name Name of the command or sub-command to display in the usage + * line. + * @param argtable Array of argument table structs describing the available + * options and arguments. + * + * @see arg_dstr_create, arg_dstr_cstr, arg_rem, arg_print_glossary + */ +ARG_EXTERN void arg_make_help_msg(arg_dstr_t ds, const char* cmd_name, void** argtable); + +/** + * Generates a concise syntax error message for command-line parsing errors. + * + * The `arg_make_syntax_err_msg` function constructs a brief error message + * summarizing the syntax errors detected during argument parsing. The message + * is written to a dynamic string buffer, which can then be displayed to the + * user or logged for diagnostics. This function is useful for applications that + * want to provide immediate feedback about what went wrong, without including + * full usage or help information. + * + * The generated message typically includes a summary of the errors encountered + * and the relevant arguments or options that caused the error. + * + * For a more comprehensive help message that includes usage and glossary + * information, use `arg_make_syntax_err_help_msg`. + * + * Example usage: + * ``` + * arg_dstr_t ds = arg_dstr_create(); + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors > 0) { + * arg_make_syntax_err_msg(ds, argtable, end); + * fprintf(stderr, "%s", arg_dstr_cstr(ds)); + * } + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Pointer to a dynamic string object to store the generated + * message. + * @param argtable An array of argument table structs describing the expected + * arguments. + * @param end Pointer to the `arg_end` structure containing error details. + * + * @see arg_make_syntax_err_help_msg, arg_parse, arg_print_errors, + * arg_dstr_create, arg_dstr_cstr + */ +ARG_EXTERN void arg_make_syntax_err_msg(arg_dstr_t ds, void** argtable, arg_end_t* end); + +/** + * Generates a detailed syntax error help message for command-line parsing errors. + * + * The `arg_make_syntax_err_help_msg` function constructs a comprehensive help + * message when syntax errors are detected during argument parsing. It combines + * error details, usage information, and optional help text into a dynamic string + * buffer, which can then be displayed to the user or logged for diagnostics. + * + * This function is typically used in applications that want to provide users + * with clear feedback about what went wrong, what the correct syntax is, and + * how to get further help. It is especially useful for CLI tools that need to + * guide users through complex argument requirements. + * + * The generated message may include the command name and a summary of the + * errors, the correct usage syntax for the command, a glossary of available + * options and arguments, and additional help text if the help flag is set. + * + * Example usage: + * ``` + * arg_dstr_t ds = arg_dstr_create(); + * int exitcode = 0; + * int nerrors = arg_parse(argc, argv, argtable); + * if (nerrors > 0) { + * arg_make_syntax_err_help_msg(ds, argv[0], 0, nerrors, argtable, end, + * &exitcode); + * fprintf(stderr, "%s", arg_dstr_cstr(ds)); + * } + * arg_dstr_destroy(ds); + * ``` + * + * @param ds Pointer to a dynamic string object to store the generated + * message. + * @param name The name of the command or application. + * @param help Nonzero if the help flag was specified; zero otherwise. + * @param nerrors The number of syntax errors detected during parsing. + * @param argtable An array of argument table structs describing the expected + * arguments. + * @param end Pointer to the `arg_end` structure containing error details. + * @param exitcode Pointer to an integer where the recommended exit code will be + * stored. + * + * @return Returns 0 on success, or a nonzero error code on failure. + * + * @see arg_parse, arg_print_errors, arg_dstr_create, arg_dstr_cstr + */ +ARG_EXTERN int arg_make_syntax_err_help_msg(arg_dstr_t ds, const char* name, int help, int nerrors, void** argtable, arg_end_t* end, int* exitcode); + +/** + * Sets the module (application) name. + * + * The `arg_set_module_name` function allows you to specify the name of your + * application or module. This name can be displayed in help messages, version + * output, and error messages generated by Argtable3. It is typically called at + * program startup, before parsing command-line arguments, to ensure that the + * module name is available for reporting to the user. + * + * Setting a meaningful module name helps users identify the application in + * command-line output and documentation, especially when distributing binaries + * or providing support. + * + * Example usage: + * ``` + * arg_set_module_name("myapp"); + * ``` + * + * @param name The module or application name as a null-terminated string. Pass + * a descriptive name that will be shown in help and version output. + */ +ARG_EXTERN void arg_set_module_name(const char* name); + +/** + * Sets the module (application) version information. + * + * The `arg_set_module_version` function allows you to specify the version + * information for your application or module, which can be displayed in help or + * version output. This function is typically called at program startup, before + * parsing command-line arguments, to ensure that version information is + * available for reporting to the user. + * + * The version is specified using three integer components (major, minor, patch) + * and an optional string tag (such as a commit hash or build identifier). This + * enables you to provide detailed versioning information, which is useful for + * debugging, support, and user reference. + * + * Example usage: + * ``` + * arg_set_module_version(3, 1, 5, "githash-abc123"); + * ``` + * + * @param[in] major The major version number (e.g., 3 in version 3.1.5). + * @param[in] minor The minor version number (e.g., 1 in version 3.1.5). + * @param[in] patch The patch version number (e.g., 5 in version 3.1.5). + * @param[in] tag An optional string identifying a version control commit, + * build tag, or other metadata. Pass `NULL` if not needed. + */ +ARG_EXTERN void arg_set_module_version(int major, int minor, int patch, const char* tag); + +/**** deprecated functions, for back-compatibility only ********/ + +/** + * Deallocates or frees non-null entries of the argument table. + * + * The `arg_free` function is deprecated in favour of the `arg_freetable` + * function due to a flaw in its design. The flaw results in memory leak in the + * (very rare) case that an intermediate entry in the argtable array failed its + * memory allocation while others following that entry were still allocated ok. + * Those subsequent allocations will not be deallocated by `arg_free`. + * + * Despite the unlikeliness of the problem occurring, and the even unlikelier + * event that it has any deliterious effect, it is fixed regardless by replacing + * `arg_free` with the newer `arg_freetable` function. We still keep `arg_free` + * for backwards compatibility. + * + * @param argtable An array of argument table structs. + * @deprecated Use `arg_freetable` instead. + */ +ARG_EXTERN void arg_free(void** argtable); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/argtable3_private.h b/src/argtable3_private.h index 1d48592..3a98d66 100644 --- a/src/argtable3_private.h +++ b/src/argtable3_private.h @@ -35,8 +35,25 @@ #include +#ifndef ARG_ENABLE_TRACE #define ARG_ENABLE_TRACE 0 +#endif /* ARG_ENABLE_TRACE */ + +#ifndef ARG_ENABLE_LOG #define ARG_ENABLE_LOG 1 +#endif /* ARG_ENABLE_LOG */ + +/* Use the embedded getopt as the system getopt(3) */ +#ifndef ARG_REPLACE_GETOPT +#define ARG_REPLACE_GETOPT 1 +#endif /* ARG_REPLACE_GETOPT */ + +/* Size of the buffer pre-allocated for dynamic strings. + * If the length exceeds this size, the buffer will be dynamically allocated. + */ +#ifndef ARG_DSTR_SIZE +#define ARG_DSTR_SIZE 200 +#endif /* ARG_DSTR_SIZE */ #ifdef __cplusplus extern "C" { @@ -81,10 +98,10 @@ typedef void(arg_panicfn)(const char* fmt, ...); * They can be a problem for the platforms like NuttX, where * the namespace is flat for everything including apps and libraries. */ -#define xmalloc argtable3_xmalloc -#define xcalloc argtable3_xcalloc -#define xrealloc argtable3_xrealloc -#define xfree argtable3_xfree +#define xmalloc malloc +#define xcalloc calloc +#define xrealloc realloc +#define xfree free extern void dbg_printf(const char* fmt, ...); extern void arg_set_panic(arg_panicfn* proc); diff --git a/src/chacha20_drng.c b/src/chacha20_drng.c index 3c46706..dc3b659 100644 --- a/src/chacha20_drng.c +++ b/src/chacha20_drng.c @@ -17,22 +17,17 @@ * DAMAGE. */ +#define _GNU_SOURCE #include +#include #include #include #include #include #include - -#ifdef _WIN32 -#include -#else #include -#endif - #include "chacha20_drng.h" -#include "randombytes.h" #define MAJVERSION 1 /* API / ABI incompatible changes, * functional changes that require consumer @@ -58,9 +53,7 @@ /*********************************** Helper ***********************************/ -#ifndef _WIN32 #define min(x, y) ((x < y) ? x : y) -#endif #define __aligned(x) __attribute__((aligned(x))) static inline void memset_secure(void *s, int c, uint32_t n) @@ -71,23 +64,14 @@ static inline void memset_secure(void *s, int c, uint32_t n) static inline void get_time(time_t *sec, uint32_t *nsec) { -#ifdef _WIN32 - SYSTEMTIME SystemTime; - GetSystemTime(&SystemTime); - if(sec) - *sec = SystemTime.wSecond; - if(nsec) - *nsec = SystemTime.wMilliseconds; -#else struct timespec time; + if (clock_gettime(CLOCK_REALTIME, &time) == 0) { if (sec) *sec = time.tv_sec; if (nsec) *nsec = time.tv_nsec; } -#endif - } static inline uint32_t rol32(uint32_t x, int n) @@ -95,25 +79,36 @@ static inline uint32_t rol32(uint32_t x, int n) return ( (x << (n&(32-1))) | (x >> ((32-n)&(32-1))) ); } - /* Endian dependent byte swap operations. */ #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ -/* Byte swap for 32-bit and 64-bit integers. */ +# define le_bswap32(x) _bswap32(x) static inline uint32_t ror32(uint32_t x, int n) { return ( (x >> (n&(32-1))) | (x << ((32-n)&(32-1))) ); } + +/* Byte swap for 32-bit and 64-bit integers. */ static inline uint32_t _bswap32(uint32_t x) { return ((rol32(x, 8) & 0x00ff00ffL) | (ror32(x, 8) & 0xff00ff00L)); } -# define le_bswap32(x) _bswap32(x) #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ # define le_bswap32(x) ((uint32_t)(x)) #else #error "Endianess not defined" #endif +static inline void drng_chacha20_bswap32(uint32_t *ptr, uint32_t words) +{ + uint32_t i; + + /* Byte-swap data which is an LE representation */ + for (i = 0; i < words; i++) { + *ptr = le_bswap32(*ptr); + ptr++; + } +} + /******************************* ChaCha20 Block *******************************/ #define CHACHA20_KEY_SIZE 32 @@ -203,6 +198,7 @@ static inline int drng_chacha20_selftest_one(struct chacha20_state *state, uint32_t result[CHACHA20_BLOCK_SIZE_WORDS]; chacha20_block(&state->constants[0], result); + return memcmp(expected, result, CHACHA20_BLOCK_SIZE); } @@ -230,24 +226,186 @@ static int drng_chacha20_selftest(void) expected[12] = 0xd19c12b5; expected[13] = 0xb94e16de; expected[14] = 0xe883d0cb; expected[15] = 0x4e3c50a2; + drng_chacha20_bswap32(expected, CHACHA20_BLOCK_SIZE_WORDS); + return drng_chacha20_selftest_one(&chacha20, &expected[0]); } +/********************* getrandom system call seed source *********************/ +#ifdef GETRANDOM + +#include +static int drng_getrandom_get(uint8_t *buf, uint32_t buflen) +{ + uint32_t len = 0; + ssize_t ret; + + if (buflen > INT_MAX) + return 0; + + do { + ret = syscall(__NR_getrandom, (buf + len), (buflen - len), 0); + if (0 < ret) + len += ret; + } while ((0 < ret || EINTR == errno || ERESTART == errno) + && buflen > len); + + return len; +} + +#else +static int drng_getrandom_get(uint8_t *buf, uint32_t buflen) +{ + (void)buf; + (void)buflen; + + return 0; +} + +#endif + +/*************************** Jitter RNG seed source ***************************/ +#ifdef JENT + +#include "jitterentropy.h" + +struct jent_noise_source { + struct rand_data *ec; + int initialized; +}; + +static struct jent_noise_source jent_noise_source = { + NULL, + 0, +}; + +static int drng_jent_alloc() +{ + int ret = jent_entropy_init(); + + if (ret) { + jent_noise_source.initialized = -1; + return -EFAULT; + } + + jent_noise_source.ec = jent_entropy_collector_alloc(0, 0); + if (!jent_noise_source.ec) + return -ENOMEM; + + return 0; +} + +static void drng_jent_dealloc(void) +{ + if (jent_noise_source.initialized != 1) + return; + + jent_entropy_collector_free(jent_noise_source.ec); + jent_noise_source.ec = NULL; + jent_noise_source.initialized = 0; +} + +static int drng_jent_get(uint8_t *buf, uint32_t buflen) +{ + if (!jent_noise_source.initialized) { + int ret = drng_jent_alloc(); + + if (ret) + return ret; + + jent_noise_source.initialized = 1; + } + + if (jent_noise_source.initialized > 0) + return jent_read_entropy(jent_noise_source.ec, + (char *)buf, buflen); + + return 0; +} + +#else +static int drng_jent_get(uint8_t *buf, uint32_t buflen) +{ + (void)buf; + (void)buflen; + + return 0; +} + +static void drng_jent_dealloc(void) +{ + return; +} +#endif + +/************************** /dev/random seed source **************************/ +#ifdef DEVRANDOM + #include #include #include #include +static int random_fd = -1; + +static int drng_random_alloc(void) +{ + random_fd = open("/dev/random", O_RDONLY|O_CLOEXEC); + if (0 > random_fd) + return -EBADFD; + + return 0; +} + static int drng_random_get(uint8_t *buf, uint32_t buflen) { - int ret = randombytes(buf, buflen); - if( ret != 0) { - return 0; - } else { - return buflen; - } + uint32_t len = 0; + ssize_t ret; + + if (random_fd == -1) { + int ret = drng_random_alloc(); + + if (ret) + return ret; + } + + if (buflen > INT_MAX) + return 0; + + do { + ret = read(random_fd, (buf + len), (buflen - len)); + if (0 < ret) + len += ret; + } while ((0 < ret || EINTR == errno || ERESTART == errno) + && buflen > len); + + return len; } +static void drng_random_dealloc(void) +{ + if (random_fd < 0) + return; + + close(random_fd); + random_fd = -1; +} + +#else +static int drng_random_get(uint8_t *buf, uint32_t buflen) +{ + (void)buf; + (void)buflen; + + return 0; +} + +static void drng_random_dealloc(void) +{ + return; +} +#endif + /******************************* ChaCha20 DRNG *******************************/ struct chacha20_drng { @@ -267,22 +425,23 @@ static inline void drng_chacha20_update(struct chacha20_state *chacha20, { uint32_t i, tmp[CHACHA20_BLOCK_SIZE_WORDS]; - if (used_words > CHACHA20_KEY_SIZE_WORDS) { + if (CHACHA20_BLOCK_SIZE_WORDS - used_words < CHACHA20_KEY_SIZE_WORDS) { chacha20_block(&chacha20->constants[0], tmp); for (i = 0; i < CHACHA20_KEY_SIZE_WORDS; i++) - chacha20->key.u[i] ^= tmp[i]; + chacha20->key.u[i] ^= le_bswap32(tmp[i]); memset_secure(tmp, 0, sizeof(tmp)); } else { for (i = 0; i < CHACHA20_KEY_SIZE_WORDS; i++) - chacha20->key.u[i] ^= buf[i + used_words]; + chacha20->key.u[i] ^= le_bswap32(buf[i + used_words]); } /* Deterministic increment of nonce as required in RFC 7539 chapter 4 */ chacha20->nonce[0]++; - if (chacha20->nonce[0] == 0) + if (chacha20->nonce[0] == 0){ chacha20->nonce[1]++; - if (chacha20->nonce[1] == 0) - chacha20->nonce[2]++; + if (chacha20->nonce[1] == 0) + chacha20->nonce[2]++; + } /* Leave counter untouched as it is start value is undefined in RFC */ } @@ -338,7 +497,7 @@ static int drng_chacha20_generate(struct chacha20_state *chacha20, int zeroize_buf = 0; while (outbuflen >= CHACHA20_BLOCK_SIZE) { - if ((uintptr_t)outbuf & (sizeof(aligned_buf[0]) - 1)) { + if ((unsigned long)outbuf & (sizeof(aligned_buf[0]) - 1)) { chacha20_block(&chacha20->constants[0], aligned_buf); memcpy(outbuf, aligned_buf, CHACHA20_BLOCK_SIZE); zeroize_buf = 1; @@ -388,7 +547,7 @@ static int drng_chacha20_rng_selftest(struct chacha20_drng *drng) * * remaining state is 0 * and pulling one ChaCha20 DRNG block. */ - uint8_t expected_block[CHACHA20_KEY_SIZE] = { + static const uint8_t expected_block[CHACHA20_KEY_SIZE] = { 0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90, 0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28, 0xbd, 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a, @@ -409,15 +568,15 @@ static int drng_chacha20_rng_selftest(struct chacha20_drng *drng) * 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f * and pulling two ChaCha20 DRNG blocks. */ - uint8_t expected_twoblocks[CHACHA20_KEY_SIZE * 2] = { - 0xf5, 0xb4, 0xb6, 0x5a, 0xec, 0xcd, 0x5a, 0x65, - 0x87, 0x56, 0xe3, 0x86, 0x51, 0x54, 0xfc, 0x90, - 0x56, 0xff, 0x5e, 0xae, 0x58, 0xf2, 0x01, 0x88, - 0xb1, 0x7e, 0xb8, 0x2e, 0x17, 0x9a, 0x27, 0xe6, - 0x86, 0xb3, 0xed, 0x33, 0xf7, 0xb9, 0x06, 0x05, - 0x8a, 0x2d, 0x1a, 0x93, 0xc9, 0x0b, 0x80, 0x04, - 0x03, 0xaa, 0x60, 0xaf, 0xd5, 0x36, 0x40, 0x11, - 0x67, 0x89, 0xb1, 0x66, 0xd5, 0x88, 0x62, 0x6d }; + static const uint8_t expected_twoblocks[CHACHA20_KEY_SIZE * 2] = { + 0xe3, 0xb0, 0x8a, 0xcc, 0x34, 0xc3, 0x17, 0x0e, + 0xc3, 0xd8, 0xc3, 0x40, 0xe7, 0x73, 0xe9, 0x0d, + 0xd1, 0x62, 0xa3, 0x5d, 0x7d, 0xf2, 0xf1, 0x4a, + 0x24, 0x42, 0xb7, 0x1e, 0xb0, 0x05, 0x17, 0x07, + 0xb9, 0x35, 0x10, 0x69, 0x8b, 0x46, 0xfb, 0x51, + 0xe9, 0x91, 0x3f, 0x46, 0xf2, 0x4d, 0xea, 0xd0, + 0x81, 0xc1, 0x1b, 0xa9, 0x5d, 0x52, 0x91, 0x5f, + 0xcd, 0xdc, 0xc6, 0xd6, 0xc3, 0x7c, 0x50, 0x23 }; /* * Expected result when ChaCha20 DRNG state is zero: @@ -429,18 +588,22 @@ static int drng_chacha20_rng_selftest(struct chacha20_drng *drng) * 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, * 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, * 0x20 - * and pulling one ChaCha20 DRNG block plus one byte. + * and pulling one ChaCha20 DRNG block plus four byte. */ - uint8_t expected_block_and_byte[CHACHA20_KEY_SIZE + 1] = { - 0x3d, 0x13, 0x47, 0x1e, 0x7f, 0x7c, 0x99, 0x33, - 0xfc, 0x44, 0xa4, 0xdd, 0xf9, 0x3d, 0xe1, 0x9a, - 0xd4, 0xe8, 0x7a, 0x7d, 0x42, 0xac, 0xd1, 0xcd, - 0x10, 0x69, 0xe7, 0xbf, 0xd4, 0xfd, 0x69, 0x4b, - 0xa7 }; + static const uint8_t expected_block_nonaligned[CHACHA20_KEY_SIZE + 4] = { + 0x9c, 0xfc, 0x5e, 0x31, 0x21, 0x62, 0x11, 0x85, + 0xd3, 0x77, 0xd3, 0x69, 0x0f, 0xa8, 0x16, 0x55, + 0xb4, 0x4c, 0xf6, 0x52, 0xf3, 0xa8, 0x37, 0x99, + 0x38, 0x76, 0xa0, 0x66, 0xec, 0xbb, 0xce, 0xa9, + 0x9c, 0x95, 0xa1, 0xfd }; + + drng_chacha20_bswap32((uint32_t *)seed, + sizeof(seed) / sizeof(uint32_t)); /* Generate with zero state */ ret = drng_chacha20_generate(&drng->chacha20, outbuf, sizeof(expected_block)); + if (ret) return ret; if (memcmp(outbuf, expected_block, sizeof(expected_block))) @@ -454,6 +617,7 @@ static int drng_chacha20_rng_selftest(struct chacha20_drng *drng) sizeof(expected_twoblocks)); if (ret) return ret; + ret = drng_chacha20_generate(&drng->chacha20, outbuf, sizeof(expected_twoblocks)); if (ret) @@ -466,15 +630,15 @@ static int drng_chacha20_rng_selftest(struct chacha20_drng *drng) /* Reseed with 1 block and one byte */ ret = drng_chacha20_seed(&drng->chacha20, seed, - sizeof(expected_block_and_byte)); + sizeof(expected_block_nonaligned)); if (ret) return ret; ret = drng_chacha20_generate(&drng->chacha20, outbuf, - sizeof(expected_block_and_byte)); + sizeof(expected_block_nonaligned)); if (ret) return ret; - if (memcmp(outbuf, expected_block_and_byte, - sizeof(expected_block_and_byte))) + if (memcmp(outbuf, expected_block_nonaligned, + sizeof(expected_block_nonaligned))) return -EFAULT; return 0; @@ -482,8 +646,8 @@ static int drng_chacha20_rng_selftest(struct chacha20_drng *drng) static void drng_chacha20_dealloc(struct chacha20_drng *drng) { - memset_secure(drng, 0, sizeof(*drng)); - free(drng); + memset_secure(drng, 0, sizeof(*drng)); + free(drng); } /** @@ -499,31 +663,26 @@ static int drng_chacha20_alloc(struct chacha20_drng **out) return -EFAULT; } -#ifdef _WIN32 - drng = _aligned_malloc(sizeof(*drng), CHACHA20_DRNG_ALIGNMENT); -#endif - -#ifndef aligned_alloc - drng = malloc(sizeof(*drng)); -#else - drng = aligned_alloc(CHACHA20_DRNG_ALIGNMENT, sizeof(*drng)); -#endif - if (drng == NULL) { - return -1; + ret = posix_memalign((void *)&drng, CHACHA20_DRNG_ALIGNMENT, + sizeof(*drng)); + if (ret) { + return -ret; } -#ifndef _WIN32 /* prevent paging out of the memory state to swap space */ ret = mlock(drng, sizeof(*drng)); if (ret && errno != EPERM && errno != EAGAIN) { ret = -errno; goto err; } -#endif - + memset(drng, 0, sizeof(*drng)); - memcpy(&drng->chacha20.constants[0], "expand 32-byte k", 16); + /* String "expand 32-byte k" */ + drng->chacha20.constants[0] = 0x61707865; + drng->chacha20.constants[1] = 0x3320646e; + drng->chacha20.constants[2] = 0x79622d32; + drng->chacha20.constants[3] = 0x6b206574; ret = drng_chacha20_rng_selftest(drng); if (ret) @@ -559,6 +718,33 @@ int drng_chacha20_reseed(struct chacha20_drng *drng, const uint8_t *inbuf, int ret; uint32_t collected = 0; + /* Entropy assumption: 1 data bit delivers one bit of entropy */ + ret = drng_getrandom_get(seed, CHACHA20_KEY_SIZE); + if (ret < 0) + return ret; + + if (ret) { + collected = ret; + + ret = drng_chacha20_seed(&drng->chacha20, seed, + CHACHA20_KEY_SIZE); + if (ret) + return ret; + } + + /* Entropy assumption: 2 data bits deliver one bit of entropy */ + ret = drng_jent_get(seed, sizeof(seed)); + if (ret < 0) + return ret; + + if (ret) { + collected += ret; + + ret = drng_chacha20_seed(&drng->chacha20, seed, sizeof(seed)); + if (ret) + return ret; + } + /* Entropy assumption: 1 data bit delivers one bit of entropy */ ret = drng_random_get(seed, CHACHA20_KEY_SIZE); if (ret < 0) @@ -591,7 +777,9 @@ int drng_chacha20_reseed(struct chacha20_drng *drng, const uint8_t *inbuf, DSO_PUBLIC void drng_chacha20_destroy(struct chacha20_drng *drng) { - drng_chacha20_dealloc(drng); + drng_jent_dealloc(); + drng_random_dealloc(); + drng_chacha20_dealloc(drng); } DSO_PUBLIC diff --git a/src/inexact.c b/src/inexact.c index 1992e17..3910a74 100644 --- a/src/inexact.c +++ b/src/inexact.c @@ -1134,4 +1134,3 @@ exit: return message; return NULL; } - diff --git a/src/sha3.c b/src/sha3.c index 15a726f..ffc030e 100644 --- a/src/sha3.c +++ b/src/sha3.c @@ -23,22 +23,15 @@ #include "sha3.h" #define SHA3_ASSERT( x ) -#if defined(_MSC_VER) #define SHA3_TRACE( format, ...) -#define SHA3_TRACE_BUF( format, buf, l, ...) -#else -#define SHA3_TRACE(format, args...) -#define SHA3_TRACE_BUF(format, buf, l, args...) -#endif +#define SHA3_TRACE_BUF(format, buf, l) -//#define SHA3_USE_KECCAK /* - * Define SHA3_USE_KECCAK to run "pure" Keccak, as opposed to SHA3. - * The tests that this macro enables use the input and output from [Keccak] - * (see the reference below). The used test vectors aren't correct for SHA3, - * however, they are helpful to verify the implementation. - * SHA3_USE_KECCAK only changes one line of code in Finalize. + * This flag is used to configure "pure" Keccak, as opposed to NIST SHA3. */ +#define SHA3_USE_KECCAK_FLAG 0x80000000 +#define SHA3_CW(x) ((x) & (~SHA3_USE_KECCAK_FLAG)) + #if defined(_MSC_VER) #define SHA3_CONST(x) x @@ -123,30 +116,44 @@ keccakf(uint64_t s[25]) /* *************************** Public Inteface ************************ */ /* For Init or Reset call these: */ +sha3_return_t +sha3_Init(void *priv, unsigned bitSize) { + sha3_context *ctx = (sha3_context *) priv; + if( bitSize != 256 && bitSize != 384 && bitSize != 512 ) + return SHA3_RETURN_BAD_PARAMS; + memset(ctx, 0, sizeof(*ctx)); + ctx->capacityWords = 2 * bitSize / (8 * sizeof(uint64_t)); + return SHA3_RETURN_OK; +} + void sha3_Init256(void *priv) { - sha3_context *ctx = (sha3_context *) priv; - memset(ctx, 0, sizeof(*ctx)); - ctx->capacityWords = 2 * 256 / (8 * sizeof(uint64_t)); + sha3_Init(priv, 256); } void sha3_Init384(void *priv) { - sha3_context *ctx = (sha3_context *) priv; - memset(ctx, 0, sizeof(*ctx)); - ctx->capacityWords = 2 * 384 / (8 * sizeof(uint64_t)); + sha3_Init(priv, 384); } void sha3_Init512(void *priv) { - sha3_context *ctx = (sha3_context *) priv; - memset(ctx, 0, sizeof(*ctx)); - ctx->capacityWords = 2 * 512 / (8 * sizeof(uint64_t)); + sha3_Init(priv, 512); } +enum SHA3_FLAGS +sha3_SetFlags(void *priv, enum SHA3_FLAGS flags) +{ + sha3_context *ctx = (sha3_context *) priv; + flags &= SHA3_FLAGS_KECCAK; + ctx->capacityWords |= (flags == SHA3_FLAGS_KECCAK ? SHA3_USE_KECCAK_FLAG : 0); + return flags; +} + + void sha3_Update(void *priv, void const *bufIn, size_t len) { @@ -164,7 +171,7 @@ sha3_Update(void *priv, void const *bufIn, size_t len) SHA3_TRACE_BUF("called to update with:", buf, len); SHA3_ASSERT(ctx->byteIndex < 8); - SHA3_ASSERT(ctx->wordIndex < sizeof(ctx->s) / sizeof(ctx->s[0])); + SHA3_ASSERT(ctx->wordIndex < sizeof(ctx->u.s) / sizeof(ctx->u.s[0])); if(len < old_tail) { /* have no complete word or haven't started * the word yet */ @@ -185,13 +192,13 @@ sha3_Update(void *priv, void const *bufIn, size_t len) ctx->saved |= (uint64_t) (*(buf++)) << ((ctx->byteIndex++) * 8); /* now ready to add saved to the sponge */ - ctx->s[ctx->wordIndex] ^= ctx->saved; + ctx->u.s[ctx->wordIndex] ^= ctx->saved; SHA3_ASSERT(ctx->byteIndex == 8); ctx->byteIndex = 0; ctx->saved = 0; if(++ctx->wordIndex == - (SHA3_KECCAK_SPONGE_WORDS - ctx->capacityWords)) { - keccakf(ctx->s); + (SHA3_KECCAK_SPONGE_WORDS - SHA3_CW(ctx->capacityWords))) { + keccakf(ctx->u.s); ctx->wordIndex = 0; } } @@ -217,10 +224,10 @@ sha3_Update(void *priv, void const *bufIn, size_t len) #if defined(__x86_64__ ) || defined(__i386__) SHA3_ASSERT(memcmp(&t, buf, 8) == 0); #endif - ctx->s[ctx->wordIndex] ^= t; + ctx->u.s[ctx->wordIndex] ^= t; if(++ctx->wordIndex == - (SHA3_KECCAK_SPONGE_WORDS - ctx->capacityWords)) { - keccakf(ctx->s); + (SHA3_KECCAK_SPONGE_WORDS - SHA3_CW(ctx->capacityWords))) { + keccakf(ctx->u.s); ctx->wordIndex = 0; } } @@ -253,21 +260,22 @@ sha3_Finalize(void *priv) * Overall, we feed 0, then 1, and finally 1 to start padding. Without * M || 01, we would simply use 1 to start padding. */ -#ifndef SHA3_USE_KECCAK - /* SHA3 version */ - ctx->s[ctx->wordIndex] ^= - (ctx->saved ^ ((uint64_t) ((uint64_t) (0x02 | (1 << 2)) << - ((ctx->byteIndex) * 8)))); -#else - /* For testing the "pure" Keccak version */ - ctx->s[ctx->wordIndex] ^= - (ctx->saved ^ ((uint64_t) ((uint64_t) 1 << (ctx->byteIndex * - 8)))); -#endif + uint64_t t; - ctx->s[SHA3_KECCAK_SPONGE_WORDS - ctx->capacityWords - 1] ^= + if( ctx->capacityWords & SHA3_USE_KECCAK_FLAG ) { + /* Keccak version */ + t = (uint64_t)(((uint64_t) 1) << (ctx->byteIndex * 8)); + } + else { + /* SHA3 version */ + t = (uint64_t)(((uint64_t)(0x02 | (1 << 2))) << ((ctx->byteIndex) * 8)); + } + + ctx->u.s[ctx->wordIndex] ^= ctx->saved ^ t; + + ctx->u.s[SHA3_KECCAK_SPONGE_WORDS - SHA3_CW(ctx->capacityWords) - 1] ^= SHA3_CONST(0x8000000000000000UL); - keccakf(ctx->s); + keccakf(ctx->u.s); /* Return first bytes of the ctx->s. This conversion is not needed for * little-endian platforms e.g. wrap with #if !defined(__BYTE_ORDER__) @@ -277,20 +285,39 @@ sha3_Finalize(void *priv) { unsigned i; for(i = 0; i < SHA3_KECCAK_SPONGE_WORDS; i++) { - const unsigned t1 = (uint32_t) ctx->s[i]; - const unsigned t2 = (uint32_t) ((ctx->s[i] >> 16) >> 16); - ctx->sb[i * 8 + 0] = (uint8_t) (t1); - ctx->sb[i * 8 + 1] = (uint8_t) (t1 >> 8); - ctx->sb[i * 8 + 2] = (uint8_t) (t1 >> 16); - ctx->sb[i * 8 + 3] = (uint8_t) (t1 >> 24); - ctx->sb[i * 8 + 4] = (uint8_t) (t2); - ctx->sb[i * 8 + 5] = (uint8_t) (t2 >> 8); - ctx->sb[i * 8 + 6] = (uint8_t) (t2 >> 16); - ctx->sb[i * 8 + 7] = (uint8_t) (t2 >> 24); + const unsigned t1 = (uint32_t) ctx->u.s[i]; + const unsigned t2 = (uint32_t) ((ctx->u.s[i] >> 16) >> 16); + ctx->u.sb[i * 8 + 0] = (uint8_t) (t1); + ctx->u.sb[i * 8 + 1] = (uint8_t) (t1 >> 8); + ctx->u.sb[i * 8 + 2] = (uint8_t) (t1 >> 16); + ctx->u.sb[i * 8 + 3] = (uint8_t) (t1 >> 24); + ctx->u.sb[i * 8 + 4] = (uint8_t) (t2); + ctx->u.sb[i * 8 + 5] = (uint8_t) (t2 >> 8); + ctx->u.sb[i * 8 + 6] = (uint8_t) (t2 >> 16); + ctx->u.sb[i * 8 + 7] = (uint8_t) (t2 >> 24); } } - SHA3_TRACE_BUF("Hash: (first 32 bytes)", ctx->sb, 256 / 8); + SHA3_TRACE_BUF("Hash: (first 32 bytes)", ctx->u.sb, 256 / 8); - return (ctx->sb); + return (ctx->u.sb); +} + +sha3_return_t sha3_HashBuffer( unsigned bitSize, enum SHA3_FLAGS flags, const void *in, unsigned inBytes, void *out, unsigned outBytes ) { + sha3_return_t err; + sha3_context c; + + err = sha3_Init(&c, bitSize); + if( err != SHA3_RETURN_OK ) + return err; + if( sha3_SetFlags(&c, flags) != flags ) { + return SHA3_RETURN_BAD_PARAMS; + } + sha3_Update(&c, in, inBytes); + const void *h = sha3_Finalize(&c); + + if(outBytes > bitSize/8) + outBytes = bitSize/8; + memcpy(out, h, outBytes); + return SHA3_RETURN_OK; } diff --git a/src/sha3.h b/src/sha3.h index adcf1e2..7ad98f2 100644 --- a/src/sha3.h +++ b/src/sha3.h @@ -1,6 +1,8 @@ #ifndef SHA3_H #define SHA3_H +#include + /* ------------------------------------------------------------------------- * Works when compiled for either 32-bit or 64-bit targets, optimized for * 64 bit. @@ -28,7 +30,7 @@ typedef struct sha3_context_ { union { /* Keccak's state */ uint64_t s[SHA3_KECCAK_SPONGE_WORDS]; uint8_t sb[SHA3_KECCAK_SPONGE_WORDS * 8]; - }; + } u; unsigned byteIndex; /* 0..7--the next byte after the set one * (starts from 0; 0--none are buffered) */ unsigned wordIndex; /* 0..24--the next word to integrate input @@ -37,14 +39,35 @@ typedef struct sha3_context_ { * words (e.g. 16 for Keccak 512) */ } sha3_context; +enum SHA3_FLAGS { + SHA3_FLAGS_NONE=0, + SHA3_FLAGS_KECCAK=1 +}; + +enum SHA3_RETURN { + SHA3_RETURN_OK=0, + SHA3_RETURN_BAD_PARAMS=1 +}; +typedef enum SHA3_RETURN sha3_return_t; /* For Init or Reset call these: */ +sha3_return_t sha3_Init(void *priv, unsigned bitSize); + void sha3_Init256(void *priv); void sha3_Init384(void *priv); void sha3_Init512(void *priv); +enum SHA3_FLAGS sha3_SetFlags(void *priv, enum SHA3_FLAGS); + void sha3_Update(void *priv, void const *bufIn, size_t len); void const *sha3_Finalize(void *priv); +/* Single-call hashing */ +sha3_return_t sha3_HashBuffer( + unsigned bitSize, /* 256, 384, 512 */ + enum SHA3_FLAGS flags, /* SHA3_FLAGS_NONE or SHA3_FLAGS_KECCAK */ + const void *in, unsigned inBytes, + void *out, unsigned outBytes ); /* up to bitSize/8; truncation OK */ + #endif