/* Parse arguments from a string and prepend them to an argv.12Copyright (C) 1999, 2000, 2001, 2002 Free Software Foundation, Inc.34This program is free software; you can redistribute it and/or modify5it under the terms of the GNU General Public License as published by6the Free Software Foundation; either version 2, or (at your option)7any later version.89This program is distributed in the hope that it will be useful,10but WITHOUT ANY WARRANTY; without even the implied warranty of11MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12GNU General Public License for more details.1314You should have received a copy of the GNU General Public License15along with this program; if not, write to the Free Software16Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA1702111-1307, USA. */1819/* Written by Paul Eggert <[email protected]>. */2021#ifdef HAVE_CONFIG_H22# include <config.h>23#endif24#include "prepargs.h"25#include <string.h>26#include <sys/types.h>27#include <xalloc.h>2829#include <ctype.h>3031/* IN_CTYPE_DOMAIN (C) is nonzero if the unsigned char C can safely be given32as an argument to <ctype.h> macros like "isspace". */33#ifdef STDC_HEADERS34# define IN_CTYPE_DOMAIN(c) 135#else36# define IN_CTYPE_DOMAIN(c) ((c) <= 0177)37#endif3839#define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c))4041/* Find the white-space-separated options specified by OPTIONS, and42using BUF to store copies of these options, set ARGV[0], ARGV[1],43etc. to the option copies. Return the number N of options found.44Do not set ARGV[N]. If ARGV is zero, do not store ARGV[0] etc.45Backslash can be used to escape whitespace (and backslashes). */46static int47prepend_args (char const *options, char *buf, char **argv)48{49char const *o = options;50char *b = buf;51int n = 0;5253for (;;)54{55while (ISSPACE ((unsigned char) *o))56o++;57if (!*o)58return n;59if (argv)60argv[n] = b;61n++;6263do64if ((*b++ = *o++) == '\\' && *o)65b[-1] = *o++;66while (*o && ! ISSPACE ((unsigned char) *o));6768*b++ = '\0';69}70}7172/* Prepend the whitespace-separated options in OPTIONS to the argument73vector of a main program with argument count *PARGC and argument74vector *PARGV. */75void76prepend_default_options (char const *options, int *pargc, char ***pargv)77{78if (options)79{80char *buf = xmalloc (strlen (options) + 1);81int prepended = prepend_args (options, buf, (char **) 0);82int argc = *pargc;83char * const *argv = *pargv;84char **pp = (char **) xmalloc ((prepended + argc + 1) * sizeof *pp);85*pargc = prepended + argc;86*pargv = pp;87*pp++ = *argv++;88pp += prepend_args (options, buf, pp);89while ((*pp++ = *argv++))90continue;91}92}939495