OSDN Git Service

73bb8dda80e48da193ae4f9e3c7713c4e9e77faf
[mingw/mingw-org-wsl.git] / mingwrt / setargv.c
1 /*
2  * setargv.c
3  *
4  * Implements runtime initialization code to populate the argument
5  * vector, which will subsequently be passed to the main() function;
6  * provides a _setargv() hook, similar to that described on MSDN.
7  *
8  * $Id$
9  *
10  * Written by Keith Marshall <keithmarshall@users.sourceforge.net>
11  * Copyright (C) 2014, 2017, MinGW.org Project
12  *
13  * ---------------------------------------------------------------------------
14  *
15  * Permission is hereby granted, free of charge, to any person obtaining a
16  * copy of this software and associated documentation files (the "Software"),
17  * to deal in the Software without restriction, including without limitation
18  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
19  * and/or sell copies of the Software, and to permit persons to whom the
20  * Software is furnished to do so, subject to the following conditions:
21  *
22  * The above copyright notice and this permission notice shall be included
23  * in all copies or substantial portions of the Software.
24  *
25  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
26  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
28  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
30  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
31  * DEALINGS IN THE SOFTWARE.
32  *
33  * ---------------------------------------------------------------------------
34  *
35  */
36 #define _ISOC99_SOURCE
37
38 #include <glob.h>
39 #include <string.h>
40 #include <ctype.h>
41
42 #define WIN32_LEAN_AND_MEAN
43 #include <windows.h>
44
45 /* Access to a standard 'main'-like argument count and list.
46  */
47 extern int     _argc;
48 extern char ** _argv;
49 extern int     _CRT_glob;
50
51 #define ARGV_INLINE  static __inline__ __attribute__((__always_inline__))
52
53 #define ARGV_ESCAPE     __CRT_GLOB_ESCAPE_CHAR__
54 #define ARGV_SQUOTE     __CRT_GLOB_USE_SINGLE_QUOTE__
55 #define ARGV_NOGROUP    __CRT_GLOB_BRACKET_GROUPS__
56
57 ARGV_INLINE
58 char *backslash( int count, char *buf )
59 {
60   /* Helper used by the MinGW replacement command line globbing handler,
61    * to provide appropriate handling of backslashes while preparing the
62    * command line arguments for globbing.
63    */
64   while( count-- )
65     *buf++ = '\\';
66   return buf;
67 }
68
69 ARGV_INLINE
70 char *unquote( int quote, int altquote, int escape, int *state, char *buf )
71 {
72   /* Helper used by the MinGW replacement command line globbing handler,
73    * to provide a single level of reduction for balanced quotation marks,
74    * while preparing the command line arguments for globbing.
75    */
76   buf = backslash( escape >> 1, buf );
77   if( (escape & 1) || (*state == altquote) )
78     /*
79      * In this case, the quotation mark is to be interpreted as a literal,
80      * and is NOT a candidate for reduction...
81      */
82     *buf++ = quote;
83   else
84     /* ...while this is the more usual case, of a quotation mark used to
85      * delimit a single argument; it must be reduced.
86      */
87     *state ^= quote;
88   return buf;
89 }
90
91 ARGV_INLINE
92 void __mingw32_setargv( const char *cmdline )
93 {
94   /* Implementation of the MinGW replacement command line interpreter.
95    */
96   char cmdbuf[1 + strlen( cmdline ) << 1];
97   int c, gotarg = 0, quoted = 0, bracket = 0, bslash = 0;
98   char *argptr = cmdbuf; const char *cmdptr = cmdline;
99   glob_t gl_argv;
100
101   /* Capture any non-default globbing options, which the user may have
102    * specified via a custom setting for _CRT_glob.
103    */
104   int gl_opts = GLOB_NOCHECK;
105   if( _CRT_glob & __CRT_GLOB_CASE_SENSITIVE__ )
106     gl_opts |= GLOB_CASEMATCH;
107
108   /* We explicitly DO NOT use the GLOB_DOOFFS capability; ensure that
109    * the associated field, in the glob_t structure, is initialized to
110    * correctly reflect this.
111    */
112   gl_argv.gl_offs = 0;
113
114   /* Scan the command line, and prepare it for globbing.
115    */
116   while( c = *cmdptr++ )
117   {
118     /* Got a character to process...
119      */
120     switch( c )
121     {
122       /* Specific characters, which serve as globbing tokens,
123        * need special handling.
124        */
125       case '\\':
126         /* We don't (yet) know if this is a literal backslash,
127          * (directory separator), or an escape for a following
128          * quote character; just note its presence, until we
129          * have looked far enough ahead to decide.
130          */
131         ++bslash;
132         break;
133
134       case '[':
135         /* POSIX defines this as a globbing token, (introducing
136          * a character group); we don't support this by default,
137          * so defeat it, unless the extended behaviour has been
138          * requested by the user.
139          */
140         bracket = (_CRT_glob & ARGV_NOGROUP) ? 0 : ARGV_NOGROUP;
141
142       case '*':
143       case '?':
144         /* These standard globbing tokens...
145          */
146       case ARGV_ESCAPE:
147         /* ...and the escape character itself, need to be escaped
148          * when they appear in any context in which they should be
149          * interpreted literally, rather than globbed.
150          */
151         argptr = backslash( bslash, argptr );
152         if( quoted || (bracket == ARGV_NOGROUP) || (c == ARGV_ESCAPE) )
153           *argptr++ = ARGV_ESCAPE;
154         bracket = bslash = 0;
155         *argptr++ = c;
156         break;
157
158       case '"':
159         /* The double quote always acts as an argument quoting
160          * character, (unless escaped); handle it accordingly.
161          */
162         argptr = unquote( c, '\'', bslash, &quoted, argptr );
163         gotarg = 1; bslash = 0;
164         break;
165
166       case '\'':
167         /* POSIX also defines the single quote as a quoting
168          * character, but MS-Windows does not; we offer this
169          * extended handling...
170          */
171         if( _CRT_glob & ARGV_SQUOTE )
172         {
173           /* ...only when the user has explicitly enabled the
174            * POSIX compatible extended quoting option.
175            */
176           argptr = unquote( c, '"', bslash, &quoted, argptr );
177           gotarg = 1; bslash = 0;
178           break;
179         }
180
181       default:
182         /* With one exception, any other character is handled
183          * literally, after flushing out any pending backslashes.
184          */
185         argptr = backslash( bslash, argptr );
186         if( (quoted == 0) && isblank( c ) )
187         {
188           /* The one exception is any blank or tab character,
189            * when it is not contained within quotes; this acts
190            * as an argument separator, (or is simply discarded
191            * if there is no argument already collected)...
192            */
193           if( gotarg || (argptr > cmdbuf) )
194           {
195             /* ...so, when there is a argument pending, we may
196              * now add it to the globbed argument vector.
197              */
198             *argptr = '\0';
199             __mingw_glob( argptr = cmdbuf, gl_opts, NULL, &gl_argv );
200             gl_opts |= GLOB_APPEND;
201             gotarg = 0;
202           }
203         }
204         else
205           /* In every other case, we simply collect the current
206            * literal character into the next pending argument.
207            */
208           *argptr++ = c;
209
210         /* Irrespective of how we handled the current character,
211          * we can be certain that there are no pending backslashes
212          * by the time we get to here.
213          */
214         bslash = 0;
215     }
216   }
217   /* Finally, when we've run out of command line characters to process,
218    * flush out any final pending backslashes, ...
219    */
220   argptr = backslash( bslash, argptr );
221   if( gotarg || (argptr > cmdbuf) )
222   {
223     /* ...and add any final pending argument to the globbed vector.
224      */
225     *argptr = '\0';
226     __mingw_glob( argptr = cmdbuf, gl_opts, NULL, &gl_argv );
227   }
228   /* ...and store the resultant globbed vector into the "argc" and "argv"
229    * variables to be passed to main(); note that this allows us to safely
230    * discard our working glob_t structure, but we MUST NOT globfree() it,
231    * as that would destroy the content of "argv".
232    */
233   _argc = gl_argv.gl_pathc;
234   _argv = gl_argv.gl_pathv;
235 }
236
237 extern void _mingw32_init_mainargs( void );
238
239 void _setargv()
240 {
241   /* Initialize the _argc, _argv and environ variables.
242    */
243   if( (_CRT_glob & __CRT_GLOB_USE_MINGW__) == 0 )
244   {
245     /* This is the old start-up mechanism, implemented via a callback
246      * into the CRT initialization module, in which we use a start-up
247      * hook provided by Microsoft's runtime library to initialize the
248      * argument and environment vectors.
249      */
250     _mingw32_init_mainargs();
251   }
252   else
253   { /* Here, we implement a new, more POSIX compatible mechanism,
254      * for initializing the argument vector; note that we delegate
255      * to the previously defined inline function, which avoids the
256      * broken globbing behaviour of some more recent versions of
257      * MSVCRT.DLL
258      */
259     __mingw32_setargv( GetCommandLine() );
260   }
261 }
262
263 /* $RCSfile$: end of file */