1 /* Parse arguments from a string and prepend them to an argv. 2 3 Copyright (C) 1999-2002, 2006, 2009-2011 Free Software Foundation, Inc. 4 5 This program is free software: you can redistribute it and/or modify 6 it under the terms of the GNU General Public License as published by 7 the Free Software Foundation, either version 3 of the License, or 8 (at your option) any later version. 9 10 This program is distributed in the hope that it will be useful, 11 but WITHOUT ANY WARRANTY; without even the implied warranty of 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 GNU General Public License for more details. 14 15 You should have received a copy of the GNU General Public License 16 along with this program. If not, see <http://www.gnu.org/licenses/>. */ 17 18 /* Written by Paul Eggert <eggert@twinsun.com>. */ 19 20 #include <config.h> 21 22 #include "prepargs.h" 23 #include <string.h> 24 #include <sys/types.h> 25 #include <xalloc.h> 26 27 #include <ctype.h> 28 29 /* IN_CTYPE_DOMAIN (C) is nonzero if the unsigned char C can safely be given 30 as an argument to <ctype.h> macros like "isspace". */ 31 #ifdef STDC_HEADERS 32 # define IN_CTYPE_DOMAIN(c) 1 33 #else 34 # define IN_CTYPE_DOMAIN(c) ((c) <= 0177) 35 #endif 36 37 #define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c)) 38 39 /* Find the white-space-separated options specified by OPTIONS, and 40 using BUF to store copies of these options, set ARGV[0], ARGV[1], 41 etc. to the option copies. Return the number N of options found. 42 Do not set ARGV[N]. If ARGV is zero, do not store ARGV[0] etc. 43 Backslash can be used to escape whitespace (and backslashes). */ 44 static int 45 prepend_args (char const *options, char *buf, char **argv) 46 { 47 char const *o = options; 48 char *b = buf; 49 int n = 0; 50 51 for (;;) 52 { 53 while (ISSPACE ((unsigned char) *o)) 54 o++; 55 if (!*o) 56 return n; 57 if (argv) 58 argv[n] = b; 59 n++; 60 61 do 62 if ((*b++ = *o++) == '\\' && *o) 63 b[-1] = *o++; 64 while (*o && ! ISSPACE ((unsigned char) *o)); 65 66 *b++ = '\0'; 67 } 68 } 69 70 /* Prepend the whitespace-separated options in OPTIONS to the argument 71 vector of a main program with argument count *PARGC and argument 72 vector *PARGV. */ 73 void 74 prepend_default_options (char const *options, int *pargc, char ***pargv) 75 { 76 if (options) 77 { 78 char *buf = xmalloc (strlen (options) + 1); 79 int prepended = prepend_args (options, buf, (char **) 0); 80 int argc = *pargc; 81 char * const *argv = *pargv; 82 char **pp = xmalloc ((prepended + argc + 1) * sizeof *pp); 83 *pargc = prepended + argc; 84 *pargv = pp; 85 *pp++ = *argv++; 86 pp += prepend_args (options, buf, pp); 87 while ((*pp++ = *argv++)) 88 continue; 89 } 90 } 91