wined3d: Rename dummyTextureName variable.
[wine/multimedia.git] / programs / cmd / wcmdmain.c
blob04e13910065b87ee80f4d00ee8a960436675812a
1 /*
2 * CMD - Wine-compatible command line interface.
4 * Copyright (C) 1999 - 2001 D A Pickles
5 * Copyright (C) 2007 J Edmeades
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 * FIXME:
24 * - Cannot handle parameters in quotes
25 * - Lots of functionality missing from builtins
28 #include "config.h"
29 #include "wcmd.h"
30 #include "wine/debug.h"
32 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
34 const WCHAR inbuilt[][10] = {
35 {'A','T','T','R','I','B','\0'},
36 {'C','A','L','L','\0'},
37 {'C','D','\0'},
38 {'C','H','D','I','R','\0'},
39 {'C','L','S','\0'},
40 {'C','O','P','Y','\0'},
41 {'C','T','T','Y','\0'},
42 {'D','A','T','E','\0'},
43 {'D','E','L','\0'},
44 {'D','I','R','\0'},
45 {'E','C','H','O','\0'},
46 {'E','R','A','S','E','\0'},
47 {'F','O','R','\0'},
48 {'G','O','T','O','\0'},
49 {'H','E','L','P','\0'},
50 {'I','F','\0'},
51 {'L','A','B','E','L','\0'},
52 {'M','D','\0'},
53 {'M','K','D','I','R','\0'},
54 {'M','O','V','E','\0'},
55 {'P','A','T','H','\0'},
56 {'P','A','U','S','E','\0'},
57 {'P','R','O','M','P','T','\0'},
58 {'R','E','M','\0'},
59 {'R','E','N','\0'},
60 {'R','E','N','A','M','E','\0'},
61 {'R','D','\0'},
62 {'R','M','D','I','R','\0'},
63 {'S','E','T','\0'},
64 {'S','H','I','F','T','\0'},
65 {'T','I','M','E','\0'},
66 {'T','I','T','L','E','\0'},
67 {'T','Y','P','E','\0'},
68 {'V','E','R','I','F','Y','\0'},
69 {'V','E','R','\0'},
70 {'V','O','L','\0'},
71 {'E','N','D','L','O','C','A','L','\0'},
72 {'S','E','T','L','O','C','A','L','\0'},
73 {'P','U','S','H','D','\0'},
74 {'P','O','P','D','\0'},
75 {'A','S','S','O','C','\0'},
76 {'C','O','L','O','R','\0'},
77 {'F','T','Y','P','E','\0'},
78 {'M','O','R','E','\0'},
79 {'C','H','O','I','C','E','\0'},
80 {'E','X','I','T','\0'}
83 HINSTANCE hinst;
84 DWORD errorlevel;
85 int echo_mode = 1, verify_mode = 0, defaultColor = 7;
86 static int opt_c, opt_k, opt_s;
87 const WCHAR newline[] = {'\r','\n','\0'};
88 static const WCHAR equalsW[] = {'=','\0'};
89 static const WCHAR closeBW[] = {')','\0'};
90 WCHAR anykey[100];
91 WCHAR version_string[100];
92 WCHAR quals[MAX_PATH], param1[MAXSTRING], param2[MAXSTRING];
93 BATCH_CONTEXT *context = NULL;
94 extern struct env_stack *pushd_directories;
95 static const WCHAR *pagedMessage = NULL;
96 static char *output_bufA = NULL;
97 #define MAX_WRITECONSOLE_SIZE 65535
98 BOOL unicodePipes = FALSE;
101 /*******************************************************************
102 * WCMD_output_asis_len - send output to current standard output
104 * Output a formatted unicode string. Ideally this will go to the console
105 * and hence required WriteConsoleW to output it, however if file i/o is
106 * redirected, it needs to be WriteFile'd using OEM (not ANSI) format
108 static void WCMD_output_asis_len(const WCHAR *message, int len, HANDLE device) {
110 DWORD nOut= 0;
111 DWORD res = 0;
113 /* If nothing to write, return (MORE does this sometimes) */
114 if (!len) return;
116 /* Try to write as unicode assuming it is to a console */
117 res = WriteConsoleW(device, message, len, &nOut, NULL);
119 /* If writing to console fails, assume its file
120 i/o so convert to OEM codepage and output */
121 if (!res) {
122 BOOL usedDefaultChar = FALSE;
123 DWORD convertedChars;
125 if (!unicodePipes) {
127 * Allocate buffer to use when writing to file. (Not freed, as one off)
129 if (!output_bufA) output_bufA = HeapAlloc(GetProcessHeap(), 0,
130 MAX_WRITECONSOLE_SIZE);
131 if (!output_bufA) {
132 WINE_FIXME("Out of memory - could not allocate ansi 64K buffer\n");
133 return;
136 /* Convert to OEM, then output */
137 convertedChars = WideCharToMultiByte(GetConsoleOutputCP(), 0, message,
138 len, output_bufA, MAX_WRITECONSOLE_SIZE,
139 "?", &usedDefaultChar);
140 WriteFile(device, output_bufA, convertedChars,
141 &nOut, FALSE);
142 } else {
143 WriteFile(device, message, len*sizeof(WCHAR),
144 &nOut, FALSE);
147 return;
150 /*******************************************************************
151 * WCMD_output - send output to current standard output device.
155 void WCMD_output (const WCHAR *format, ...) {
157 va_list ap;
158 WCHAR string[1024];
159 int ret;
161 va_start(ap,format);
162 ret = vsnprintfW(string, sizeof(string)/sizeof(WCHAR), format, ap);
163 if( ret >= (sizeof(string)/sizeof(WCHAR))) {
164 WINE_ERR("Output truncated in WCMD_output\n" );
165 ret = (sizeof(string)/sizeof(WCHAR)) - 1;
166 string[ret] = '\0';
168 va_end(ap);
169 WCMD_output_asis_len(string, ret, GetStdHandle(STD_OUTPUT_HANDLE));
173 static int line_count;
174 static int max_height;
175 static int max_width;
176 static BOOL paged_mode;
177 static int numChars;
179 void WCMD_enter_paged_mode(const WCHAR *msg)
181 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
183 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo)) {
184 max_height = consoleInfo.dwSize.Y;
185 max_width = consoleInfo.dwSize.X;
186 } else {
187 max_height = 25;
188 max_width = 80;
190 paged_mode = TRUE;
191 line_count = 0;
192 numChars = 0;
193 pagedMessage = (msg==NULL)? anykey : msg;
196 void WCMD_leave_paged_mode(void)
198 paged_mode = FALSE;
199 pagedMessage = NULL;
202 /***************************************************************************
203 * WCMD_Readfile
205 * Read characters in from a console/file, returning result in Unicode
206 * with signature identical to ReadFile
208 BOOL WCMD_ReadFile(const HANDLE hIn, WCHAR *intoBuf, const DWORD maxChars,
209 LPDWORD charsRead, const LPOVERLAPPED unused) {
211 BOOL res;
213 /* Try to read from console as Unicode */
214 res = ReadConsoleW(hIn, intoBuf, maxChars, charsRead, NULL);
216 /* If reading from console has failed we assume its file
217 i/o so read in and convert from OEM codepage */
218 if (!res) {
220 DWORD numRead;
222 * Allocate buffer to use when reading from file. Not freed
224 if (!output_bufA) output_bufA = HeapAlloc(GetProcessHeap(), 0,
225 MAX_WRITECONSOLE_SIZE);
226 if (!output_bufA) {
227 WINE_FIXME("Out of memory - could not allocate ansi 64K buffer\n");
228 return 0;
231 /* Read from file (assume OEM codepage) */
232 res = ReadFile(hIn, output_bufA, maxChars, &numRead, unused);
234 /* Convert from OEM */
235 *charsRead = MultiByteToWideChar(GetConsoleCP(), 0, output_bufA, numRead,
236 intoBuf, maxChars);
239 return res;
242 /*******************************************************************
243 * WCMD_output_asis - send output to current standard output device.
244 * without formatting eg. when message contains '%'
246 void WCMD_output_asis (const WCHAR *message) {
247 DWORD count;
248 const WCHAR* ptr;
249 WCHAR string[1024];
251 if (paged_mode) {
252 do {
253 ptr = message;
254 while (*ptr && *ptr!='\n' && (numChars < max_width)) {
255 numChars++;
256 ptr++;
258 if (*ptr == '\n') ptr++;
259 WCMD_output_asis_len(message, (ptr) ? ptr - message : strlenW(message),
260 GetStdHandle(STD_OUTPUT_HANDLE));
261 if (ptr) {
262 numChars = 0;
263 if (++line_count >= max_height - 1) {
264 line_count = 0;
265 WCMD_output_asis_len(pagedMessage, strlenW(pagedMessage),
266 GetStdHandle(STD_OUTPUT_HANDLE));
267 WCMD_ReadFile (GetStdHandle(STD_INPUT_HANDLE), string,
268 sizeof(string)/sizeof(WCHAR), &count, NULL);
271 } while (((message = ptr) != NULL) && (*ptr));
272 } else {
273 WCMD_output_asis_len(message, lstrlenW(message),
274 GetStdHandle(STD_OUTPUT_HANDLE));
278 /****************************************************************************
279 * WCMD_print_error
281 * Print the message for GetLastError
284 void WCMD_print_error (void) {
285 LPVOID lpMsgBuf;
286 DWORD error_code;
287 int status;
289 error_code = GetLastError ();
290 status = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
291 NULL, error_code, 0, (LPWSTR) &lpMsgBuf, 0, NULL);
292 if (!status) {
293 WINE_FIXME ("Cannot display message for error %d, status %d\n",
294 error_code, GetLastError());
295 return;
298 WCMD_output_asis_len(lpMsgBuf, lstrlenW(lpMsgBuf),
299 GetStdHandle(STD_ERROR_HANDLE));
300 LocalFree (lpMsgBuf);
301 WCMD_output_asis_len (newline, lstrlenW(newline),
302 GetStdHandle(STD_ERROR_HANDLE));
303 return;
306 /******************************************************************************
307 * WCMD_show_prompt
309 * Display the prompt on STDout
313 static void WCMD_show_prompt (void) {
315 int status;
316 WCHAR out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
317 WCHAR *p, *q;
318 DWORD len;
319 static const WCHAR envPrompt[] = {'P','R','O','M','P','T','\0'};
321 len = GetEnvironmentVariableW(envPrompt, prompt_string,
322 sizeof(prompt_string)/sizeof(WCHAR));
323 if ((len == 0) || (len >= (sizeof(prompt_string)/sizeof(WCHAR)))) {
324 static const WCHAR dfltPrompt[] = {'$','P','$','G','\0'};
325 strcpyW (prompt_string, dfltPrompt);
327 p = prompt_string;
328 q = out_string;
329 *q++ = '\r';
330 *q++ = '\n';
331 *q = '\0';
332 while (*p != '\0') {
333 if (*p != '$') {
334 *q++ = *p++;
335 *q = '\0';
337 else {
338 p++;
339 switch (toupper(*p)) {
340 case '$':
341 *q++ = '$';
342 break;
343 case 'A':
344 *q++ = '&';
345 break;
346 case 'B':
347 *q++ = '|';
348 break;
349 case 'C':
350 *q++ = '(';
351 break;
352 case 'D':
353 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
354 while (*q) q++;
355 break;
356 case 'E':
357 *q++ = '\E';
358 break;
359 case 'F':
360 *q++ = ')';
361 break;
362 case 'G':
363 *q++ = '>';
364 break;
365 case 'H':
366 *q++ = '\b';
367 break;
368 case 'L':
369 *q++ = '<';
370 break;
371 case 'N':
372 status = GetCurrentDirectoryW(sizeof(curdir)/sizeof(WCHAR), curdir);
373 if (status) {
374 *q++ = curdir[0];
376 break;
377 case 'P':
378 status = GetCurrentDirectoryW(sizeof(curdir)/sizeof(WCHAR), curdir);
379 if (status) {
380 strcatW (q, curdir);
381 while (*q) q++;
383 break;
384 case 'Q':
385 *q++ = '=';
386 break;
387 case 'S':
388 *q++ = ' ';
389 break;
390 case 'T':
391 GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
392 while (*q) q++;
393 break;
394 case 'V':
395 strcatW (q, version_string);
396 while (*q) q++;
397 break;
398 case '_':
399 *q++ = '\n';
400 break;
401 case '+':
402 if (pushd_directories) {
403 memset(q, '+', pushd_directories->u.stackdepth);
404 q = q + pushd_directories->u.stackdepth;
406 break;
408 p++;
409 *q = '\0';
412 WCMD_output_asis (out_string);
416 /*************************************************************************
417 * WCMD_strdupW
418 * A wide version of strdup as its missing from unicode.h
420 WCHAR *WCMD_strdupW(const WCHAR *input) {
421 int len=strlenW(input)+1;
422 WCHAR *result = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
423 memcpy(result, input, len * sizeof(WCHAR));
424 return result;
427 /*************************************************************************
428 * WCMD_strsubstW
429 * Replaces a portion of a Unicode string with the specified string.
430 * It's up to the caller to ensure there is enough space in the
431 * destination buffer.
433 void WCMD_strsubstW(WCHAR *start, const WCHAR *next, const WCHAR *insert, int len) {
435 if (len < 0)
436 len=insert ? lstrlenW(insert) : 0;
437 if (start+len != next)
438 memmove(start+len, next, (strlenW(next) + 1) * sizeof(*next));
439 if (insert)
440 memcpy(start, insert, len * sizeof(*insert));
443 /***************************************************************************
444 * WCMD_skip_leading_spaces
446 * Return a pointer to the first non-whitespace character of string.
447 * Does not modify the input string.
449 WCHAR *WCMD_skip_leading_spaces (WCHAR *string) {
451 WCHAR *ptr;
453 ptr = string;
454 while (*ptr == ' ' || *ptr == '\t') ptr++;
455 return ptr;
458 /***************************************************************************
459 * WCMD_keyword_ws_found
461 * Checks if the string located at ptr matches a keyword (of length len)
462 * followed by a whitespace character (space or tab)
464 BOOL WCMD_keyword_ws_found(const WCHAR *keyword, int len, const WCHAR *ptr) {
465 return (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
466 ptr, len, keyword, len) == CSTR_EQUAL)
467 && ((*(ptr + len) == ' ') || (*(ptr + len) == '\t'));
470 /*************************************************************************
471 * WCMD_opt_s_strip_quotes
473 * Remove first and last quote WCHARacters, preserving all other text
475 void WCMD_opt_s_strip_quotes(WCHAR *cmd) {
476 WCHAR *src = cmd + 1, *dest = cmd, *lastq = NULL;
477 while((*dest=*src) != '\0') {
478 if (*src=='\"')
479 lastq=dest;
480 dest++, src++;
482 if (lastq) {
483 dest=lastq++;
484 while ((*dest++=*lastq++) != 0)
490 /*************************************************************************
491 * WCMD_is_magic_envvar
492 * Return TRUE if s is '%'magicvar'%'
493 * and is not masked by a real environment variable.
496 static inline BOOL WCMD_is_magic_envvar(const WCHAR *s, const WCHAR *magicvar)
498 int len;
500 if (s[0] != '%')
501 return FALSE; /* Didn't begin with % */
502 len = strlenW(s);
503 if (len < 2 || s[len-1] != '%')
504 return FALSE; /* Didn't end with another % */
506 if (CompareStringW(LOCALE_USER_DEFAULT,
507 NORM_IGNORECASE | SORT_STRINGSORT,
508 s+1, len-2, magicvar, -1) != CSTR_EQUAL) {
509 /* Name doesn't match. */
510 return FALSE;
513 if (GetEnvironmentVariableW(magicvar, NULL, 0) > 0) {
514 /* Masked by real environment variable. */
515 return FALSE;
518 return TRUE;
521 /*************************************************************************
522 * WCMD_expand_envvar
524 * Expands environment variables, allowing for WCHARacter substitution
526 static WCHAR *WCMD_expand_envvar(WCHAR *start,
527 const WCHAR *forVar, const WCHAR *forVal) {
528 WCHAR *endOfVar = NULL, *s;
529 WCHAR *colonpos = NULL;
530 WCHAR thisVar[MAXSTRING];
531 WCHAR thisVarContents[MAXSTRING];
532 WCHAR savedchar = 0x00;
533 int len;
535 static const WCHAR ErrorLvl[] = {'E','R','R','O','R','L','E','V','E','L','\0'};
536 static const WCHAR Date[] = {'D','A','T','E','\0'};
537 static const WCHAR Time[] = {'T','I','M','E','\0'};
538 static const WCHAR Cd[] = {'C','D','\0'};
539 static const WCHAR Random[] = {'R','A','N','D','O','M','\0'};
540 static const WCHAR Delims[] = {'%',' ',':','\0'};
542 WINE_TRACE("Expanding: %s (%s,%s)\n", wine_dbgstr_w(start),
543 wine_dbgstr_w(forVal), wine_dbgstr_w(forVar));
545 /* Find the end of the environment variable, and extract name */
546 endOfVar = strpbrkW(start+1, Delims);
548 if (endOfVar == NULL || *endOfVar==' ') {
550 /* In batch program, missing terminator for % and no following
551 ':' just removes the '%' */
552 if (context) {
553 WCMD_strsubstW(start, start + 1, NULL, 0);
554 return start;
555 } else {
557 /* In command processing, just ignore it - allows command line
558 syntax like: for %i in (a.a) do echo %i */
559 return start+1;
563 /* If ':' found, process remaining up until '%' (or stop at ':' if
564 a missing '%' */
565 if (*endOfVar==':') {
566 WCHAR *endOfVar2 = strchrW(endOfVar+1, '%');
567 if (endOfVar2 != NULL) endOfVar = endOfVar2;
570 memcpy(thisVar, start, ((endOfVar - start) + 1) * sizeof(WCHAR));
571 thisVar[(endOfVar - start)+1] = 0x00;
572 colonpos = strchrW(thisVar+1, ':');
574 /* If there's complex substitution, just need %var% for now
575 to get the expanded data to play with */
576 if (colonpos) {
577 *colonpos = '%';
578 savedchar = *(colonpos+1);
579 *(colonpos+1) = 0x00;
582 WINE_TRACE("Retrieving contents of %s\n", wine_dbgstr_w(thisVar));
584 /* Expand to contents, if unchanged, return */
585 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
586 /* override if existing env var called that name */
587 if (WCMD_is_magic_envvar(thisVar, ErrorLvl)) {
588 static const WCHAR fmt[] = {'%','d','\0'};
589 wsprintfW(thisVarContents, fmt, errorlevel);
590 len = strlenW(thisVarContents);
591 } else if (WCMD_is_magic_envvar(thisVar, Date)) {
592 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL,
593 NULL, thisVarContents, MAXSTRING);
594 len = strlenW(thisVarContents);
595 } else if (WCMD_is_magic_envvar(thisVar, Time)) {
596 GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL,
597 NULL, thisVarContents, MAXSTRING);
598 len = strlenW(thisVarContents);
599 } else if (WCMD_is_magic_envvar(thisVar, Cd)) {
600 GetCurrentDirectoryW(MAXSTRING, thisVarContents);
601 len = strlenW(thisVarContents);
602 } else if (WCMD_is_magic_envvar(thisVar, Random)) {
603 static const WCHAR fmt[] = {'%','d','\0'};
604 wsprintfW(thisVarContents, fmt, rand() % 32768);
605 len = strlenW(thisVarContents);
607 /* Look for a matching 'for' variable */
608 } else if (forVar &&
609 (CompareStringW(LOCALE_USER_DEFAULT,
610 SORT_STRINGSORT,
611 thisVar,
612 (colonpos - thisVar) - 1,
613 forVar, -1) == CSTR_EQUAL)) {
614 strcpyW(thisVarContents, forVal);
615 len = strlenW(thisVarContents);
617 } else {
619 len = ExpandEnvironmentStringsW(thisVar, thisVarContents,
620 sizeof(thisVarContents)/sizeof(WCHAR));
623 if (len == 0)
624 return endOfVar+1;
626 /* In a batch program, unknown env vars are replaced with nothing,
627 note syntax %garbage:1,3% results in anything after the ':'
628 except the %
629 From the command line, you just get back what you entered */
630 if (lstrcmpiW(thisVar, thisVarContents) == 0) {
632 /* Restore the complex part after the compare */
633 if (colonpos) {
634 *colonpos = ':';
635 *(colonpos+1) = savedchar;
638 /* Command line - just ignore this */
639 if (context == NULL) return endOfVar+1;
642 /* Batch - replace unknown env var with nothing */
643 if (colonpos == NULL) {
644 WCMD_strsubstW(start, endOfVar + 1, NULL, 0);
645 } else {
646 len = strlenW(thisVar);
647 thisVar[len-1] = 0x00;
648 /* If %:...% supplied, : is retained */
649 if (colonpos == thisVar+1) {
650 WCMD_strsubstW(start, endOfVar + 1, colonpos, -1);
651 } else {
652 WCMD_strsubstW(start, endOfVar + 1, colonpos + 1, -1);
655 return start;
659 /* See if we need to do complex substitution (any ':'s), if not
660 then our work here is done */
661 if (colonpos == NULL) {
662 WCMD_strsubstW(start, endOfVar + 1, thisVarContents, -1);
663 return start;
666 /* Restore complex bit */
667 *colonpos = ':';
668 *(colonpos+1) = savedchar;
671 Handle complex substitutions:
672 xxx=yyy (replace xxx with yyy)
673 *xxx=yyy (replace up to and including xxx with yyy)
674 ~x (from x WCHARs in)
675 ~-x (from x WCHARs from the end)
676 ~x,y (from x WCHARs in for y WCHARacters)
677 ~x,-y (from x WCHARs in until y WCHARacters from the end)
680 /* ~ is substring manipulation */
681 if (savedchar == '~') {
683 int substrposition, substrlength = 0;
684 WCHAR *commapos = strchrW(colonpos+2, ',');
685 WCHAR *startCopy;
687 substrposition = atolW(colonpos+2);
688 if (commapos) substrlength = atolW(commapos+1);
690 /* Check bounds */
691 if (substrposition >= 0) {
692 startCopy = &thisVarContents[min(substrposition, len)];
693 } else {
694 startCopy = &thisVarContents[max(0, len+substrposition-1)];
697 if (commapos == NULL) {
698 /* Copy the lot */
699 WCMD_strsubstW(start, endOfVar + 1, startCopy, -1);
700 } else if (substrlength < 0) {
702 int copybytes = (len+substrlength-1)-(startCopy-thisVarContents);
703 if (copybytes > len) copybytes = len;
704 else if (copybytes < 0) copybytes = 0;
705 WCMD_strsubstW(start, endOfVar + 1, startCopy, copybytes);
706 } else {
707 WCMD_strsubstW(start, endOfVar + 1, startCopy, substrlength);
710 return start;
712 /* search and replace manipulation */
713 } else {
714 WCHAR *equalspos = strstrW(colonpos, equalsW);
715 WCHAR *replacewith = equalspos+1;
716 WCHAR *found = NULL;
717 WCHAR *searchIn;
718 WCHAR *searchFor;
720 if (equalspos == NULL) return start+1;
721 s = WCMD_strdupW(endOfVar + 1);
723 /* Null terminate both strings */
724 thisVar[strlenW(thisVar)-1] = 0x00;
725 *equalspos = 0x00;
727 /* Since we need to be case insensitive, copy the 2 buffers */
728 searchIn = WCMD_strdupW(thisVarContents);
729 CharUpperBuffW(searchIn, strlenW(thisVarContents));
730 searchFor = WCMD_strdupW(colonpos+1);
731 CharUpperBuffW(searchFor, strlenW(colonpos+1));
733 /* Handle wildcard case */
734 if (*(colonpos+1) == '*') {
735 /* Search for string to replace */
736 found = strstrW(searchIn, searchFor+1);
738 if (found) {
739 /* Do replacement */
740 strcpyW(start, replacewith);
741 strcatW(start, thisVarContents + (found-searchIn) + strlenW(searchFor+1));
742 strcatW(start, s);
743 } else {
744 /* Copy as is */
745 strcpyW(start, thisVarContents);
746 strcatW(start, s);
749 } else {
750 /* Loop replacing all instances */
751 WCHAR *lastFound = searchIn;
752 WCHAR *outputposn = start;
754 *start = 0x00;
755 while ((found = strstrW(lastFound, searchFor))) {
756 lstrcpynW(outputposn,
757 thisVarContents + (lastFound-searchIn),
758 (found - lastFound)+1);
759 outputposn = outputposn + (found - lastFound);
760 strcatW(outputposn, replacewith);
761 outputposn = outputposn + strlenW(replacewith);
762 lastFound = found + strlenW(searchFor);
764 strcatW(outputposn,
765 thisVarContents + (lastFound-searchIn));
766 strcatW(outputposn, s);
768 HeapFree(GetProcessHeap(), 0, s);
769 HeapFree(GetProcessHeap(), 0, searchIn);
770 HeapFree(GetProcessHeap(), 0, searchFor);
771 return start;
773 return start+1;
776 /*****************************************************************************
777 * Expand the command. Native expands lines from batch programs as they are
778 * read in and not again, except for 'for' variable substitution.
779 * eg. As evidence, "echo %1 && shift && echo %1" or "echo %%path%%"
781 static void handleExpansion(WCHAR *cmd, BOOL justFors,
782 const WCHAR *forVariable, const WCHAR *forValue) {
784 /* For commands in a context (batch program): */
785 /* Expand environment variables in a batch file %{0-9} first */
786 /* including support for any ~ modifiers */
787 /* Additionally: */
788 /* Expand the DATE, TIME, CD, RANDOM and ERRORLEVEL special */
789 /* names allowing environment variable overrides */
790 /* NOTE: To support the %PATH:xxx% syntax, also perform */
791 /* manual expansion of environment variables here */
793 WCHAR *p = cmd;
794 WCHAR *t;
795 int i;
797 while ((p = strchrW(p, '%'))) {
799 WINE_TRACE("Translate command:%s %d (at: %s)\n",
800 wine_dbgstr_w(cmd), justFors, wine_dbgstr_w(p));
801 i = *(p+1) - '0';
803 /* Don't touch %% unless its in Batch */
804 if (!justFors && *(p+1) == '%') {
805 if (context) {
806 WCMD_strsubstW(p, p+1, NULL, 0);
808 p+=1;
810 /* Replace %~ modifications if in batch program */
811 } else if (*(p+1) == '~') {
812 WCMD_HandleTildaModifiers(&p, forVariable, forValue, justFors);
813 p++;
815 /* Replace use of %0...%9 if in batch program*/
816 } else if (!justFors && context && (i >= 0) && (i <= 9)) {
817 t = WCMD_parameter (context -> command, i + context -> shift_count[i], NULL);
818 WCMD_strsubstW(p, p+2, t, -1);
820 /* Replace use of %* if in batch program*/
821 } else if (!justFors && context && *(p+1)=='*') {
822 WCHAR *startOfParms = NULL;
823 t = WCMD_parameter (context -> command, 1, &startOfParms);
824 if (startOfParms != NULL)
825 WCMD_strsubstW(p, p+2, startOfParms, -1);
826 else
827 WCMD_strsubstW(p, p+2, NULL, 0);
829 } else if (forVariable &&
830 (CompareStringW(LOCALE_USER_DEFAULT,
831 SORT_STRINGSORT,
833 strlenW(forVariable),
834 forVariable, -1) == CSTR_EQUAL)) {
835 WCMD_strsubstW(p, p + strlenW(forVariable), forValue, -1);
837 } else if (!justFors) {
838 p = WCMD_expand_envvar(p, forVariable, forValue);
840 /* In a FOR loop, see if this is the variable to replace */
841 } else { /* Ignore %'s on second pass of batch program */
842 p++;
846 return;
850 /*******************************************************************
851 * WCMD_parse - parse a command into parameters and qualifiers.
853 * On exit, all qualifiers are concatenated into q, the first string
854 * not beginning with "/" is in p1 and the
855 * second in p2. Any subsequent non-qualifier strings are lost.
856 * Parameters in quotes are handled.
858 static void WCMD_parse (const WCHAR *s, WCHAR *q, WCHAR *p1, WCHAR *p2)
860 int p = 0;
862 *q = *p1 = *p2 = '\0';
863 while (TRUE) {
864 switch (*s) {
865 case '/':
866 *q++ = *s++;
867 while ((*s != '\0') && (*s != ' ') && *s != '/') {
868 *q++ = toupperW (*s++);
870 *q = '\0';
871 break;
872 case ' ':
873 case '\t':
874 s++;
875 break;
876 case '"':
877 s++;
878 while ((*s != '\0') && (*s != '"')) {
879 if (p == 0) *p1++ = *s++;
880 else if (p == 1) *p2++ = *s++;
881 else s++;
883 if (p == 0) *p1 = '\0';
884 if (p == 1) *p2 = '\0';
885 p++;
886 if (*s == '"') s++;
887 break;
888 case '\0':
889 return;
890 default:
891 while ((*s != '\0') && (*s != ' ') && (*s != '\t')
892 && (*s != '=') && (*s != ',') ) {
893 if (p == 0) *p1++ = *s++;
894 else if (p == 1) *p2++ = *s++;
895 else s++;
897 /* Skip concurrent parms */
898 while ((*s == ' ') || (*s == '\t') || (*s == '=') || (*s == ',') ) s++;
900 if (p == 0) *p1 = '\0';
901 if (p == 1) *p2 = '\0';
902 p++;
907 static void init_msvcrt_io_block(STARTUPINFOW* st)
909 STARTUPINFOW st_p;
910 /* fetch the parent MSVCRT info block if any, so that the child can use the
911 * same handles as its grand-father
913 st_p.cb = sizeof(STARTUPINFOW);
914 GetStartupInfoW(&st_p);
915 st->cbReserved2 = st_p.cbReserved2;
916 st->lpReserved2 = st_p.lpReserved2;
917 if (st_p.cbReserved2 && st_p.lpReserved2)
919 /* Override the entries for fd 0,1,2 if we happened
920 * to change those std handles (this depends on the way cmd sets
921 * its new input & output handles)
923 size_t sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
924 BYTE* ptr = HeapAlloc(GetProcessHeap(), 0, sz);
925 if (ptr)
927 unsigned num = *(unsigned*)st_p.lpReserved2;
928 char* flags = (char*)(ptr + sizeof(unsigned));
929 HANDLE* handles = (HANDLE*)(flags + num * sizeof(char));
931 memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
932 st->cbReserved2 = sz;
933 st->lpReserved2 = ptr;
935 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
936 if (num <= 0 || (flags[0] & WX_OPEN))
938 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
939 flags[0] |= WX_OPEN;
941 if (num <= 1 || (flags[1] & WX_OPEN))
943 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
944 flags[1] |= WX_OPEN;
946 if (num <= 2 || (flags[2] & WX_OPEN))
948 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
949 flags[2] |= WX_OPEN;
951 #undef WX_OPEN
956 /******************************************************************************
957 * WCMD_run_program
959 * Execute a command line as an external program. Must allow recursion.
961 * Precedence:
962 * Manual testing under windows shows PATHEXT plays a key part in this,
963 * and the search algorithm and precedence appears to be as follows.
965 * Search locations:
966 * If directory supplied on command, just use that directory
967 * If extension supplied on command, look for that explicit name first
968 * Otherwise, search in each directory on the path
969 * Precedence:
970 * If extension supplied on command, look for that explicit name first
971 * Then look for supplied name .* (even if extension supplied, so
972 * 'garbage.exe' will match 'garbage.exe.cmd')
973 * If any found, cycle through PATHEXT looking for name.exe one by one
974 * Launching
975 * Once a match has been found, it is launched - Code currently uses
976 * findexecutable to achieve this which is left untouched.
979 void WCMD_run_program (WCHAR *command, int called) {
981 WCHAR temp[MAX_PATH];
982 WCHAR pathtosearch[MAXSTRING];
983 WCHAR *pathposn;
984 WCHAR stemofsearch[MAX_PATH]; /* maximum allowed executable name is
985 MAX_PATH, including null character */
986 WCHAR *lastSlash;
987 WCHAR pathext[MAXSTRING];
988 BOOL extensionsupplied = FALSE;
989 BOOL launched = FALSE;
990 BOOL status;
991 BOOL assumeInternal = FALSE;
992 DWORD len;
993 static const WCHAR envPath[] = {'P','A','T','H','\0'};
994 static const WCHAR envPathExt[] = {'P','A','T','H','E','X','T','\0'};
995 static const WCHAR delims[] = {'/','\\',':','\0'};
997 WCMD_parse (command, quals, param1, param2); /* Quick way to get the filename */
998 if (!(*param1) && !(*param2))
999 return;
1001 /* Calculate the search path and stem to search for */
1002 if (strpbrkW (param1, delims) == NULL) { /* No explicit path given, search path */
1003 static const WCHAR curDir[] = {'.',';','\0'};
1004 strcpyW(pathtosearch, curDir);
1005 len = GetEnvironmentVariableW(envPath, &pathtosearch[2], (sizeof(pathtosearch)/sizeof(WCHAR))-2);
1006 if ((len == 0) || (len >= (sizeof(pathtosearch)/sizeof(WCHAR)) - 2)) {
1007 static const WCHAR curDir[] = {'.','\0'};
1008 strcpyW (pathtosearch, curDir);
1010 if (strchrW(param1, '.') != NULL) extensionsupplied = TRUE;
1011 if (strlenW(param1) >= MAX_PATH)
1013 WCMD_output_asis(WCMD_LoadMessage(WCMD_LINETOOLONG));
1014 return;
1017 strcpyW(stemofsearch, param1);
1019 } else {
1021 /* Convert eg. ..\fred to include a directory by removing file part */
1022 GetFullPathNameW(param1, sizeof(pathtosearch)/sizeof(WCHAR), pathtosearch, NULL);
1023 lastSlash = strrchrW(pathtosearch, '\\');
1024 if (lastSlash && strchrW(lastSlash, '.') != NULL) extensionsupplied = TRUE;
1025 strcpyW(stemofsearch, lastSlash+1);
1027 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
1028 c:\windows\a.bat syntax */
1029 if (lastSlash) *(lastSlash + 1) = 0x00;
1032 /* Now extract PATHEXT */
1033 len = GetEnvironmentVariableW(envPathExt, pathext, sizeof(pathext)/sizeof(WCHAR));
1034 if ((len == 0) || (len >= (sizeof(pathext)/sizeof(WCHAR)))) {
1035 static const WCHAR dfltPathExt[] = {'.','b','a','t',';',
1036 '.','c','o','m',';',
1037 '.','c','m','d',';',
1038 '.','e','x','e','\0'};
1039 strcpyW (pathext, dfltPathExt);
1042 /* Loop through the search path, dir by dir */
1043 pathposn = pathtosearch;
1044 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch),
1045 wine_dbgstr_w(stemofsearch));
1046 while (!launched && pathposn) {
1048 WCHAR thisDir[MAX_PATH] = {'\0'};
1049 WCHAR *pos = NULL;
1050 BOOL found = FALSE;
1051 static const WCHAR slashW[] = {'\\','\0'};
1053 /* Work on the first directory on the search path */
1054 pos = strchrW(pathposn, ';');
1055 if (pos) {
1056 memcpy(thisDir, pathposn, (pos-pathposn) * sizeof(WCHAR));
1057 thisDir[(pos-pathposn)] = 0x00;
1058 pathposn = pos+1;
1060 } else {
1061 strcpyW(thisDir, pathposn);
1062 pathposn = NULL;
1065 /* Since you can have eg. ..\.. on the path, need to expand
1066 to full information */
1067 strcpyW(temp, thisDir);
1068 GetFullPathNameW(temp, MAX_PATH, thisDir, NULL);
1070 /* 1. If extension supplied, see if that file exists */
1071 strcatW(thisDir, slashW);
1072 strcatW(thisDir, stemofsearch);
1073 pos = &thisDir[strlenW(thisDir)]; /* Pos = end of name */
1075 /* 1. If extension supplied, see if that file exists */
1076 if (extensionsupplied) {
1077 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1078 found = TRUE;
1082 /* 2. Any .* matches? */
1083 if (!found) {
1084 HANDLE h;
1085 WIN32_FIND_DATAW finddata;
1086 static const WCHAR allFiles[] = {'.','*','\0'};
1088 strcatW(thisDir,allFiles);
1089 h = FindFirstFileW(thisDir, &finddata);
1090 FindClose(h);
1091 if (h != INVALID_HANDLE_VALUE) {
1093 WCHAR *thisExt = pathext;
1095 /* 3. Yes - Try each path ext */
1096 while (thisExt) {
1097 WCHAR *nextExt = strchrW(thisExt, ';');
1099 if (nextExt) {
1100 memcpy(pos, thisExt, (nextExt-thisExt) * sizeof(WCHAR));
1101 pos[(nextExt-thisExt)] = 0x00;
1102 thisExt = nextExt+1;
1103 } else {
1104 strcpyW(pos, thisExt);
1105 thisExt = NULL;
1108 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1109 found = TRUE;
1110 thisExt = NULL;
1116 /* Internal programs won't be picked up by this search, so even
1117 though not found, try one last createprocess and wait for it
1118 to complete.
1119 Note: Ideally we could tell between a console app (wait) and a
1120 windows app, but the API's for it fail in this case */
1121 if (!found && pathposn == NULL) {
1122 WINE_TRACE("ASSUMING INTERNAL\n");
1123 assumeInternal = TRUE;
1124 } else {
1125 WINE_TRACE("Found as %s\n", wine_dbgstr_w(thisDir));
1128 /* Once found, launch it */
1129 if (found || assumeInternal) {
1130 STARTUPINFOW st;
1131 PROCESS_INFORMATION pe;
1132 SHFILEINFOW psfi;
1133 DWORD console;
1134 HINSTANCE hinst;
1135 WCHAR *ext = strrchrW( thisDir, '.' );
1136 static const WCHAR batExt[] = {'.','b','a','t','\0'};
1137 static const WCHAR cmdExt[] = {'.','c','m','d','\0'};
1139 launched = TRUE;
1141 /* Special case BAT and CMD */
1142 if (ext && !strcmpiW(ext, batExt)) {
1143 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
1144 return;
1145 } else if (ext && !strcmpiW(ext, cmdExt)) {
1146 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
1147 return;
1148 } else {
1150 /* thisDir contains the file to be launched, but with what?
1151 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
1152 hinst = FindExecutableW (thisDir, NULL, temp);
1153 if ((INT_PTR)hinst < 32)
1154 console = 0;
1155 else
1156 console = SHGetFileInfoW(temp, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
1158 ZeroMemory (&st, sizeof(STARTUPINFOW));
1159 st.cb = sizeof(STARTUPINFOW);
1160 init_msvcrt_io_block(&st);
1162 /* Launch the process and if a CUI wait on it to complete
1163 Note: Launching internal wine processes cannot specify a full path to exe */
1164 status = CreateProcessW(assumeInternal?NULL : thisDir,
1165 command, NULL, NULL, TRUE, 0, NULL, NULL, &st, &pe);
1166 if ((opt_c || opt_k) && !opt_s && !status
1167 && GetLastError()==ERROR_FILE_NOT_FOUND && command[0]=='\"') {
1168 /* strip first and last quote WCHARacters and try again */
1169 WCMD_opt_s_strip_quotes(command);
1170 opt_s=1;
1171 WCMD_run_program(command, called);
1172 return;
1175 if (!status)
1176 break;
1178 if (!assumeInternal && !console) errorlevel = 0;
1179 else
1181 /* Always wait when called in a batch program context */
1182 if (assumeInternal || context || !HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
1183 GetExitCodeProcess (pe.hProcess, &errorlevel);
1184 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
1186 CloseHandle(pe.hProcess);
1187 CloseHandle(pe.hThread);
1188 return;
1193 /* Not found anywhere - give up */
1194 SetLastError(ERROR_FILE_NOT_FOUND);
1195 WCMD_print_error ();
1197 /* If a command fails to launch, it sets errorlevel 9009 - which
1198 does not seem to have any associated constant definition */
1199 errorlevel = 9009;
1200 return;
1204 /*****************************************************************************
1205 * Process one command. If the command is EXIT this routine does not return.
1206 * We will recurse through here executing batch files.
1208 void WCMD_execute (const WCHAR *command, const WCHAR *redirects,
1209 const WCHAR *forVariable, const WCHAR *forValue,
1210 CMD_LIST **cmdList)
1212 WCHAR *cmd, *p, *redir;
1213 int status, i;
1214 DWORD count, creationDisposition;
1215 HANDLE h;
1216 WCHAR *whichcmd;
1217 SECURITY_ATTRIBUTES sa;
1218 WCHAR *new_cmd = NULL;
1219 WCHAR *new_redir = NULL;
1220 HANDLE old_stdhandles[3] = {GetStdHandle (STD_INPUT_HANDLE),
1221 GetStdHandle (STD_OUTPUT_HANDLE),
1222 GetStdHandle (STD_ERROR_HANDLE)};
1223 DWORD idx_stdhandles[3] = {STD_INPUT_HANDLE,
1224 STD_OUTPUT_HANDLE,
1225 STD_ERROR_HANDLE};
1226 BOOL piped = FALSE;
1228 WINE_TRACE("command on entry:%s (%p), with forVariable '%s'='%s'\n",
1229 wine_dbgstr_w(command), cmdList,
1230 wine_dbgstr_w(forVariable), wine_dbgstr_w(forValue));
1232 /* If the next command is a pipe then we implement pipes by redirecting
1233 the output from this command to a temp file and input into the
1234 next command from that temp file.
1235 FIXME: Use of named pipes would make more sense here as currently this
1236 process has to finish before the next one can start but this requires
1237 a change to not wait for the first app to finish but rather the pipe */
1238 if (cmdList && (*cmdList)->nextcommand &&
1239 (*cmdList)->nextcommand->prevDelim == CMD_PIPE) {
1241 WCHAR temp_path[MAX_PATH];
1242 static const WCHAR cmdW[] = {'C','M','D','\0'};
1244 /* Remember piping is in action */
1245 WINE_TRACE("Output needs to be piped\n");
1246 piped = TRUE;
1248 /* Generate a unique temporary filename */
1249 GetTempPathW(sizeof(temp_path)/sizeof(WCHAR), temp_path);
1250 GetTempFileNameW(temp_path, cmdW, 0, (*cmdList)->nextcommand->pipeFile);
1251 WINE_TRACE("Using temporary file of %s\n",
1252 wine_dbgstr_w((*cmdList)->nextcommand->pipeFile));
1255 /* Move copy of the command onto the heap so it can be expanded */
1256 new_cmd = HeapAlloc( GetProcessHeap(), 0, MAXSTRING * sizeof(WCHAR));
1257 if (!new_cmd)
1259 WINE_ERR("Could not allocate memory for new_cmd\n");
1260 return;
1262 strcpyW(new_cmd, command);
1264 /* Move copy of the redirects onto the heap so it can be expanded */
1265 new_redir = HeapAlloc( GetProcessHeap(), 0, MAXSTRING * sizeof(WCHAR));
1266 if (!new_redir)
1268 WINE_ERR("Could not allocate memory for new_redir\n");
1269 HeapFree( GetProcessHeap(), 0, new_cmd );
1270 return;
1273 /* If piped output, send stdout to the pipe by appending >filename to redirects */
1274 if (piped) {
1275 static const WCHAR redirOut[] = {'%','s',' ','>',' ','%','s','\0'};
1276 wsprintfW (new_redir, redirOut, redirects, (*cmdList)->nextcommand->pipeFile);
1277 WINE_TRACE("Redirects now %s\n", wine_dbgstr_w(new_redir));
1278 } else {
1279 strcpyW(new_redir, redirects);
1282 /* Expand variables in command line mode only (batch mode will
1283 be expanded as the line is read in, except for 'for' loops) */
1284 handleExpansion(new_cmd, (context != NULL), forVariable, forValue);
1285 handleExpansion(new_redir, (context != NULL), forVariable, forValue);
1286 cmd = new_cmd;
1289 * Changing default drive has to be handled as a special case.
1292 if ((cmd[1] == ':') && IsCharAlphaW(cmd[0]) && (strlenW(cmd) == 2)) {
1293 WCHAR envvar[5];
1294 WCHAR dir[MAX_PATH];
1296 /* According to MSDN CreateProcess docs, special env vars record
1297 the current directory on each drive, in the form =C:
1298 so see if one specified, and if so go back to it */
1299 strcpyW(envvar, equalsW);
1300 strcatW(envvar, cmd);
1301 if (GetEnvironmentVariableW(envvar, dir, MAX_PATH) == 0) {
1302 static const WCHAR fmt[] = {'%','s','\\','\0'};
1303 wsprintfW(cmd, fmt, cmd);
1304 WINE_TRACE("No special directory settings, using dir of %s\n", wine_dbgstr_w(cmd));
1306 WINE_TRACE("Got directory %s as %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(cmd));
1307 status = SetCurrentDirectoryW(cmd);
1308 if (!status) WCMD_print_error ();
1309 HeapFree( GetProcessHeap(), 0, cmd );
1310 HeapFree( GetProcessHeap(), 0, new_redir );
1311 return;
1314 sa.nLength = sizeof(sa);
1315 sa.lpSecurityDescriptor = NULL;
1316 sa.bInheritHandle = TRUE;
1319 * Redirect stdin, stdout and/or stderr if required.
1322 /* STDIN could come from a preceding pipe, so delete on close if it does */
1323 if (cmdList && (*cmdList)->pipeFile[0] != 0x00) {
1324 WINE_TRACE("Input coming from %s\n", wine_dbgstr_w((*cmdList)->pipeFile));
1325 h = CreateFileW((*cmdList)->pipeFile, GENERIC_READ,
1326 FILE_SHARE_READ, &sa, OPEN_EXISTING,
1327 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL);
1328 if (h == INVALID_HANDLE_VALUE) {
1329 WCMD_print_error ();
1330 HeapFree( GetProcessHeap(), 0, cmd );
1331 HeapFree( GetProcessHeap(), 0, new_redir );
1332 return;
1334 SetStdHandle (STD_INPUT_HANDLE, h);
1336 /* No need to remember the temporary name any longer once opened */
1337 (*cmdList)->pipeFile[0] = 0x00;
1339 /* Otherwise STDIN could come from a '<' redirect */
1340 } else if ((p = strchrW(new_redir,'<')) != NULL) {
1341 h = CreateFileW(WCMD_parameter (++p, 0, NULL), GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
1342 FILE_ATTRIBUTE_NORMAL, NULL);
1343 if (h == INVALID_HANDLE_VALUE) {
1344 WCMD_print_error ();
1345 HeapFree( GetProcessHeap(), 0, cmd );
1346 HeapFree( GetProcessHeap(), 0, new_redir );
1347 return;
1349 SetStdHandle (STD_INPUT_HANDLE, h);
1352 /* Scan the whole command looking for > and 2> */
1353 redir = new_redir;
1354 while (redir != NULL && ((p = strchrW(redir,'>')) != NULL)) {
1355 int handle = 0;
1357 if (*(p-1)!='2') {
1358 handle = 1;
1359 } else {
1360 handle = 2;
1363 p++;
1364 if ('>' == *p) {
1365 creationDisposition = OPEN_ALWAYS;
1366 p++;
1368 else {
1369 creationDisposition = CREATE_ALWAYS;
1372 /* Add support for 2>&1 */
1373 redir = p;
1374 if (*p == '&') {
1375 int idx = *(p+1) - '0';
1377 if (DuplicateHandle(GetCurrentProcess(),
1378 GetStdHandle(idx_stdhandles[idx]),
1379 GetCurrentProcess(),
1381 0, TRUE, DUPLICATE_SAME_ACCESS) == 0) {
1382 WINE_FIXME("Duplicating handle failed with gle %d\n", GetLastError());
1384 WINE_TRACE("Redirect %d (%p) to %d (%p)\n", handle, GetStdHandle(idx_stdhandles[idx]), idx, h);
1386 } else {
1387 WCHAR *param = WCMD_parameter (p, 0, NULL);
1388 h = CreateFileW(param, GENERIC_WRITE, 0, &sa, creationDisposition,
1389 FILE_ATTRIBUTE_NORMAL, NULL);
1390 if (h == INVALID_HANDLE_VALUE) {
1391 WCMD_print_error ();
1392 HeapFree( GetProcessHeap(), 0, cmd );
1393 HeapFree( GetProcessHeap(), 0, new_redir );
1394 return;
1396 if (SetFilePointer (h, 0, NULL, FILE_END) ==
1397 INVALID_SET_FILE_POINTER) {
1398 WCMD_print_error ();
1400 WINE_TRACE("Redirect %d to '%s' (%p)\n", handle, wine_dbgstr_w(param), h);
1403 SetStdHandle (idx_stdhandles[handle], h);
1407 * Strip leading whitespaces, and a '@' if supplied
1409 whichcmd = WCMD_skip_leading_spaces(cmd);
1410 WINE_TRACE("Command: '%s'\n", wine_dbgstr_w(cmd));
1411 if (whichcmd[0] == '@') whichcmd++;
1414 * Check if the command entered is internal. If it is, pass the rest of the
1415 * line down to the command. If not try to run a program.
1418 count = 0;
1419 while (IsCharAlphaNumericW(whichcmd[count])) {
1420 count++;
1422 for (i=0; i<=WCMD_EXIT; i++) {
1423 if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1424 whichcmd, count, inbuilt[i], -1) == CSTR_EQUAL) break;
1426 p = WCMD_skip_leading_spaces (&whichcmd[count]);
1427 WCMD_parse (p, quals, param1, param2);
1428 WINE_TRACE("param1: %s, param2: %s\n", wine_dbgstr_w(param1), wine_dbgstr_w(param2));
1430 if (i <= WCMD_EXIT && (p[0] == '/') && (p[1] == '?')) {
1431 /* this is a help request for a builtin program */
1432 i = WCMD_HELP;
1433 memcpy(p, whichcmd, count * sizeof(WCHAR));
1434 p[count] = '\0';
1438 switch (i) {
1440 case WCMD_ATTRIB:
1441 WCMD_setshow_attrib ();
1442 break;
1443 case WCMD_CALL:
1444 WCMD_call (p);
1445 break;
1446 case WCMD_CD:
1447 case WCMD_CHDIR:
1448 WCMD_setshow_default (p);
1449 break;
1450 case WCMD_CLS:
1451 WCMD_clear_screen ();
1452 break;
1453 case WCMD_COPY:
1454 WCMD_copy ();
1455 break;
1456 case WCMD_CTTY:
1457 WCMD_change_tty ();
1458 break;
1459 case WCMD_DATE:
1460 WCMD_setshow_date ();
1461 break;
1462 case WCMD_DEL:
1463 case WCMD_ERASE:
1464 WCMD_delete (p);
1465 break;
1466 case WCMD_DIR:
1467 WCMD_directory (p);
1468 break;
1469 case WCMD_ECHO:
1470 WCMD_echo(&whichcmd[count]);
1471 break;
1472 case WCMD_FOR:
1473 WCMD_for (p, cmdList);
1474 break;
1475 case WCMD_GOTO:
1476 WCMD_goto (cmdList);
1477 break;
1478 case WCMD_HELP:
1479 WCMD_give_help (p);
1480 break;
1481 case WCMD_IF:
1482 WCMD_if (p, cmdList);
1483 break;
1484 case WCMD_LABEL:
1485 WCMD_volume (1, p);
1486 break;
1487 case WCMD_MD:
1488 case WCMD_MKDIR:
1489 WCMD_create_dir (p);
1490 break;
1491 case WCMD_MOVE:
1492 WCMD_move ();
1493 break;
1494 case WCMD_PATH:
1495 WCMD_setshow_path (p);
1496 break;
1497 case WCMD_PAUSE:
1498 WCMD_pause ();
1499 break;
1500 case WCMD_PROMPT:
1501 WCMD_setshow_prompt ();
1502 break;
1503 case WCMD_REM:
1504 break;
1505 case WCMD_REN:
1506 case WCMD_RENAME:
1507 WCMD_rename ();
1508 break;
1509 case WCMD_RD:
1510 case WCMD_RMDIR:
1511 WCMD_remove_dir (p);
1512 break;
1513 case WCMD_SETLOCAL:
1514 WCMD_setlocal(p);
1515 break;
1516 case WCMD_ENDLOCAL:
1517 WCMD_endlocal();
1518 break;
1519 case WCMD_SET:
1520 WCMD_setshow_env (p);
1521 break;
1522 case WCMD_SHIFT:
1523 WCMD_shift (p);
1524 break;
1525 case WCMD_TIME:
1526 WCMD_setshow_time ();
1527 break;
1528 case WCMD_TITLE:
1529 if (strlenW(&whichcmd[count]) > 0)
1530 WCMD_title(&whichcmd[count+1]);
1531 break;
1532 case WCMD_TYPE:
1533 WCMD_type (p);
1534 break;
1535 case WCMD_VER:
1536 WCMD_output(newline);
1537 WCMD_version ();
1538 break;
1539 case WCMD_VERIFY:
1540 WCMD_verify (p);
1541 break;
1542 case WCMD_VOL:
1543 WCMD_volume (0, p);
1544 break;
1545 case WCMD_PUSHD:
1546 WCMD_pushd(p);
1547 break;
1548 case WCMD_POPD:
1549 WCMD_popd();
1550 break;
1551 case WCMD_ASSOC:
1552 WCMD_assoc(p, TRUE);
1553 break;
1554 case WCMD_COLOR:
1555 WCMD_color();
1556 break;
1557 case WCMD_FTYPE:
1558 WCMD_assoc(p, FALSE);
1559 break;
1560 case WCMD_MORE:
1561 WCMD_more(p);
1562 break;
1563 case WCMD_CHOICE:
1564 WCMD_choice(p);
1565 break;
1566 case WCMD_EXIT:
1567 WCMD_exit (cmdList);
1568 break;
1569 default:
1570 WCMD_run_program (whichcmd, 0);
1572 HeapFree( GetProcessHeap(), 0, cmd );
1573 HeapFree( GetProcessHeap(), 0, new_redir );
1575 /* Restore old handles */
1576 for (i=0; i<3; i++) {
1577 if (old_stdhandles[i] != GetStdHandle(idx_stdhandles[i])) {
1578 CloseHandle (GetStdHandle (idx_stdhandles[i]));
1579 SetStdHandle (idx_stdhandles[i], old_stdhandles[i]);
1583 /*************************************************************************
1584 * WCMD_LoadMessage
1585 * Load a string from the resource file, handling any error
1586 * Returns string retrieved from resource file
1588 WCHAR *WCMD_LoadMessage(UINT id) {
1589 static WCHAR msg[2048];
1590 static const WCHAR failedMsg[] = {'F','a','i','l','e','d','!','\0'};
1592 if (!LoadStringW(GetModuleHandleW(NULL), id, msg, sizeof(msg)/sizeof(WCHAR))) {
1593 WINE_FIXME("LoadString failed with %d\n", GetLastError());
1594 strcpyW(msg, failedMsg);
1596 return msg;
1599 /***************************************************************************
1600 * WCMD_DumpCommands
1602 * Dumps out the parsed command line to ensure syntax is correct
1604 static void WCMD_DumpCommands(CMD_LIST *commands) {
1605 CMD_LIST *thisCmd = commands;
1607 WINE_TRACE("Parsed line:\n");
1608 while (thisCmd != NULL) {
1609 WINE_TRACE("%p %d %2.2d %p %s Redir:%s\n",
1610 thisCmd,
1611 thisCmd->prevDelim,
1612 thisCmd->bracketDepth,
1613 thisCmd->nextcommand,
1614 wine_dbgstr_w(thisCmd->command),
1615 wine_dbgstr_w(thisCmd->redirects));
1616 thisCmd = thisCmd->nextcommand;
1620 /***************************************************************************
1621 * WCMD_addCommand
1623 * Adds a command to the current command list
1625 static void WCMD_addCommand(WCHAR *command, int *commandLen,
1626 WCHAR *redirs, int *redirLen,
1627 WCHAR **copyTo, int **copyToLen,
1628 CMD_DELIMITERS prevDelim, int curDepth,
1629 CMD_LIST **lastEntry, CMD_LIST **output) {
1631 CMD_LIST *thisEntry = NULL;
1633 /* Allocate storage for command */
1634 thisEntry = HeapAlloc(GetProcessHeap(), 0, sizeof(CMD_LIST));
1636 /* Copy in the command */
1637 if (command) {
1638 thisEntry->command = HeapAlloc(GetProcessHeap(), 0,
1639 (*commandLen+1) * sizeof(WCHAR));
1640 memcpy(thisEntry->command, command, *commandLen * sizeof(WCHAR));
1641 thisEntry->command[*commandLen] = 0x00;
1643 /* Copy in the redirects */
1644 thisEntry->redirects = HeapAlloc(GetProcessHeap(), 0,
1645 (*redirLen+1) * sizeof(WCHAR));
1646 memcpy(thisEntry->redirects, redirs, *redirLen * sizeof(WCHAR));
1647 thisEntry->redirects[*redirLen] = 0x00;
1648 thisEntry->pipeFile[0] = 0x00;
1650 /* Reset the lengths */
1651 *commandLen = 0;
1652 *redirLen = 0;
1653 *copyToLen = commandLen;
1654 *copyTo = command;
1656 } else {
1657 thisEntry->command = NULL;
1658 thisEntry->redirects = NULL;
1659 thisEntry->pipeFile[0] = 0x00;
1662 /* Fill in other fields */
1663 thisEntry->nextcommand = NULL;
1664 thisEntry->prevDelim = prevDelim;
1665 thisEntry->bracketDepth = curDepth;
1666 if (*lastEntry) {
1667 (*lastEntry)->nextcommand = thisEntry;
1668 } else {
1669 *output = thisEntry;
1671 *lastEntry = thisEntry;
1675 /***************************************************************************
1676 * WCMD_IsEndQuote
1678 * Checks if the quote pointed to is the end-quote.
1680 * Quotes end if:
1682 * 1) The current parameter ends at EOL or at the beginning
1683 * of a redirection or pipe and not in a quote section.
1685 * 2) If the next character is a space and not in a quote section.
1687 * Returns TRUE if this is an end quote, and FALSE if it is not.
1690 static BOOL WCMD_IsEndQuote(const WCHAR *quote, int quoteIndex)
1692 int quoteCount = quoteIndex;
1693 int i;
1695 /* If we are not in a quoted section, then we are not an end-quote */
1696 if(quoteIndex == 0)
1698 return FALSE;
1701 /* Check how many quotes are left for this parameter */
1702 for(i=0;quote[i];i++)
1704 if(quote[i] == '"')
1706 quoteCount++;
1709 /* Quote counting ends at EOL, redirection, space or pipe if current quote is complete */
1710 else if(((quoteCount % 2) == 0)
1711 && ((quote[i] == '<') || (quote[i] == '>') || (quote[i] == '|') || (quote[i] == ' ')))
1713 break;
1717 /* If the quote is part of the last part of a series of quotes-on-quotes, then it must
1718 be an end-quote */
1719 if(quoteIndex >= (quoteCount / 2))
1721 return TRUE;
1724 /* No cigar */
1725 return FALSE;
1728 /***************************************************************************
1729 * WCMD_ReadAndParseLine
1731 * Either uses supplied input or
1732 * Reads a file from the handle, and then...
1733 * Parse the text buffer, splitting into separate commands
1734 * - unquoted && strings split 2 commands but the 2nd is flagged as
1735 * following an &&
1736 * - ( as the first character just ups the bracket depth
1737 * - unquoted ) when bracket depth > 0 terminates a bracket and
1738 * adds a CMD_LIST structure with null command
1739 * - Anything else gets put into the command string (including
1740 * redirects)
1742 WCHAR *WCMD_ReadAndParseLine(const WCHAR *optionalcmd, CMD_LIST **output, HANDLE readFrom) {
1744 WCHAR *curPos;
1745 int inQuotes = 0;
1746 WCHAR curString[MAXSTRING];
1747 int curStringLen = 0;
1748 WCHAR curRedirs[MAXSTRING];
1749 int curRedirsLen = 0;
1750 WCHAR *curCopyTo;
1751 int *curLen;
1752 int curDepth = 0;
1753 CMD_LIST *lastEntry = NULL;
1754 CMD_DELIMITERS prevDelim = CMD_NONE;
1755 static WCHAR *extraSpace = NULL; /* Deliberately never freed */
1756 static const WCHAR remCmd[] = {'r','e','m'};
1757 static const WCHAR forCmd[] = {'f','o','r'};
1758 static const WCHAR ifCmd[] = {'i','f'};
1759 static const WCHAR ifElse[] = {'e','l','s','e'};
1760 BOOL inRem = FALSE;
1761 BOOL inFor = FALSE;
1762 BOOL inIn = FALSE;
1763 BOOL inIf = FALSE;
1764 BOOL inElse= FALSE;
1765 BOOL onlyWhiteSpace = FALSE;
1766 BOOL lastWasWhiteSpace = FALSE;
1767 BOOL lastWasDo = FALSE;
1768 BOOL lastWasIn = FALSE;
1769 BOOL lastWasElse = FALSE;
1770 BOOL lastWasRedirect = TRUE;
1772 /* Allocate working space for a command read from keyboard, file etc */
1773 if (!extraSpace)
1774 extraSpace = HeapAlloc(GetProcessHeap(), 0, (MAXSTRING+1) * sizeof(WCHAR));
1775 if (!extraSpace)
1777 WINE_ERR("Could not allocate memory for extraSpace\n");
1778 return NULL;
1781 /* If initial command read in, use that, otherwise get input from handle */
1782 if (optionalcmd != NULL) {
1783 strcpyW(extraSpace, optionalcmd);
1784 } else if (readFrom == INVALID_HANDLE_VALUE) {
1785 WINE_FIXME("No command nor handle supplied\n");
1786 } else {
1787 if (WCMD_fgets(extraSpace, MAXSTRING, readFrom) == NULL) return NULL;
1789 curPos = extraSpace;
1791 /* Handle truncated input - issue warning */
1792 if (strlenW(extraSpace) == MAXSTRING -1) {
1793 WCMD_output_asis(WCMD_LoadMessage(WCMD_TRUNCATEDLINE));
1794 WCMD_output_asis(extraSpace);
1795 WCMD_output_asis(newline);
1798 /* Replace env vars if in a batch context */
1799 if (context) handleExpansion(extraSpace, FALSE, NULL, NULL);
1800 /* Show prompt before batch line IF echo is on and in batch program */
1801 if (context && echo_mode && extraSpace[0] && (extraSpace[0] != '@')) {
1802 static const WCHAR spc[]={' ','\0'};
1803 static const WCHAR echoDot[] = {'e','c','h','o','.'};
1804 static const WCHAR echoCol[] = {'e','c','h','o',':'};
1805 const DWORD len = sizeof(echoDot)/sizeof(echoDot[0]);
1806 DWORD curr_size = strlenW(extraSpace);
1807 DWORD min_len = (curr_size < len ? curr_size : len);
1808 WCMD_show_prompt();
1809 WCMD_output_asis(extraSpace);
1810 /* I don't know why Windows puts a space here but it does */
1811 /* Except for lines starting with 'echo.' or 'echo:'. Ask MS why */
1812 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1813 extraSpace, min_len, echoDot, len) != CSTR_EQUAL
1814 && CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1815 extraSpace, min_len, echoCol, len) != CSTR_EQUAL)
1817 WCMD_output_asis(spc);
1819 WCMD_output_asis(newline);
1822 /* Start with an empty string, copying to the command string */
1823 curStringLen = 0;
1824 curRedirsLen = 0;
1825 curCopyTo = curString;
1826 curLen = &curStringLen;
1827 lastWasRedirect = FALSE; /* Required for eg spaces between > and filename */
1829 /* Parse every character on the line being processed */
1830 while (*curPos != 0x00) {
1832 WCHAR thisChar;
1834 /* Debugging AID:
1835 WINE_TRACE("Looking at '%c' (len:%d, lws:%d, ows:%d)\n", *curPos, *curLen,
1836 lastWasWhiteSpace, onlyWhiteSpace);
1839 /* Certain commands need special handling */
1840 if (curStringLen == 0 && curCopyTo == curString) {
1841 static const WCHAR forDO[] = {'d','o'};
1843 /* If command starts with 'rem ', ignore any &&, ( etc. */
1844 if (WCMD_keyword_ws_found(remCmd, sizeof(remCmd)/sizeof(remCmd[0]), curPos)) {
1845 inRem = TRUE;
1847 } else if (WCMD_keyword_ws_found(forCmd, sizeof(forCmd)/sizeof(forCmd[0]), curPos)) {
1848 inFor = TRUE;
1850 /* If command starts with 'if ' or 'else ', handle ('s mid line. We should ensure this
1851 is only true in the command portion of the IF statement, but this
1852 should suffice for now
1853 FIXME: Silly syntax like "if 1(==1( (
1854 echo they equal
1855 )" will be parsed wrong */
1856 } else if (WCMD_keyword_ws_found(ifCmd, sizeof(ifCmd)/sizeof(ifCmd[0]), curPos)) {
1857 inIf = TRUE;
1859 } else if (WCMD_keyword_ws_found(ifElse, sizeof(ifElse)/sizeof(ifElse[0]), curPos)) {
1860 const int keyw_len = sizeof(ifElse)/sizeof(ifElse[0]) + 1;
1861 inElse = TRUE;
1862 lastWasElse = TRUE;
1863 onlyWhiteSpace = TRUE;
1864 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1865 (*curLen)+=keyw_len;
1866 curPos+=keyw_len;
1867 continue;
1869 /* In a for loop, the DO command will follow a close bracket followed by
1870 whitespace, followed by DO, ie closeBracket inserts a NULL entry, curLen
1871 is then 0, and all whitespace is skipped */
1872 } else if (inFor &&
1873 WCMD_keyword_ws_found(forDO, sizeof(forDO)/sizeof(forDO[0]), curPos)) {
1874 const int keyw_len = sizeof(forDO)/sizeof(forDO[0]) + 1;
1875 WINE_TRACE("Found 'DO '\n");
1876 lastWasDo = TRUE;
1877 onlyWhiteSpace = TRUE;
1878 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1879 (*curLen)+=keyw_len;
1880 curPos+=keyw_len;
1881 continue;
1883 } else if (curCopyTo == curString) {
1885 /* Special handling for the 'FOR' command */
1886 if (inFor && lastWasWhiteSpace) {
1887 static const WCHAR forIN[] = {'i','n'};
1889 WINE_TRACE("Found 'FOR ', comparing next parm: '%s'\n", wine_dbgstr_w(curPos));
1891 if (WCMD_keyword_ws_found(forIN, sizeof(forIN)/sizeof(forIN[0]), curPos)) {
1892 const int keyw_len = sizeof(forIN)/sizeof(forIN[0]) + 1;
1893 WINE_TRACE("Found 'IN '\n");
1894 lastWasIn = TRUE;
1895 onlyWhiteSpace = TRUE;
1896 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1897 (*curLen)+=keyw_len;
1898 curPos+=keyw_len;
1899 continue;
1904 /* Nothing 'ends' a REM statement and &&, quotes etc are ineffective,
1905 so just use the default processing ie skip character specific
1906 matching below */
1907 if (!inRem) thisChar = *curPos;
1908 else thisChar = 'X'; /* Character with no special processing */
1910 lastWasWhiteSpace = FALSE; /* Will be reset below */
1912 switch (thisChar) {
1914 case '=': /* drop through - ignore token delimiters at the start of a command */
1915 case ',': /* drop through - ignore token delimiters at the start of a command */
1916 case '\t':/* drop through - ignore token delimiters at the start of a command */
1917 case ' ':
1918 /* If a redirect in place, it ends here */
1919 if (!inQuotes && !lastWasRedirect) {
1921 /* If finishing off a redirect, add a whitespace delimiter */
1922 if (curCopyTo == curRedirs) {
1923 curCopyTo[(*curLen)++] = ' ';
1925 curCopyTo = curString;
1926 curLen = &curStringLen;
1928 if (*curLen > 0) {
1929 curCopyTo[(*curLen)++] = *curPos;
1932 /* Remember just processed whitespace */
1933 lastWasWhiteSpace = TRUE;
1935 break;
1937 case '>': /* drop through - handle redirect chars the same */
1938 case '<':
1939 /* Make a redirect start here */
1940 if (!inQuotes) {
1941 curCopyTo = curRedirs;
1942 curLen = &curRedirsLen;
1943 lastWasRedirect = TRUE;
1946 /* See if 1>, 2> etc, in which case we have some patching up
1947 to do */
1948 if (curPos != extraSpace &&
1949 *(curPos-1)>='1' && *(curPos-1)<='9') {
1951 curStringLen--;
1952 curString[curStringLen] = 0x00;
1953 curCopyTo[(*curLen)++] = *(curPos-1);
1956 curCopyTo[(*curLen)++] = *curPos;
1958 /* If a redirect is immediately followed by '&' (ie. 2>&1) then
1959 do not process that ampersand as an AND operator */
1960 if (thisChar == '>' && *(curPos+1) == '&') {
1961 curCopyTo[(*curLen)++] = *(curPos+1);
1962 curPos++;
1964 break;
1966 case '|': /* Pipe character only if not || */
1967 if (!inQuotes) {
1968 lastWasRedirect = FALSE;
1970 /* Add an entry to the command list */
1971 if (curStringLen > 0) {
1973 /* Add the current command */
1974 WCMD_addCommand(curString, &curStringLen,
1975 curRedirs, &curRedirsLen,
1976 &curCopyTo, &curLen,
1977 prevDelim, curDepth,
1978 &lastEntry, output);
1982 if (*(curPos+1) == '|') {
1983 curPos++; /* Skip other | */
1984 prevDelim = CMD_ONFAILURE;
1985 } else {
1986 prevDelim = CMD_PIPE;
1988 } else {
1989 curCopyTo[(*curLen)++] = *curPos;
1991 break;
1993 case '"': if (WCMD_IsEndQuote(curPos, inQuotes)) {
1994 inQuotes--;
1995 } else {
1996 inQuotes++; /* Quotes within quotes are fun! */
1998 curCopyTo[(*curLen)++] = *curPos;
1999 lastWasRedirect = FALSE;
2000 break;
2002 case '(': /* If a '(' is the first non whitespace in a command portion
2003 ie start of line or just after &&, then we read until an
2004 unquoted ) is found */
2005 WINE_TRACE("Found '(' conditions: curLen(%d), inQ(%d), onlyWS(%d)"
2006 ", for(%d, In:%d, Do:%d)"
2007 ", if(%d, else:%d, lwe:%d)\n",
2008 *curLen, inQuotes,
2009 onlyWhiteSpace,
2010 inFor, lastWasIn, lastWasDo,
2011 inIf, inElse, lastWasElse);
2012 lastWasRedirect = FALSE;
2014 /* Ignore open brackets inside the for set */
2015 if (*curLen == 0 && !inIn) {
2016 curDepth++;
2018 /* If in quotes, ignore brackets */
2019 } else if (inQuotes) {
2020 curCopyTo[(*curLen)++] = *curPos;
2022 /* In a FOR loop, an unquoted '(' may occur straight after
2023 IN or DO
2024 In an IF statement just handle it regardless as we don't
2025 parse the operands
2026 In an ELSE statement, only allow it straight away after
2027 the ELSE and whitespace
2029 } else if (inIf ||
2030 (inElse && lastWasElse && onlyWhiteSpace) ||
2031 (inFor && (lastWasIn || lastWasDo) && onlyWhiteSpace)) {
2033 /* If entering into an 'IN', set inIn */
2034 if (inFor && lastWasIn && onlyWhiteSpace) {
2035 WINE_TRACE("Inside an IN\n");
2036 inIn = TRUE;
2039 /* Add the current command */
2040 WCMD_addCommand(curString, &curStringLen,
2041 curRedirs, &curRedirsLen,
2042 &curCopyTo, &curLen,
2043 prevDelim, curDepth,
2044 &lastEntry, output);
2046 curDepth++;
2047 } else {
2048 curCopyTo[(*curLen)++] = *curPos;
2050 break;
2052 case '&': if (!inQuotes) {
2053 lastWasRedirect = FALSE;
2055 /* Add an entry to the command list */
2056 if (curStringLen > 0) {
2058 /* Add the current command */
2059 WCMD_addCommand(curString, &curStringLen,
2060 curRedirs, &curRedirsLen,
2061 &curCopyTo, &curLen,
2062 prevDelim, curDepth,
2063 &lastEntry, output);
2067 if (*(curPos+1) == '&') {
2068 curPos++; /* Skip other & */
2069 prevDelim = CMD_ONSUCCESS;
2070 } else {
2071 prevDelim = CMD_NONE;
2073 } else {
2074 curCopyTo[(*curLen)++] = *curPos;
2076 break;
2078 case ')': if (!inQuotes && curDepth > 0) {
2079 lastWasRedirect = FALSE;
2081 /* Add the current command if there is one */
2082 if (curStringLen) {
2084 /* Add the current command */
2085 WCMD_addCommand(curString, &curStringLen,
2086 curRedirs, &curRedirsLen,
2087 &curCopyTo, &curLen,
2088 prevDelim, curDepth,
2089 &lastEntry, output);
2092 /* Add an empty entry to the command list */
2093 prevDelim = CMD_NONE;
2094 WCMD_addCommand(NULL, &curStringLen,
2095 curRedirs, &curRedirsLen,
2096 &curCopyTo, &curLen,
2097 prevDelim, curDepth,
2098 &lastEntry, output);
2099 curDepth--;
2101 /* Leave inIn if necessary */
2102 if (inIn) inIn = FALSE;
2103 } else {
2104 curCopyTo[(*curLen)++] = *curPos;
2106 break;
2107 default:
2108 lastWasRedirect = FALSE;
2109 curCopyTo[(*curLen)++] = *curPos;
2112 curPos++;
2114 /* At various times we need to know if we have only skipped whitespace,
2115 so reset this variable and then it will remain true until a non
2116 whitespace is found */
2117 if ((thisChar != ' ') && (thisChar != '\t') && (thisChar != '\n'))
2118 onlyWhiteSpace = FALSE;
2120 /* Flag end of interest in FOR DO and IN parms once something has been processed */
2121 if (!lastWasWhiteSpace) {
2122 lastWasIn = lastWasDo = FALSE;
2125 /* If we have reached the end, add this command into the list */
2126 if (*curPos == 0x00 && *curLen > 0) {
2128 /* Add an entry to the command list */
2129 WCMD_addCommand(curString, &curStringLen,
2130 curRedirs, &curRedirsLen,
2131 &curCopyTo, &curLen,
2132 prevDelim, curDepth,
2133 &lastEntry, output);
2136 /* If we have reached the end of the string, see if bracketing outstanding */
2137 if (*curPos == 0x00 && curDepth > 0 && readFrom != INVALID_HANDLE_VALUE) {
2138 inRem = FALSE;
2139 prevDelim = CMD_NONE;
2140 inQuotes = 0;
2141 memset(extraSpace, 0x00, (MAXSTRING+1) * sizeof(WCHAR));
2143 /* Read more, skipping any blank lines */
2144 while (*extraSpace == 0x00) {
2145 if (!context) WCMD_output_asis( WCMD_LoadMessage(WCMD_MOREPROMPT));
2146 if (WCMD_fgets(extraSpace, MAXSTRING, readFrom) == NULL) break;
2148 curPos = extraSpace;
2149 if (context) handleExpansion(extraSpace, FALSE, NULL, NULL);
2150 /* Continue to echo commands IF echo is on and in batch program */
2151 if (context && echo_mode && extraSpace[0] && (extraSpace[0] != '@')) {
2152 WCMD_output_asis(extraSpace);
2153 WCMD_output_asis(newline);
2158 /* Dump out the parsed output */
2159 WCMD_DumpCommands(*output);
2161 return extraSpace;
2164 /***************************************************************************
2165 * WCMD_process_commands
2167 * Process all the commands read in so far
2169 CMD_LIST *WCMD_process_commands(CMD_LIST *thisCmd, BOOL oneBracket,
2170 const WCHAR *var, const WCHAR *val) {
2172 int bdepth = -1;
2174 if (thisCmd && oneBracket) bdepth = thisCmd->bracketDepth;
2176 /* Loop through the commands, processing them one by one */
2177 while (thisCmd) {
2179 CMD_LIST *origCmd = thisCmd;
2181 /* If processing one bracket only, and we find the end bracket
2182 entry (or less), return */
2183 if (oneBracket && !thisCmd->command &&
2184 bdepth <= thisCmd->bracketDepth) {
2185 WINE_TRACE("Finished bracket @ %p, next command is %p\n",
2186 thisCmd, thisCmd->nextcommand);
2187 return thisCmd->nextcommand;
2190 /* Ignore the NULL entries a ')' inserts (Only 'if' cares
2191 about them and it will be handled in there)
2192 Also, skip over any batch labels (eg. :fred) */
2193 if (thisCmd->command && thisCmd->command[0] != ':') {
2194 WINE_TRACE("Executing command: '%s'\n", wine_dbgstr_w(thisCmd->command));
2195 WCMD_execute (thisCmd->command, thisCmd->redirects, var, val, &thisCmd);
2198 /* Step on unless the command itself already stepped on */
2199 if (thisCmd == origCmd) thisCmd = thisCmd->nextcommand;
2201 return NULL;
2204 /***************************************************************************
2205 * WCMD_free_commands
2207 * Frees the storage held for a parsed command line
2208 * - This is not done in the process_commands, as eventually the current
2209 * pointer will be modified within the commands, and hence a single free
2210 * routine is simpler
2212 void WCMD_free_commands(CMD_LIST *cmds) {
2214 /* Loop through the commands, freeing them one by one */
2215 while (cmds) {
2216 CMD_LIST *thisCmd = cmds;
2217 cmds = cmds->nextcommand;
2218 HeapFree(GetProcessHeap(), 0, thisCmd->command);
2219 HeapFree(GetProcessHeap(), 0, thisCmd->redirects);
2220 HeapFree(GetProcessHeap(), 0, thisCmd);
2225 /*****************************************************************************
2226 * Main entry point. This is a console application so we have a main() not a
2227 * winmain().
2230 int wmain (int argc, WCHAR *argvW[])
2232 int args;
2233 WCHAR *cmd = NULL;
2234 WCHAR string[1024];
2235 WCHAR envvar[4];
2236 HANDLE h;
2237 int opt_q;
2238 int opt_t = 0;
2239 static const WCHAR autoexec[] = {'\\','a','u','t','o','e','x','e','c','.',
2240 'b','a','t','\0'};
2241 static const WCHAR promptW[] = {'P','R','O','M','P','T','\0'};
2242 static const WCHAR defaultpromptW[] = {'$','P','$','G','\0'};
2243 char ansiVersion[100];
2244 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
2246 srand(time(NULL));
2248 /* Pre initialize some messages */
2249 strcpy(ansiVersion, PACKAGE_VERSION);
2250 MultiByteToWideChar(CP_ACP, 0, ansiVersion, -1, string, 1024);
2251 wsprintfW(version_string, WCMD_LoadMessage(WCMD_VERSION), string);
2252 strcpyW(anykey, WCMD_LoadMessage(WCMD_ANYKEY));
2254 args = argc;
2255 opt_c=opt_k=opt_q=opt_s=0;
2256 while (args > 0)
2258 WCHAR c;
2259 WINE_TRACE("Command line parm: '%s'\n", wine_dbgstr_w(*argvW));
2260 if ((*argvW)[0]!='/' || (*argvW)[1]=='\0') {
2261 argvW++;
2262 args--;
2263 continue;
2266 c=(*argvW)[1];
2267 if (tolowerW(c)=='c') {
2268 opt_c=1;
2269 } else if (tolowerW(c)=='q') {
2270 opt_q=1;
2271 } else if (tolowerW(c)=='k') {
2272 opt_k=1;
2273 } else if (tolowerW(c)=='s') {
2274 opt_s=1;
2275 } else if (tolowerW(c)=='a') {
2276 unicodePipes=FALSE;
2277 } else if (tolowerW(c)=='u') {
2278 unicodePipes=TRUE;
2279 } else if (tolowerW(c)=='t' && (*argvW)[2]==':') {
2280 opt_t=strtoulW(&(*argvW)[3], NULL, 16);
2281 } else if (tolowerW(c)=='x' || tolowerW(c)=='y') {
2282 /* Ignored for compatibility with Windows */
2285 if ((*argvW)[2]==0) {
2286 argvW++;
2287 args--;
2289 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
2291 *argvW+=2;
2294 if (opt_c || opt_k) /* break out of parsing immediately after c or k */
2295 break;
2298 if (opt_q) {
2299 static const WCHAR eoff[] = {'O','F','F','\0'};
2300 WCMD_echo(eoff);
2303 if (opt_c || opt_k) {
2304 int len,qcount;
2305 WCHAR** arg;
2306 int argsLeft;
2307 WCHAR* p;
2309 /* opt_s left unflagged if the command starts with and contains exactly
2310 * one quoted string (exactly two quote characters). The quoted string
2311 * must be an executable name that has whitespace and must not have the
2312 * following characters: &<>()@^| */
2314 /* Build the command to execute */
2315 len = 0;
2316 qcount = 0;
2317 argsLeft = args;
2318 for (arg = argvW; argsLeft>0; arg++,argsLeft--)
2320 int has_space,bcount;
2321 WCHAR* a;
2323 has_space=0;
2324 bcount=0;
2325 a=*arg;
2326 if( !*a ) has_space=1;
2327 while (*a!='\0') {
2328 if (*a=='\\') {
2329 bcount++;
2330 } else {
2331 if (*a==' ' || *a=='\t') {
2332 has_space=1;
2333 } else if (*a=='"') {
2334 /* doubling of '\' preceding a '"',
2335 * plus escaping of said '"'
2337 len+=2*bcount+1;
2338 qcount++;
2340 bcount=0;
2342 a++;
2344 len+=(a-*arg) + 1; /* for the separating space */
2345 if (has_space)
2347 len+=2; /* for the quotes */
2348 qcount+=2;
2352 if (qcount!=2)
2353 opt_s=1;
2355 /* check argvW[0] for a space and invalid characters */
2356 if (!opt_s) {
2357 opt_s=1;
2358 p=*argvW;
2359 while (*p!='\0') {
2360 if (*p=='&' || *p=='<' || *p=='>' || *p=='(' || *p==')'
2361 || *p=='@' || *p=='^' || *p=='|') {
2362 opt_s=1;
2363 break;
2365 if (*p==' ')
2366 opt_s=0;
2367 p++;
2371 cmd = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
2372 if (!cmd)
2373 exit(1);
2375 p = cmd;
2376 argsLeft = args;
2377 for (arg = argvW; argsLeft>0; arg++,argsLeft--)
2379 int has_space,has_quote;
2380 WCHAR* a;
2382 /* Check for quotes and spaces in this argument */
2383 has_space=has_quote=0;
2384 a=*arg;
2385 if( !*a ) has_space=1;
2386 while (*a!='\0') {
2387 if (*a==' ' || *a=='\t') {
2388 has_space=1;
2389 if (has_quote)
2390 break;
2391 } else if (*a=='"') {
2392 has_quote=1;
2393 if (has_space)
2394 break;
2396 a++;
2399 /* Now transfer it to the command line */
2400 if (has_space)
2401 *p++='"';
2402 if (has_quote) {
2403 int bcount;
2404 WCHAR* a;
2406 bcount=0;
2407 a=*arg;
2408 while (*a!='\0') {
2409 if (*a=='\\') {
2410 *p++=*a;
2411 bcount++;
2412 } else {
2413 if (*a=='"') {
2414 int i;
2416 /* Double all the '\\' preceding this '"', plus one */
2417 for (i=0;i<=bcount;i++)
2418 *p++='\\';
2419 *p++='"';
2420 } else {
2421 *p++=*a;
2423 bcount=0;
2425 a++;
2427 } else {
2428 strcpyW(p,*arg);
2429 p+=strlenW(*arg);
2431 if (has_space)
2432 *p++='"';
2433 *p++=' ';
2435 if (p > cmd)
2436 p--; /* remove last space */
2437 *p = '\0';
2439 WINE_TRACE("/c command line: '%s'\n", wine_dbgstr_w(cmd));
2441 /* strip first and last quote characters if opt_s; check for invalid
2442 * executable is done later */
2443 if (opt_s && *cmd=='\"')
2444 WCMD_opt_s_strip_quotes(cmd);
2447 if (opt_c) {
2448 /* If we do a "cmd /c command", we don't want to allocate a new
2449 * console since the command returns immediately. Rather, we use
2450 * the currently allocated input and output handles. This allows
2451 * us to pipe to and read from the command interpreter.
2454 /* Parse the command string, without reading any more input */
2455 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2456 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
2457 WCMD_free_commands(toExecute);
2458 toExecute = NULL;
2460 HeapFree(GetProcessHeap(), 0, cmd);
2461 return errorlevel;
2464 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT |
2465 ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
2466 SetConsoleTitleW(WCMD_LoadMessage(WCMD_CONSTITLE));
2468 /* Note: cmd.exe /c dir does not get a new color, /k dir does */
2469 if (opt_t) {
2470 if (!(((opt_t & 0xF0) >> 4) == (opt_t & 0x0F))) {
2471 defaultColor = opt_t & 0xFF;
2472 param1[0] = 0x00;
2473 WCMD_color();
2475 } else {
2476 /* Check HKCU\Software\Microsoft\Command Processor
2477 Then HKLM\Software\Microsoft\Command Processor
2478 for defaultcolour value
2479 Note Can be supplied as DWORD or REG_SZ
2480 Note2 When supplied as REG_SZ it's in decimal!!! */
2481 HKEY key;
2482 DWORD type;
2483 DWORD value=0, size=4;
2484 static const WCHAR regKeyW[] = {'S','o','f','t','w','a','r','e','\\',
2485 'M','i','c','r','o','s','o','f','t','\\',
2486 'C','o','m','m','a','n','d',' ','P','r','o','c','e','s','s','o','r','\0'};
2487 static const WCHAR dfltColorW[] = {'D','e','f','a','u','l','t','C','o','l','o','r','\0'};
2489 if (RegOpenKeyExW(HKEY_CURRENT_USER, regKeyW,
2490 0, KEY_READ, &key) == ERROR_SUCCESS) {
2491 WCHAR strvalue[4];
2493 /* See if DWORD or REG_SZ */
2494 if (RegQueryValueExW(key, dfltColorW, NULL, &type,
2495 NULL, NULL) == ERROR_SUCCESS) {
2496 if (type == REG_DWORD) {
2497 size = sizeof(DWORD);
2498 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2499 (LPBYTE)&value, &size);
2500 } else if (type == REG_SZ) {
2501 size = sizeof(strvalue)/sizeof(WCHAR);
2502 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2503 (LPBYTE)strvalue, &size);
2504 value = strtoulW(strvalue, NULL, 10);
2507 RegCloseKey(key);
2510 if (value == 0 && RegOpenKeyExW(HKEY_LOCAL_MACHINE, regKeyW,
2511 0, KEY_READ, &key) == ERROR_SUCCESS) {
2512 WCHAR strvalue[4];
2514 /* See if DWORD or REG_SZ */
2515 if (RegQueryValueExW(key, dfltColorW, NULL, &type,
2516 NULL, NULL) == ERROR_SUCCESS) {
2517 if (type == REG_DWORD) {
2518 size = sizeof(DWORD);
2519 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2520 (LPBYTE)&value, &size);
2521 } else if (type == REG_SZ) {
2522 size = sizeof(strvalue)/sizeof(WCHAR);
2523 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2524 (LPBYTE)strvalue, &size);
2525 value = strtoulW(strvalue, NULL, 10);
2528 RegCloseKey(key);
2531 /* If one found, set the screen to that colour */
2532 if (!(((value & 0xF0) >> 4) == (value & 0x0F))) {
2533 defaultColor = value & 0xFF;
2534 param1[0] = 0x00;
2535 WCMD_color();
2540 /* Save cwd into appropriate env var */
2541 GetCurrentDirectoryW(1024, string);
2542 if (IsCharAlphaW(string[0]) && string[1] == ':') {
2543 static const WCHAR fmt[] = {'=','%','c',':','\0'};
2544 wsprintfW(envvar, fmt, string[0]);
2545 SetEnvironmentVariableW(envvar, string);
2546 WINE_TRACE("Set %s to %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(string));
2549 if (opt_k) {
2550 /* Parse the command string, without reading any more input */
2551 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2552 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
2553 WCMD_free_commands(toExecute);
2554 toExecute = NULL;
2555 HeapFree(GetProcessHeap(), 0, cmd);
2559 * If there is an AUTOEXEC.BAT file, try to execute it.
2562 GetFullPathNameW (autoexec, sizeof(string)/sizeof(WCHAR), string, NULL);
2563 h = CreateFileW(string, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
2564 if (h != INVALID_HANDLE_VALUE) {
2565 CloseHandle (h);
2566 #if 0
2567 WCMD_batch (autoexec, autoexec, 0, NULL, INVALID_HANDLE_VALUE);
2568 #endif
2572 * Loop forever getting commands and executing them.
2575 SetEnvironmentVariableW(promptW, defaultpromptW);
2576 WCMD_version ();
2577 while (TRUE) {
2579 /* Read until EOF (which for std input is never, but if redirect
2580 in place, may occur */
2581 if (echo_mode) WCMD_show_prompt();
2582 if (WCMD_ReadAndParseLine(NULL, &toExecute,
2583 GetStdHandle(STD_INPUT_HANDLE)) == NULL)
2584 break;
2585 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
2586 WCMD_free_commands(toExecute);
2587 toExecute = NULL;
2589 return 0;