shell32/tests: Fix a typo.
[wine.git] / programs / cmd / wcmdmain.c
blob637c0e94bd541a5ffed086c37a778f7d5318647d
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 <time.h>
30 #include "wcmd.h"
31 #include "shellapi.h"
32 #include "wine/debug.h"
34 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
36 extern const WCHAR inbuilt[][10];
37 extern struct env_stack *pushd_directories;
39 BATCH_CONTEXT *context = NULL;
40 DWORD errorlevel;
41 WCHAR quals[MAXSTRING], param1[MAXSTRING], param2[MAXSTRING];
42 BOOL interactive;
43 FOR_CONTEXT forloopcontext; /* The 'for' loop context */
44 BOOL delayedsubst = FALSE; /* The current delayed substitution setting */
46 int defaultColor = 7;
47 BOOL echo_mode = TRUE;
49 WCHAR anykey[100], version_string[100];
50 const WCHAR newlineW[] = {'\r','\n','\0'};
51 const WCHAR spaceW[] = {' ','\0'};
52 static const WCHAR envPathExt[] = {'P','A','T','H','E','X','T','\0'};
53 static const WCHAR dfltPathExt[] = {'.','b','a','t',';',
54 '.','c','o','m',';',
55 '.','c','m','d',';',
56 '.','e','x','e','\0'};
58 static BOOL opt_c, opt_k, opt_s, unicodeOutput = FALSE;
60 /* Variables pertaining to paging */
61 static BOOL paged_mode;
62 static const WCHAR *pagedMessage = NULL;
63 static int line_count;
64 static int max_height;
65 static int max_width;
66 static int numChars;
68 #define MAX_WRITECONSOLE_SIZE 65535
71 * Returns a buffer for reading from/writing to file
72 * Never freed
74 static char *get_file_buffer(void)
76 static char *output_bufA = NULL;
77 if (!output_bufA)
78 output_bufA = heap_xalloc(MAX_WRITECONSOLE_SIZE);
79 return output_bufA;
82 /*******************************************************************
83 * WCMD_output_asis_len - send output to current standard output
85 * Output a formatted unicode string. Ideally this will go to the console
86 * and hence required WriteConsoleW to output it, however if file i/o is
87 * redirected, it needs to be WriteFile'd using OEM (not ANSI) format
89 static void WCMD_output_asis_len(const WCHAR *message, DWORD len, HANDLE device)
91 DWORD nOut= 0;
92 DWORD res = 0;
94 /* If nothing to write, return (MORE does this sometimes) */
95 if (!len) return;
97 /* Try to write as unicode assuming it is to a console */
98 res = WriteConsoleW(device, message, len, &nOut, NULL);
100 /* If writing to console fails, assume it's file
101 i/o so convert to OEM codepage and output */
102 if (!res) {
103 BOOL usedDefaultChar = FALSE;
104 DWORD convertedChars;
105 char *buffer;
107 if (!unicodeOutput) {
109 if (!(buffer = get_file_buffer()))
110 return;
112 /* Convert to OEM, then output */
113 convertedChars = WideCharToMultiByte(GetConsoleOutputCP(), 0, message,
114 len, buffer, MAX_WRITECONSOLE_SIZE,
115 "?", &usedDefaultChar);
116 WriteFile(device, buffer, convertedChars,
117 &nOut, FALSE);
118 } else {
119 WriteFile(device, message, len*sizeof(WCHAR),
120 &nOut, FALSE);
123 return;
126 /*******************************************************************
127 * WCMD_output - send output to current standard output device.
131 void WINAPIV WCMD_output (const WCHAR *format, ...) {
133 __ms_va_list ap;
134 WCHAR* string;
135 DWORD len;
137 __ms_va_start(ap,format);
138 SetLastError(NO_ERROR);
139 string = NULL;
140 len = FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,
141 format, 0, 0, (LPWSTR)&string, 0, &ap);
142 __ms_va_end(ap);
143 if (len == 0 && GetLastError() != NO_ERROR)
144 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format));
145 else
147 WCMD_output_asis_len(string, len, GetStdHandle(STD_OUTPUT_HANDLE));
148 LocalFree(string);
152 /*******************************************************************
153 * WCMD_output_stderr - send output to current standard error device.
157 void WINAPIV WCMD_output_stderr (const WCHAR *format, ...) {
159 __ms_va_list ap;
160 WCHAR* string;
161 DWORD len;
163 __ms_va_start(ap,format);
164 SetLastError(NO_ERROR);
165 string = NULL;
166 len = FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,
167 format, 0, 0, (LPWSTR)&string, 0, &ap);
168 __ms_va_end(ap);
169 if (len == 0 && GetLastError() != NO_ERROR)
170 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format));
171 else
173 WCMD_output_asis_len(string, len, GetStdHandle(STD_ERROR_HANDLE));
174 LocalFree(string);
178 /*******************************************************************
179 * WCMD_format_string - allocate a buffer and format a string
183 WCHAR* WINAPIV WCMD_format_string (const WCHAR *format, ...)
185 __ms_va_list ap;
186 WCHAR* string;
187 DWORD len;
189 __ms_va_start(ap,format);
190 SetLastError(NO_ERROR);
191 len = FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,
192 format, 0, 0, (LPWSTR)&string, 0, &ap);
193 __ms_va_end(ap);
194 if (len == 0 && GetLastError() != NO_ERROR) {
195 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format));
196 string = (WCHAR*)LocalAlloc(LMEM_FIXED, 2);
197 *string = 0;
199 return string;
202 void WCMD_enter_paged_mode(const WCHAR *msg)
204 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
206 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo)) {
207 max_height = consoleInfo.dwSize.Y;
208 max_width = consoleInfo.dwSize.X;
209 } else {
210 max_height = 25;
211 max_width = 80;
213 paged_mode = TRUE;
214 line_count = 0;
215 numChars = 0;
216 pagedMessage = (msg==NULL)? anykey : msg;
219 void WCMD_leave_paged_mode(void)
221 paged_mode = FALSE;
222 pagedMessage = NULL;
225 /***************************************************************************
226 * WCMD_Readfile
228 * Read characters in from a console/file, returning result in Unicode
230 BOOL WCMD_ReadFile(const HANDLE hIn, WCHAR *intoBuf, const DWORD maxChars, LPDWORD charsRead)
232 DWORD numRead;
233 char *buffer;
235 if (WCMD_is_console_handle(hIn))
236 /* Try to read from console as Unicode */
237 return ReadConsoleW(hIn, intoBuf, maxChars, charsRead, NULL);
239 /* We assume it's a file handle and read then convert from assumed OEM codepage */
240 if (!(buffer = get_file_buffer()))
241 return FALSE;
243 if (!ReadFile(hIn, buffer, maxChars, &numRead, NULL))
244 return FALSE;
246 *charsRead = MultiByteToWideChar(GetConsoleCP(), 0, buffer, numRead, intoBuf, maxChars);
248 return TRUE;
251 /*******************************************************************
252 * WCMD_output_asis_handle
254 * Send output to specified handle without formatting e.g. when message contains '%'
256 static void WCMD_output_asis_handle (DWORD std_handle, const WCHAR *message) {
257 DWORD count;
258 const WCHAR* ptr;
259 WCHAR string[1024];
260 HANDLE handle = GetStdHandle(std_handle);
262 if (paged_mode) {
263 do {
264 ptr = message;
265 while (*ptr && *ptr!='\n' && (numChars < max_width)) {
266 numChars++;
267 ptr++;
269 if (*ptr == '\n') ptr++;
270 WCMD_output_asis_len(message, ptr - message, handle);
271 numChars = 0;
272 if (++line_count >= max_height - 1) {
273 line_count = 0;
274 WCMD_output_asis_len(pagedMessage, strlenW(pagedMessage), handle);
275 WCMD_ReadFile(GetStdHandle(STD_INPUT_HANDLE), string, ARRAY_SIZE(string), &count);
277 } while (((message = ptr) != NULL) && (*ptr));
278 } else {
279 WCMD_output_asis_len(message, lstrlenW(message), handle);
283 /*******************************************************************
284 * WCMD_output_asis
286 * Send output to current standard output device, without formatting
287 * e.g. when message contains '%'
289 void WCMD_output_asis (const WCHAR *message) {
290 WCMD_output_asis_handle(STD_OUTPUT_HANDLE, message);
293 /*******************************************************************
294 * WCMD_output_asis_stderr
296 * Send output to current standard error device, without formatting
297 * e.g. when message contains '%'
299 void WCMD_output_asis_stderr (const WCHAR *message) {
300 WCMD_output_asis_handle(STD_ERROR_HANDLE, message);
303 /****************************************************************************
304 * WCMD_print_error
306 * Print the message for GetLastError
309 void WCMD_print_error (void) {
310 LPVOID lpMsgBuf;
311 DWORD error_code;
312 int status;
314 error_code = GetLastError ();
315 status = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
316 NULL, error_code, 0, (LPWSTR) &lpMsgBuf, 0, NULL);
317 if (!status) {
318 WINE_FIXME ("Cannot display message for error %d, status %d\n",
319 error_code, GetLastError());
320 return;
323 WCMD_output_asis_len(lpMsgBuf, lstrlenW(lpMsgBuf),
324 GetStdHandle(STD_ERROR_HANDLE));
325 LocalFree (lpMsgBuf);
326 WCMD_output_asis_len (newlineW, lstrlenW(newlineW),
327 GetStdHandle(STD_ERROR_HANDLE));
328 return;
331 /******************************************************************************
332 * WCMD_show_prompt
334 * Display the prompt on STDout
338 static void WCMD_show_prompt (BOOL newLine) {
340 int status;
341 WCHAR out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
342 WCHAR *p, *q;
343 DWORD len;
344 static const WCHAR envPrompt[] = {'P','R','O','M','P','T','\0'};
346 len = GetEnvironmentVariableW(envPrompt, prompt_string, ARRAY_SIZE(prompt_string));
347 if ((len == 0) || (len >= ARRAY_SIZE(prompt_string))) {
348 static const WCHAR dfltPrompt[] = {'$','P','$','G','\0'};
349 strcpyW (prompt_string, dfltPrompt);
351 p = prompt_string;
352 q = out_string;
353 if (newLine) {
354 *q++ = '\r';
355 *q++ = '\n';
357 *q = '\0';
358 while (*p != '\0') {
359 if (*p != '$') {
360 *q++ = *p++;
361 *q = '\0';
363 else {
364 p++;
365 switch (toupper(*p)) {
366 case '$':
367 *q++ = '$';
368 break;
369 case 'A':
370 *q++ = '&';
371 break;
372 case 'B':
373 *q++ = '|';
374 break;
375 case 'C':
376 *q++ = '(';
377 break;
378 case 'D':
379 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH - (q - out_string));
380 while (*q) q++;
381 break;
382 case 'E':
383 *q++ = '\x1b';
384 break;
385 case 'F':
386 *q++ = ')';
387 break;
388 case 'G':
389 *q++ = '>';
390 break;
391 case 'H':
392 *q++ = '\b';
393 break;
394 case 'L':
395 *q++ = '<';
396 break;
397 case 'N':
398 status = GetCurrentDirectoryW(ARRAY_SIZE(curdir), curdir);
399 if (status) {
400 *q++ = curdir[0];
402 break;
403 case 'P':
404 status = GetCurrentDirectoryW(ARRAY_SIZE(curdir), curdir);
405 if (status) {
406 strcatW (q, curdir);
407 while (*q) q++;
409 break;
410 case 'Q':
411 *q++ = '=';
412 break;
413 case 'S':
414 *q++ = ' ';
415 break;
416 case 'T':
417 GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
418 while (*q) q++;
419 break;
420 case 'V':
421 strcatW (q, version_string);
422 while (*q) q++;
423 break;
424 case '_':
425 *q++ = '\n';
426 break;
427 case '+':
428 if (pushd_directories) {
429 memset(q, '+', pushd_directories->u.stackdepth);
430 q = q + pushd_directories->u.stackdepth;
432 break;
434 p++;
435 *q = '\0';
438 WCMD_output_asis (out_string);
441 void *heap_xalloc(size_t size)
443 void *ret;
445 ret = heap_alloc(size);
446 if(!ret) {
447 ERR("Out of memory\n");
448 ExitProcess(1);
451 return ret;
454 /*************************************************************************
455 * WCMD_strsubstW
456 * Replaces a portion of a Unicode string with the specified string.
457 * It's up to the caller to ensure there is enough space in the
458 * destination buffer.
460 void WCMD_strsubstW(WCHAR *start, const WCHAR *next, const WCHAR *insert, int len) {
462 if (len < 0)
463 len=insert ? lstrlenW(insert) : 0;
464 if (start+len != next)
465 memmove(start+len, next, (strlenW(next) + 1) * sizeof(*next));
466 if (insert)
467 memcpy(start, insert, len * sizeof(*insert));
470 /***************************************************************************
471 * WCMD_skip_leading_spaces
473 * Return a pointer to the first non-whitespace character of string.
474 * Does not modify the input string.
476 WCHAR *WCMD_skip_leading_spaces (WCHAR *string) {
478 WCHAR *ptr;
480 ptr = string;
481 while (*ptr == ' ' || *ptr == '\t') ptr++;
482 return ptr;
485 /***************************************************************************
486 * WCMD_keyword_ws_found
488 * Checks if the string located at ptr matches a keyword (of length len)
489 * followed by a whitespace character (space or tab)
491 BOOL WCMD_keyword_ws_found(const WCHAR *keyword, int len, const WCHAR *ptr) {
492 return (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
493 ptr, len, keyword, len) == CSTR_EQUAL)
494 && ((*(ptr + len) == ' ') || (*(ptr + len) == '\t'));
497 /*************************************************************************
498 * WCMD_strip_quotes
500 * Remove first and last quote WCHARacters, preserving all other text
501 * Returns the location of the final quote
503 WCHAR *WCMD_strip_quotes(WCHAR *cmd) {
504 WCHAR *src = cmd + 1, *dest = cmd, *lastq = NULL, *lastquote;
505 while((*dest=*src) != '\0') {
506 if (*src=='\"')
507 lastq=dest;
508 dest++, src++;
510 lastquote = lastq;
511 if (lastq) {
512 dest=lastq++;
513 while ((*dest++=*lastq++) != 0)
516 return lastquote;
520 /*************************************************************************
521 * WCMD_is_magic_envvar
522 * Return TRUE if s is '%'magicvar'%'
523 * and is not masked by a real environment variable.
526 static inline BOOL WCMD_is_magic_envvar(const WCHAR *s, const WCHAR *magicvar)
528 int len;
530 if (s[0] != '%')
531 return FALSE; /* Didn't begin with % */
532 len = strlenW(s);
533 if (len < 2 || s[len-1] != '%')
534 return FALSE; /* Didn't end with another % */
536 if (CompareStringW(LOCALE_USER_DEFAULT,
537 NORM_IGNORECASE | SORT_STRINGSORT,
538 s+1, len-2, magicvar, -1) != CSTR_EQUAL) {
539 /* Name doesn't match. */
540 return FALSE;
543 if (GetEnvironmentVariableW(magicvar, NULL, 0) > 0) {
544 /* Masked by real environment variable. */
545 return FALSE;
548 return TRUE;
551 /*************************************************************************
552 * WCMD_expand_envvar
554 * Expands environment variables, allowing for WCHARacter substitution
556 static WCHAR *WCMD_expand_envvar(WCHAR *start, WCHAR startchar)
558 WCHAR *endOfVar = NULL, *s;
559 WCHAR *colonpos = NULL;
560 WCHAR thisVar[MAXSTRING];
561 WCHAR thisVarContents[MAXSTRING];
562 WCHAR savedchar = 0x00;
563 int len;
565 static const WCHAR ErrorLvl[] = {'E','R','R','O','R','L','E','V','E','L','\0'};
566 static const WCHAR Date[] = {'D','A','T','E','\0'};
567 static const WCHAR Time[] = {'T','I','M','E','\0'};
568 static const WCHAR Cd[] = {'C','D','\0'};
569 static const WCHAR Random[] = {'R','A','N','D','O','M','\0'};
570 WCHAR Delims[] = {'%',':','\0'}; /* First char gets replaced appropriately */
572 WINE_TRACE("Expanding: %s (%c)\n", wine_dbgstr_w(start), startchar);
574 /* Find the end of the environment variable, and extract name */
575 Delims[0] = startchar;
576 endOfVar = strpbrkW(start+1, Delims);
578 if (endOfVar == NULL || *endOfVar==' ') {
580 /* In batch program, missing terminator for % and no following
581 ':' just removes the '%' */
582 if (context) {
583 WCMD_strsubstW(start, start + 1, NULL, 0);
584 return start;
585 } else {
587 /* In command processing, just ignore it - allows command line
588 syntax like: for %i in (a.a) do echo %i */
589 return start+1;
593 /* If ':' found, process remaining up until '%' (or stop at ':' if
594 a missing '%' */
595 if (*endOfVar==':') {
596 WCHAR *endOfVar2 = strchrW(endOfVar+1, startchar);
597 if (endOfVar2 != NULL) endOfVar = endOfVar2;
600 memcpy(thisVar, start, ((endOfVar - start) + 1) * sizeof(WCHAR));
601 thisVar[(endOfVar - start)+1] = 0x00;
602 colonpos = strchrW(thisVar+1, ':');
604 /* If there's complex substitution, just need %var% for now
605 to get the expanded data to play with */
606 if (colonpos) {
607 *colonpos = startchar;
608 savedchar = *(colonpos+1);
609 *(colonpos+1) = 0x00;
612 /* By now, we know the variable we want to expand but it may be
613 surrounded by '!' if we are in delayed expansion - if so convert
614 to % signs. */
615 if (startchar=='!') {
616 thisVar[0] = '%';
617 thisVar[(endOfVar - start)] = '%';
619 WINE_TRACE("Retrieving contents of %s\n", wine_dbgstr_w(thisVar));
621 /* Expand to contents, if unchanged, return */
622 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
623 /* override if existing env var called that name */
624 if (WCMD_is_magic_envvar(thisVar, ErrorLvl)) {
625 static const WCHAR fmt[] = {'%','d','\0'};
626 wsprintfW(thisVarContents, fmt, errorlevel);
627 len = strlenW(thisVarContents);
628 } else if (WCMD_is_magic_envvar(thisVar, Date)) {
629 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL,
630 NULL, thisVarContents, MAXSTRING);
631 len = strlenW(thisVarContents);
632 } else if (WCMD_is_magic_envvar(thisVar, Time)) {
633 GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL,
634 NULL, thisVarContents, MAXSTRING);
635 len = strlenW(thisVarContents);
636 } else if (WCMD_is_magic_envvar(thisVar, Cd)) {
637 GetCurrentDirectoryW(MAXSTRING, thisVarContents);
638 len = strlenW(thisVarContents);
639 } else if (WCMD_is_magic_envvar(thisVar, Random)) {
640 static const WCHAR fmt[] = {'%','d','\0'};
641 wsprintfW(thisVarContents, fmt, rand() % 32768);
642 len = strlenW(thisVarContents);
643 } else {
645 len = ExpandEnvironmentStringsW(thisVar, thisVarContents, ARRAY_SIZE(thisVarContents));
648 if (len == 0)
649 return endOfVar+1;
651 /* In a batch program, unknown env vars are replaced with nothing,
652 note syntax %garbage:1,3% results in anything after the ':'
653 except the %
654 From the command line, you just get back what you entered */
655 if (lstrcmpiW(thisVar, thisVarContents) == 0) {
657 /* Restore the complex part after the compare */
658 if (colonpos) {
659 *colonpos = ':';
660 *(colonpos+1) = savedchar;
663 /* Command line - just ignore this */
664 if (context == NULL) return endOfVar+1;
667 /* Batch - replace unknown env var with nothing */
668 if (colonpos == NULL) {
669 WCMD_strsubstW(start, endOfVar + 1, NULL, 0);
670 } else {
671 len = strlenW(thisVar);
672 thisVar[len-1] = 0x00;
673 /* If %:...% supplied, : is retained */
674 if (colonpos == thisVar+1) {
675 WCMD_strsubstW(start, endOfVar + 1, colonpos, -1);
676 } else {
677 WCMD_strsubstW(start, endOfVar + 1, colonpos + 1, -1);
680 return start;
684 /* See if we need to do complex substitution (any ':'s), if not
685 then our work here is done */
686 if (colonpos == NULL) {
687 WCMD_strsubstW(start, endOfVar + 1, thisVarContents, -1);
688 return start;
691 /* Restore complex bit */
692 *colonpos = ':';
693 *(colonpos+1) = savedchar;
696 Handle complex substitutions:
697 xxx=yyy (replace xxx with yyy)
698 *xxx=yyy (replace up to and including xxx with yyy)
699 ~x (from x WCHARs in)
700 ~-x (from x WCHARs from the end)
701 ~x,y (from x WCHARs in for y WCHARacters)
702 ~x,-y (from x WCHARs in until y WCHARacters from the end)
705 /* ~ is substring manipulation */
706 if (savedchar == '~') {
708 int substrposition, substrlength = 0;
709 WCHAR *commapos = strchrW(colonpos+2, ',');
710 WCHAR *startCopy;
712 substrposition = atolW(colonpos+2);
713 if (commapos) substrlength = atolW(commapos+1);
715 /* Check bounds */
716 if (substrposition >= 0) {
717 startCopy = &thisVarContents[min(substrposition, len)];
718 } else {
719 startCopy = &thisVarContents[max(0, len+substrposition-1)];
722 if (commapos == NULL) {
723 /* Copy the lot */
724 WCMD_strsubstW(start, endOfVar + 1, startCopy, -1);
725 } else if (substrlength < 0) {
727 int copybytes = (len+substrlength-1)-(startCopy-thisVarContents);
728 if (copybytes > len) copybytes = len;
729 else if (copybytes < 0) copybytes = 0;
730 WCMD_strsubstW(start, endOfVar + 1, startCopy, copybytes);
731 } else {
732 substrlength = min(substrlength, len - (startCopy- thisVarContents + 1));
733 WCMD_strsubstW(start, endOfVar + 1, startCopy, substrlength);
736 /* search and replace manipulation */
737 } else {
738 WCHAR *equalspos = strstrW(colonpos, equalW);
739 WCHAR *replacewith = equalspos+1;
740 WCHAR *found = NULL;
741 WCHAR *searchIn;
742 WCHAR *searchFor;
744 if (equalspos == NULL) return start+1;
745 s = heap_strdupW(endOfVar + 1);
747 /* Null terminate both strings */
748 thisVar[strlenW(thisVar)-1] = 0x00;
749 *equalspos = 0x00;
751 /* Since we need to be case insensitive, copy the 2 buffers */
752 searchIn = heap_strdupW(thisVarContents);
753 CharUpperBuffW(searchIn, strlenW(thisVarContents));
754 searchFor = heap_strdupW(colonpos+1);
755 CharUpperBuffW(searchFor, strlenW(colonpos+1));
757 /* Handle wildcard case */
758 if (*(colonpos+1) == '*') {
759 /* Search for string to replace */
760 found = strstrW(searchIn, searchFor+1);
762 if (found) {
763 /* Do replacement */
764 strcpyW(start, replacewith);
765 strcatW(start, thisVarContents + (found-searchIn) + strlenW(searchFor+1));
766 strcatW(start, s);
767 } else {
768 /* Copy as is */
769 strcpyW(start, thisVarContents);
770 strcatW(start, s);
773 } else {
774 /* Loop replacing all instances */
775 WCHAR *lastFound = searchIn;
776 WCHAR *outputposn = start;
778 *start = 0x00;
779 while ((found = strstrW(lastFound, searchFor))) {
780 lstrcpynW(outputposn,
781 thisVarContents + (lastFound-searchIn),
782 (found - lastFound)+1);
783 outputposn = outputposn + (found - lastFound);
784 strcatW(outputposn, replacewith);
785 outputposn = outputposn + strlenW(replacewith);
786 lastFound = found + strlenW(searchFor);
788 strcatW(outputposn,
789 thisVarContents + (lastFound-searchIn));
790 strcatW(outputposn, s);
792 heap_free(s);
793 heap_free(searchIn);
794 heap_free(searchFor);
796 return start;
799 /*****************************************************************************
800 * Expand the command. Native expands lines from batch programs as they are
801 * read in and not again, except for 'for' variable substitution.
802 * eg. As evidence, "echo %1 && shift && echo %1" or "echo %%path%%"
803 * atExecute is TRUE when the expansion is occurring as the command is executed
804 * rather than at parse time, i.e. delayed expansion and for loops need to be
805 * processed
807 static void handleExpansion(WCHAR *cmd, BOOL atExecute, BOOL delayed) {
809 /* For commands in a context (batch program): */
810 /* Expand environment variables in a batch file %{0-9} first */
811 /* including support for any ~ modifiers */
812 /* Additionally: */
813 /* Expand the DATE, TIME, CD, RANDOM and ERRORLEVEL special */
814 /* names allowing environment variable overrides */
815 /* NOTE: To support the %PATH:xxx% syntax, also perform */
816 /* manual expansion of environment variables here */
818 WCHAR *p = cmd;
819 WCHAR *t;
820 int i;
821 WCHAR *delayedp = NULL;
822 WCHAR startchar = '%';
823 WCHAR *normalp;
825 /* Display the FOR variables in effect */
826 for (i=0;i<52;i++) {
827 if (forloopcontext.variable[i]) {
828 WINE_TRACE("FOR variable context: %c = '%s'\n",
829 i<26?i+'a':(i-26)+'A',
830 wine_dbgstr_w(forloopcontext.variable[i]));
834 /* Find the next environment variable delimiter */
835 normalp = strchrW(p, '%');
836 if (delayed) delayedp = strchrW(p, '!');
837 if (!normalp) p = delayedp;
838 else if (!delayedp) p = normalp;
839 else p = min(p,delayedp);
840 if (p) startchar = *p;
842 while (p) {
844 WINE_TRACE("Translate command:%s %d (at: %s)\n",
845 wine_dbgstr_w(cmd), atExecute, wine_dbgstr_w(p));
846 i = *(p+1) - '0';
848 /* Don't touch %% unless it's in Batch */
849 if (!atExecute && *(p+1) == startchar) {
850 if (context) {
851 WCMD_strsubstW(p, p+1, NULL, 0);
853 p+=1;
855 /* Replace %~ modifications if in batch program */
856 } else if (*(p+1) == '~') {
857 WCMD_HandleTildaModifiers(&p, atExecute);
858 p++;
860 /* Replace use of %0...%9 if in batch program*/
861 } else if (!atExecute && context && (i >= 0) && (i <= 9) && startchar == '%') {
862 t = WCMD_parameter(context -> command, i + context -> shift_count[i],
863 NULL, TRUE, TRUE);
864 WCMD_strsubstW(p, p+2, t, -1);
866 /* Replace use of %* if in batch program*/
867 } else if (!atExecute && context && *(p+1)=='*' && startchar == '%') {
868 WCHAR *startOfParms = NULL;
869 WCHAR *thisParm = WCMD_parameter(context -> command, 0, &startOfParms, TRUE, TRUE);
870 if (startOfParms != NULL) {
871 startOfParms += strlenW(thisParm);
872 while (*startOfParms==' ' || *startOfParms == '\t') startOfParms++;
873 WCMD_strsubstW(p, p+2, startOfParms, -1);
874 } else
875 WCMD_strsubstW(p, p+2, NULL, 0);
877 } else {
878 int forvaridx = FOR_VAR_IDX(*(p+1));
879 if (startchar == '%' && forvaridx != -1 && forloopcontext.variable[forvaridx]) {
880 /* Replace the 2 characters, % and for variable character */
881 WCMD_strsubstW(p, p + 2, forloopcontext.variable[forvaridx], -1);
882 } else if (!atExecute || startchar == '!') {
883 p = WCMD_expand_envvar(p, startchar);
885 /* In a FOR loop, see if this is the variable to replace */
886 } else { /* Ignore %'s on second pass of batch program */
887 p++;
891 /* Find the next environment variable delimiter */
892 normalp = strchrW(p, '%');
893 if (delayed) delayedp = strchrW(p, '!');
894 if (!normalp) p = delayedp;
895 else if (!delayedp) p = normalp;
896 else p = min(p,delayedp);
897 if (p) startchar = *p;
900 return;
904 /*******************************************************************
905 * WCMD_parse - parse a command into parameters and qualifiers.
907 * On exit, all qualifiers are concatenated into q, the first string
908 * not beginning with "/" is in p1 and the
909 * second in p2. Any subsequent non-qualifier strings are lost.
910 * Parameters in quotes are handled.
912 static void WCMD_parse (const WCHAR *s, WCHAR *q, WCHAR *p1, WCHAR *p2)
914 int p = 0;
916 *q = *p1 = *p2 = '\0';
917 while (TRUE) {
918 switch (*s) {
919 case '/':
920 *q++ = *s++;
921 while ((*s != '\0') && (*s != ' ') && *s != '/') {
922 *q++ = toupperW (*s++);
924 *q = '\0';
925 break;
926 case ' ':
927 case '\t':
928 s++;
929 break;
930 case '"':
931 s++;
932 while ((*s != '\0') && (*s != '"')) {
933 if (p == 0) *p1++ = *s++;
934 else if (p == 1) *p2++ = *s++;
935 else s++;
937 if (p == 0) *p1 = '\0';
938 if (p == 1) *p2 = '\0';
939 p++;
940 if (*s == '"') s++;
941 break;
942 case '\0':
943 return;
944 default:
945 while ((*s != '\0') && (*s != ' ') && (*s != '\t')
946 && (*s != '=') && (*s != ',') ) {
947 if (p == 0) *p1++ = *s++;
948 else if (p == 1) *p2++ = *s++;
949 else s++;
951 /* Skip concurrent parms */
952 while ((*s == ' ') || (*s == '\t') || (*s == '=') || (*s == ',') ) s++;
954 if (p == 0) *p1 = '\0';
955 if (p == 1) *p2 = '\0';
956 p++;
961 static void init_msvcrt_io_block(STARTUPINFOW* st)
963 STARTUPINFOW st_p;
964 /* fetch the parent MSVCRT info block if any, so that the child can use the
965 * same handles as its grand-father
967 st_p.cb = sizeof(STARTUPINFOW);
968 GetStartupInfoW(&st_p);
969 st->cbReserved2 = st_p.cbReserved2;
970 st->lpReserved2 = st_p.lpReserved2;
971 if (st_p.cbReserved2 && st_p.lpReserved2)
973 unsigned num = *(unsigned*)st_p.lpReserved2;
974 char* flags;
975 HANDLE* handles;
976 BYTE *ptr;
977 size_t sz;
979 /* Override the entries for fd 0,1,2 if we happened
980 * to change those std handles (this depends on the way cmd sets
981 * its new input & output handles)
983 sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
984 ptr = heap_xalloc(sz);
985 flags = (char*)(ptr + sizeof(unsigned));
986 handles = (HANDLE*)(flags + num * sizeof(char));
988 memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
989 st->cbReserved2 = sz;
990 st->lpReserved2 = ptr;
992 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
993 if (num <= 0 || (flags[0] & WX_OPEN))
995 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
996 flags[0] |= WX_OPEN;
998 if (num <= 1 || (flags[1] & WX_OPEN))
1000 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
1001 flags[1] |= WX_OPEN;
1003 if (num <= 2 || (flags[2] & WX_OPEN))
1005 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
1006 flags[2] |= WX_OPEN;
1008 #undef WX_OPEN
1012 /******************************************************************************
1013 * WCMD_run_program
1015 * Execute a command line as an external program. Must allow recursion.
1017 * Precedence:
1018 * Manual testing under windows shows PATHEXT plays a key part in this,
1019 * and the search algorithm and precedence appears to be as follows.
1021 * Search locations:
1022 * If directory supplied on command, just use that directory
1023 * If extension supplied on command, look for that explicit name first
1024 * Otherwise, search in each directory on the path
1025 * Precedence:
1026 * If extension supplied on command, look for that explicit name first
1027 * Then look for supplied name .* (even if extension supplied, so
1028 * 'garbage.exe' will match 'garbage.exe.cmd')
1029 * If any found, cycle through PATHEXT looking for name.exe one by one
1030 * Launching
1031 * Once a match has been found, it is launched - Code currently uses
1032 * findexecutable to achieve this which is left untouched.
1033 * If an executable has not been found, and we were launched through
1034 * a call, we need to check if the command is an internal command,
1035 * so go back through wcmd_execute.
1038 void WCMD_run_program (WCHAR *command, BOOL called)
1040 WCHAR temp[MAX_PATH];
1041 WCHAR pathtosearch[MAXSTRING];
1042 WCHAR *pathposn;
1043 WCHAR stemofsearch[MAX_PATH]; /* maximum allowed executable name is
1044 MAX_PATH, including null character */
1045 WCHAR *lastSlash;
1046 WCHAR pathext[MAXSTRING];
1047 WCHAR *firstParam;
1048 BOOL extensionsupplied = FALSE;
1049 BOOL status;
1050 DWORD len;
1051 static const WCHAR envPath[] = {'P','A','T','H','\0'};
1052 static const WCHAR delims[] = {'/','\\',':','\0'};
1054 /* Quick way to get the filename is to extract the first argument. */
1055 WINE_TRACE("Running '%s' (%d)\n", wine_dbgstr_w(command), called);
1056 firstParam = WCMD_parameter(command, 0, NULL, FALSE, TRUE);
1057 if (!firstParam) return;
1059 /* Calculate the search path and stem to search for */
1060 if (strpbrkW (firstParam, delims) == NULL) { /* No explicit path given, search path */
1061 static const WCHAR curDir[] = {'.',';','\0'};
1062 strcpyW(pathtosearch, curDir);
1063 len = GetEnvironmentVariableW(envPath, &pathtosearch[2], ARRAY_SIZE(pathtosearch)-2);
1064 if ((len == 0) || (len >= ARRAY_SIZE(pathtosearch) - 2)) {
1065 static const WCHAR curDir[] = {'.','\0'};
1066 strcpyW (pathtosearch, curDir);
1068 if (strchrW(firstParam, '.') != NULL) extensionsupplied = TRUE;
1069 if (strlenW(firstParam) >= MAX_PATH)
1071 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_LINETOOLONG));
1072 return;
1075 strcpyW(stemofsearch, firstParam);
1077 } else {
1079 /* Convert eg. ..\fred to include a directory by removing file part */
1080 GetFullPathNameW(firstParam, ARRAY_SIZE(pathtosearch), pathtosearch, NULL);
1081 lastSlash = strrchrW(pathtosearch, '\\');
1082 if (lastSlash && strchrW(lastSlash, '.') != NULL) extensionsupplied = TRUE;
1083 strcpyW(stemofsearch, lastSlash+1);
1085 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
1086 c:\windows\a.bat syntax */
1087 if (lastSlash) *(lastSlash + 1) = 0x00;
1090 /* Now extract PATHEXT */
1091 len = GetEnvironmentVariableW(envPathExt, pathext, ARRAY_SIZE(pathext));
1092 if ((len == 0) || (len >= ARRAY_SIZE(pathext))) {
1093 strcpyW (pathext, dfltPathExt);
1096 /* Loop through the search path, dir by dir */
1097 pathposn = pathtosearch;
1098 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch),
1099 wine_dbgstr_w(stemofsearch));
1100 while (pathposn) {
1101 WCHAR thisDir[MAX_PATH] = {'\0'};
1102 int length = 0;
1103 WCHAR *pos = NULL;
1104 BOOL found = FALSE;
1105 BOOL inside_quotes = FALSE;
1107 /* Work on the first directory on the search path */
1108 pos = pathposn;
1109 while ((inside_quotes || *pos != ';') && *pos != 0)
1111 if (*pos == '"')
1112 inside_quotes = !inside_quotes;
1113 pos++;
1116 if (*pos) { /* Reached semicolon */
1117 memcpy(thisDir, pathposn, (pos-pathposn) * sizeof(WCHAR));
1118 thisDir[(pos-pathposn)] = 0x00;
1119 pathposn = pos+1;
1120 } else { /* Reached string end */
1121 strcpyW(thisDir, pathposn);
1122 pathposn = NULL;
1125 /* Remove quotes */
1126 length = strlenW(thisDir);
1127 if (thisDir[length - 1] == '"')
1128 thisDir[length - 1] = 0;
1130 if (*thisDir != '"')
1131 strcpyW(temp, thisDir);
1132 else
1133 strcpyW(temp, thisDir + 1);
1135 /* Since you can have eg. ..\.. on the path, need to expand
1136 to full information */
1137 GetFullPathNameW(temp, MAX_PATH, thisDir, NULL);
1139 /* 1. If extension supplied, see if that file exists */
1140 strcatW(thisDir, slashW);
1141 strcatW(thisDir, stemofsearch);
1142 pos = &thisDir[strlenW(thisDir)]; /* Pos = end of name */
1144 /* 1. If extension supplied, see if that file exists */
1145 if (extensionsupplied) {
1146 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1147 found = TRUE;
1151 /* 2. Any .* matches? */
1152 if (!found) {
1153 HANDLE h;
1154 WIN32_FIND_DATAW finddata;
1155 static const WCHAR allFiles[] = {'.','*','\0'};
1157 strcatW(thisDir,allFiles);
1158 h = FindFirstFileW(thisDir, &finddata);
1159 FindClose(h);
1160 if (h != INVALID_HANDLE_VALUE) {
1162 WCHAR *thisExt = pathext;
1164 /* 3. Yes - Try each path ext */
1165 while (thisExt) {
1166 WCHAR *nextExt = strchrW(thisExt, ';');
1168 if (nextExt) {
1169 memcpy(pos, thisExt, (nextExt-thisExt) * sizeof(WCHAR));
1170 pos[(nextExt-thisExt)] = 0x00;
1171 thisExt = nextExt+1;
1172 } else {
1173 strcpyW(pos, thisExt);
1174 thisExt = NULL;
1177 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1178 found = TRUE;
1179 thisExt = NULL;
1185 /* Once found, launch it */
1186 if (found) {
1187 STARTUPINFOW st;
1188 PROCESS_INFORMATION pe;
1189 SHFILEINFOW psfi;
1190 DWORD console;
1191 HINSTANCE hinst;
1192 WCHAR *ext = strrchrW( thisDir, '.' );
1193 static const WCHAR batExt[] = {'.','b','a','t','\0'};
1194 static const WCHAR cmdExt[] = {'.','c','m','d','\0'};
1196 WINE_TRACE("Found as %s\n", wine_dbgstr_w(thisDir));
1198 /* Special case BAT and CMD */
1199 if (ext && (!strcmpiW(ext, batExt) || !strcmpiW(ext, cmdExt))) {
1200 BOOL oldinteractive = interactive;
1201 interactive = FALSE;
1202 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
1203 interactive = oldinteractive;
1204 return;
1205 } else {
1207 /* thisDir contains the file to be launched, but with what?
1208 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
1209 hinst = FindExecutableW (thisDir, NULL, temp);
1210 if ((INT_PTR)hinst < 32)
1211 console = 0;
1212 else
1213 console = SHGetFileInfoW(temp, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
1215 ZeroMemory (&st, sizeof(STARTUPINFOW));
1216 st.cb = sizeof(STARTUPINFOW);
1217 init_msvcrt_io_block(&st);
1219 /* Launch the process and if a CUI wait on it to complete
1220 Note: Launching internal wine processes cannot specify a full path to exe */
1221 status = CreateProcessW(thisDir,
1222 command, NULL, NULL, TRUE, 0, NULL, NULL, &st, &pe);
1223 heap_free(st.lpReserved2);
1224 if ((opt_c || opt_k) && !opt_s && !status
1225 && GetLastError()==ERROR_FILE_NOT_FOUND && command[0]=='\"') {
1226 /* strip first and last quote WCHARacters and try again */
1227 WCMD_strip_quotes(command);
1228 opt_s = TRUE;
1229 WCMD_run_program(command, called);
1230 return;
1233 if (!status)
1234 break;
1236 /* Always wait when non-interactive (cmd /c or in batch program),
1237 or for console applications */
1238 if (!interactive || (console && !HIWORD(console)))
1239 WaitForSingleObject (pe.hProcess, INFINITE);
1240 GetExitCodeProcess (pe.hProcess, &errorlevel);
1241 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
1243 CloseHandle(pe.hProcess);
1244 CloseHandle(pe.hThread);
1245 return;
1250 /* Not found anywhere - were we called? */
1251 if (called) {
1252 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
1254 /* Parse the command string, without reading any more input */
1255 WCMD_ReadAndParseLine(command, &toExecute, INVALID_HANDLE_VALUE);
1256 WCMD_process_commands(toExecute, FALSE, called);
1257 WCMD_free_commands(toExecute);
1258 toExecute = NULL;
1259 return;
1262 /* Not found anywhere - give up */
1263 WCMD_output_stderr(WCMD_LoadMessage(WCMD_NO_COMMAND_FOUND), command);
1265 /* If a command fails to launch, it sets errorlevel 9009 - which
1266 does not seem to have any associated constant definition */
1267 errorlevel = 9009;
1268 return;
1272 /*****************************************************************************
1273 * Process one command. If the command is EXIT this routine does not return.
1274 * We will recurse through here executing batch files.
1275 * Note: If call is used to a non-existing program, we reparse the line and
1276 * try to run it as an internal command. 'retrycall' represents whether
1277 * we are attempting this retry.
1279 void WCMD_execute (const WCHAR *command, const WCHAR *redirects,
1280 CMD_LIST **cmdList, BOOL retrycall)
1282 WCHAR *cmd, *parms_start, *redir;
1283 WCHAR *pos;
1284 int status, i, cmd_index;
1285 DWORD count, creationDisposition;
1286 HANDLE h;
1287 WCHAR *whichcmd;
1288 SECURITY_ATTRIBUTES sa;
1289 WCHAR *new_cmd = NULL;
1290 WCHAR *new_redir = NULL;
1291 HANDLE old_stdhandles[3] = {GetStdHandle (STD_INPUT_HANDLE),
1292 GetStdHandle (STD_OUTPUT_HANDLE),
1293 GetStdHandle (STD_ERROR_HANDLE)};
1294 DWORD idx_stdhandles[3] = {STD_INPUT_HANDLE,
1295 STD_OUTPUT_HANDLE,
1296 STD_ERROR_HANDLE};
1297 BOOL prev_echo_mode, piped = FALSE;
1299 WINE_TRACE("command on entry:%s (%p)\n",
1300 wine_dbgstr_w(command), cmdList);
1302 /* Move copy of the command onto the heap so it can be expanded */
1303 new_cmd = heap_xalloc(MAXSTRING * sizeof(WCHAR));
1304 strcpyW(new_cmd, command);
1305 cmd = new_cmd;
1307 /* Move copy of the redirects onto the heap so it can be expanded */
1308 new_redir = heap_xalloc(MAXSTRING * sizeof(WCHAR));
1309 redir = new_redir;
1311 /* Strip leading whitespaces, and a '@' if supplied */
1312 whichcmd = WCMD_skip_leading_spaces(cmd);
1313 WINE_TRACE("Command: '%s'\n", wine_dbgstr_w(cmd));
1314 if (whichcmd[0] == '@') whichcmd++;
1316 /* Check if the command entered is internal, and identify which one */
1317 count = 0;
1318 while (IsCharAlphaNumericW(whichcmd[count])) {
1319 count++;
1321 for (i=0; i<=WCMD_EXIT; i++) {
1322 if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1323 whichcmd, count, inbuilt[i], -1) == CSTR_EQUAL) break;
1325 cmd_index = i;
1326 parms_start = WCMD_skip_leading_spaces (&whichcmd[count]);
1328 /* If the next command is a pipe then we implement pipes by redirecting
1329 the output from this command to a temp file and input into the
1330 next command from that temp file.
1331 Note: Do not do this for a for or if statement as the pipe is for
1332 the individual statements, not the for or if itself.
1333 FIXME: Use of named pipes would make more sense here as currently this
1334 process has to finish before the next one can start but this requires
1335 a change to not wait for the first app to finish but rather the pipe */
1336 if (!(cmd_index == WCMD_FOR || cmd_index == WCMD_IF) &&
1337 cmdList && (*cmdList)->nextcommand &&
1338 (*cmdList)->nextcommand->prevDelim == CMD_PIPE) {
1340 WCHAR temp_path[MAX_PATH];
1341 static const WCHAR cmdW[] = {'C','M','D','\0'};
1343 /* Remember piping is in action */
1344 WINE_TRACE("Output needs to be piped\n");
1345 piped = TRUE;
1347 /* Generate a unique temporary filename */
1348 GetTempPathW(ARRAY_SIZE(temp_path), temp_path);
1349 GetTempFileNameW(temp_path, cmdW, 0, (*cmdList)->nextcommand->pipeFile);
1350 WINE_TRACE("Using temporary file of %s\n",
1351 wine_dbgstr_w((*cmdList)->nextcommand->pipeFile));
1354 /* If piped output, send stdout to the pipe by appending >filename to redirects */
1355 if (piped) {
1356 static const WCHAR redirOut[] = {'%','s',' ','>',' ','%','s','\0'};
1357 wsprintfW (new_redir, redirOut, redirects, (*cmdList)->nextcommand->pipeFile);
1358 WINE_TRACE("Redirects now %s\n", wine_dbgstr_w(new_redir));
1359 } else {
1360 strcpyW(new_redir, redirects);
1363 /* Expand variables in command line mode only (batch mode will
1364 be expanded as the line is read in, except for 'for' loops) */
1365 handleExpansion(new_cmd, (context != NULL), delayedsubst);
1366 handleExpansion(new_redir, (context != NULL), delayedsubst);
1369 * Changing default drive has to be handled as a special case, anything
1370 * else if it exists after whitespace is ignored
1373 if ((cmd[1] == ':') && IsCharAlphaW(cmd[0]) &&
1374 (!cmd[2] || cmd[2] == ' ' || cmd[2] == '\t')) {
1375 WCHAR envvar[5];
1376 WCHAR dir[MAX_PATH];
1378 /* Ignore potential garbage on the same line */
1379 cmd[2]=0x00;
1381 /* According to MSDN CreateProcess docs, special env vars record
1382 the current directory on each drive, in the form =C:
1383 so see if one specified, and if so go back to it */
1384 strcpyW(envvar, equalW);
1385 strcatW(envvar, cmd);
1386 if (GetEnvironmentVariableW(envvar, dir, MAX_PATH) == 0) {
1387 static const WCHAR fmt[] = {'%','s','\\','\0'};
1388 wsprintfW(cmd, fmt, cmd);
1389 WINE_TRACE("No special directory settings, using dir of %s\n", wine_dbgstr_w(cmd));
1391 WINE_TRACE("Got directory %s as %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(cmd));
1392 status = SetCurrentDirectoryW(cmd);
1393 if (!status) WCMD_print_error ();
1394 heap_free(cmd );
1395 heap_free(new_redir);
1396 return;
1399 sa.nLength = sizeof(sa);
1400 sa.lpSecurityDescriptor = NULL;
1401 sa.bInheritHandle = TRUE;
1404 * Redirect stdin, stdout and/or stderr if required.
1405 * Note: Do not do this for a for or if statement as the pipe is for
1406 * the individual statements, not the for or if itself.
1408 if (!(cmd_index == WCMD_FOR || cmd_index == WCMD_IF)) {
1409 /* STDIN could come from a preceding pipe, so delete on close if it does */
1410 if (cmdList && (*cmdList)->pipeFile[0] != 0x00) {
1411 WINE_TRACE("Input coming from %s\n", wine_dbgstr_w((*cmdList)->pipeFile));
1412 h = CreateFileW((*cmdList)->pipeFile, GENERIC_READ,
1413 FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING,
1414 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL);
1415 if (h == INVALID_HANDLE_VALUE) {
1416 WCMD_print_error ();
1417 heap_free(cmd);
1418 heap_free(new_redir);
1419 return;
1421 SetStdHandle (STD_INPUT_HANDLE, h);
1423 /* No need to remember the temporary name any longer once opened */
1424 (*cmdList)->pipeFile[0] = 0x00;
1426 /* Otherwise STDIN could come from a '<' redirect */
1427 } else if ((pos = strchrW(new_redir,'<')) != NULL) {
1428 h = CreateFileW(WCMD_parameter(++pos, 0, NULL, FALSE, FALSE), GENERIC_READ, FILE_SHARE_READ,
1429 &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1430 if (h == INVALID_HANDLE_VALUE) {
1431 WCMD_print_error ();
1432 heap_free(cmd);
1433 heap_free(new_redir);
1434 return;
1436 SetStdHandle (STD_INPUT_HANDLE, h);
1439 /* Scan the whole command looking for > and 2> */
1440 while (redir != NULL && ((pos = strchrW(redir,'>')) != NULL)) {
1441 int handle = 0;
1443 if (pos > redir && (*(pos-1)=='2'))
1444 handle = 2;
1445 else
1446 handle = 1;
1448 pos++;
1449 if ('>' == *pos) {
1450 creationDisposition = OPEN_ALWAYS;
1451 pos++;
1453 else {
1454 creationDisposition = CREATE_ALWAYS;
1457 /* Add support for 2>&1 */
1458 redir = pos;
1459 if (*pos == '&') {
1460 int idx = *(pos+1) - '0';
1462 if (DuplicateHandle(GetCurrentProcess(),
1463 GetStdHandle(idx_stdhandles[idx]),
1464 GetCurrentProcess(),
1466 0, TRUE, DUPLICATE_SAME_ACCESS) == 0) {
1467 WINE_FIXME("Duplicating handle failed with gle %d\n", GetLastError());
1469 WINE_TRACE("Redirect %d (%p) to %d (%p)\n", handle, GetStdHandle(idx_stdhandles[idx]), idx, h);
1471 } else {
1472 WCHAR *param = WCMD_parameter(pos, 0, NULL, FALSE, FALSE);
1473 h = CreateFileW(param, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE,
1474 &sa, creationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
1475 if (h == INVALID_HANDLE_VALUE) {
1476 WCMD_print_error ();
1477 heap_free(cmd);
1478 heap_free(new_redir);
1479 return;
1481 if (SetFilePointer (h, 0, NULL, FILE_END) ==
1482 INVALID_SET_FILE_POINTER) {
1483 WCMD_print_error ();
1485 WINE_TRACE("Redirect %d to '%s' (%p)\n", handle, wine_dbgstr_w(param), h);
1488 SetStdHandle (idx_stdhandles[handle], h);
1490 } else {
1491 WINE_TRACE("Not touching redirects for a FOR or IF command\n");
1493 WCMD_parse (parms_start, quals, param1, param2);
1494 WINE_TRACE("param1: %s, param2: %s\n", wine_dbgstr_w(param1), wine_dbgstr_w(param2));
1496 if (i <= WCMD_EXIT && (parms_start[0] == '/') && (parms_start[1] == '?')) {
1497 /* this is a help request for a builtin program */
1498 i = WCMD_HELP;
1499 memcpy(parms_start, whichcmd, count * sizeof(WCHAR));
1500 parms_start[count] = '\0';
1504 switch (i) {
1506 case WCMD_CALL:
1507 WCMD_call (parms_start);
1508 break;
1509 case WCMD_CD:
1510 case WCMD_CHDIR:
1511 WCMD_setshow_default (parms_start);
1512 break;
1513 case WCMD_CLS:
1514 WCMD_clear_screen ();
1515 break;
1516 case WCMD_COPY:
1517 WCMD_copy (parms_start);
1518 break;
1519 case WCMD_CTTY:
1520 WCMD_change_tty ();
1521 break;
1522 case WCMD_DATE:
1523 WCMD_setshow_date ();
1524 break;
1525 case WCMD_DEL:
1526 case WCMD_ERASE:
1527 WCMD_delete (parms_start);
1528 break;
1529 case WCMD_DIR:
1530 WCMD_directory (parms_start);
1531 break;
1532 case WCMD_ECHO:
1533 WCMD_echo(&whichcmd[count]);
1534 break;
1535 case WCMD_GOTO:
1536 WCMD_goto (cmdList);
1537 break;
1538 case WCMD_HELP:
1539 WCMD_give_help (parms_start);
1540 break;
1541 case WCMD_LABEL:
1542 WCMD_volume (TRUE, parms_start);
1543 break;
1544 case WCMD_MD:
1545 case WCMD_MKDIR:
1546 WCMD_create_dir (parms_start);
1547 break;
1548 case WCMD_MOVE:
1549 WCMD_move ();
1550 break;
1551 case WCMD_PATH:
1552 WCMD_setshow_path (parms_start);
1553 break;
1554 case WCMD_PAUSE:
1555 WCMD_pause ();
1556 break;
1557 case WCMD_PROMPT:
1558 WCMD_setshow_prompt ();
1559 break;
1560 case WCMD_REM:
1561 break;
1562 case WCMD_REN:
1563 case WCMD_RENAME:
1564 WCMD_rename ();
1565 break;
1566 case WCMD_RD:
1567 case WCMD_RMDIR:
1568 WCMD_remove_dir (parms_start);
1569 break;
1570 case WCMD_SETLOCAL:
1571 WCMD_setlocal(parms_start);
1572 break;
1573 case WCMD_ENDLOCAL:
1574 WCMD_endlocal();
1575 break;
1576 case WCMD_SET:
1577 WCMD_setshow_env (parms_start);
1578 break;
1579 case WCMD_SHIFT:
1580 WCMD_shift (parms_start);
1581 break;
1582 case WCMD_START:
1583 WCMD_start (parms_start);
1584 break;
1585 case WCMD_TIME:
1586 WCMD_setshow_time ();
1587 break;
1588 case WCMD_TITLE:
1589 if (strlenW(&whichcmd[count]) > 0)
1590 WCMD_title(&whichcmd[count+1]);
1591 break;
1592 case WCMD_TYPE:
1593 WCMD_type (parms_start);
1594 break;
1595 case WCMD_VER:
1596 WCMD_output_asis(newlineW);
1597 WCMD_version ();
1598 break;
1599 case WCMD_VERIFY:
1600 WCMD_verify (parms_start);
1601 break;
1602 case WCMD_VOL:
1603 WCMD_volume (FALSE, parms_start);
1604 break;
1605 case WCMD_PUSHD:
1606 WCMD_pushd(parms_start);
1607 break;
1608 case WCMD_POPD:
1609 WCMD_popd();
1610 break;
1611 case WCMD_ASSOC:
1612 WCMD_assoc(parms_start, TRUE);
1613 break;
1614 case WCMD_COLOR:
1615 WCMD_color();
1616 break;
1617 case WCMD_FTYPE:
1618 WCMD_assoc(parms_start, FALSE);
1619 break;
1620 case WCMD_MORE:
1621 WCMD_more(parms_start);
1622 break;
1623 case WCMD_CHOICE:
1624 WCMD_choice(parms_start);
1625 break;
1626 case WCMD_MKLINK:
1627 WCMD_mklink(parms_start);
1628 break;
1629 case WCMD_EXIT:
1630 WCMD_exit (cmdList);
1631 break;
1632 case WCMD_FOR:
1633 case WCMD_IF:
1634 /* Very oddly, probably because of all the special parsing required for
1635 these two commands, neither 'for' nor 'if' is supported when called,
1636 i.e. 'call if 1==1...' will fail. */
1637 if (!retrycall) {
1638 if (i==WCMD_FOR) WCMD_for (parms_start, cmdList);
1639 else if (i==WCMD_IF) WCMD_if (parms_start, cmdList);
1640 break;
1642 /* else: drop through */
1643 default:
1644 prev_echo_mode = echo_mode;
1645 WCMD_run_program (whichcmd, FALSE);
1646 echo_mode = prev_echo_mode;
1648 heap_free(cmd);
1649 heap_free(new_redir);
1651 /* Restore old handles */
1652 for (i=0; i<3; i++) {
1653 if (old_stdhandles[i] != GetStdHandle(idx_stdhandles[i])) {
1654 CloseHandle (GetStdHandle (idx_stdhandles[i]));
1655 SetStdHandle (idx_stdhandles[i], old_stdhandles[i]);
1660 /*************************************************************************
1661 * WCMD_LoadMessage
1662 * Load a string from the resource file, handling any error
1663 * Returns string retrieved from resource file
1665 WCHAR *WCMD_LoadMessage(UINT id) {
1666 static WCHAR msg[2048];
1667 static const WCHAR failedMsg[] = {'F','a','i','l','e','d','!','\0'};
1669 if (!LoadStringW(GetModuleHandleW(NULL), id, msg, ARRAY_SIZE(msg))) {
1670 WINE_FIXME("LoadString failed with %d\n", GetLastError());
1671 strcpyW(msg, failedMsg);
1673 return msg;
1676 /***************************************************************************
1677 * WCMD_DumpCommands
1679 * Dumps out the parsed command line to ensure syntax is correct
1681 static void WCMD_DumpCommands(CMD_LIST *commands) {
1682 CMD_LIST *thisCmd = commands;
1684 WINE_TRACE("Parsed line:\n");
1685 while (thisCmd != NULL) {
1686 WINE_TRACE("%p %d %2.2d %p %s Redir:%s\n",
1687 thisCmd,
1688 thisCmd->prevDelim,
1689 thisCmd->bracketDepth,
1690 thisCmd->nextcommand,
1691 wine_dbgstr_w(thisCmd->command),
1692 wine_dbgstr_w(thisCmd->redirects));
1693 thisCmd = thisCmd->nextcommand;
1697 /***************************************************************************
1698 * WCMD_addCommand
1700 * Adds a command to the current command list
1702 static void WCMD_addCommand(WCHAR *command, int *commandLen,
1703 WCHAR *redirs, int *redirLen,
1704 WCHAR **copyTo, int **copyToLen,
1705 CMD_DELIMITERS prevDelim, int curDepth,
1706 CMD_LIST **lastEntry, CMD_LIST **output) {
1708 CMD_LIST *thisEntry = NULL;
1710 /* Allocate storage for command */
1711 thisEntry = heap_xalloc(sizeof(CMD_LIST));
1713 /* Copy in the command */
1714 if (command) {
1715 thisEntry->command = heap_xalloc((*commandLen+1) * sizeof(WCHAR));
1716 memcpy(thisEntry->command, command, *commandLen * sizeof(WCHAR));
1717 thisEntry->command[*commandLen] = 0x00;
1719 /* Copy in the redirects */
1720 thisEntry->redirects = heap_xalloc((*redirLen+1) * sizeof(WCHAR));
1721 memcpy(thisEntry->redirects, redirs, *redirLen * sizeof(WCHAR));
1722 thisEntry->redirects[*redirLen] = 0x00;
1723 thisEntry->pipeFile[0] = 0x00;
1725 /* Reset the lengths */
1726 *commandLen = 0;
1727 *redirLen = 0;
1728 *copyToLen = commandLen;
1729 *copyTo = command;
1731 } else {
1732 thisEntry->command = NULL;
1733 thisEntry->redirects = NULL;
1734 thisEntry->pipeFile[0] = 0x00;
1737 /* Fill in other fields */
1738 thisEntry->nextcommand = NULL;
1739 thisEntry->prevDelim = prevDelim;
1740 thisEntry->bracketDepth = curDepth;
1741 if (*lastEntry) {
1742 (*lastEntry)->nextcommand = thisEntry;
1743 } else {
1744 *output = thisEntry;
1746 *lastEntry = thisEntry;
1750 /***************************************************************************
1751 * WCMD_IsEndQuote
1753 * Checks if the quote pointed to is the end-quote.
1755 * Quotes end if:
1757 * 1) The current parameter ends at EOL or at the beginning
1758 * of a redirection or pipe and not in a quote section.
1760 * 2) If the next character is a space and not in a quote section.
1762 * Returns TRUE if this is an end quote, and FALSE if it is not.
1765 static BOOL WCMD_IsEndQuote(const WCHAR *quote, int quoteIndex)
1767 int quoteCount = quoteIndex;
1768 int i;
1770 /* If we are not in a quoted section, then we are not an end-quote */
1771 if(quoteIndex == 0)
1773 return FALSE;
1776 /* Check how many quotes are left for this parameter */
1777 for(i=0;quote[i];i++)
1779 if(quote[i] == '"')
1781 quoteCount++;
1784 /* Quote counting ends at EOL, redirection, space or pipe if current quote is complete */
1785 else if(((quoteCount % 2) == 0)
1786 && ((quote[i] == '<') || (quote[i] == '>') || (quote[i] == '|') || (quote[i] == ' ')))
1788 break;
1792 /* If the quote is part of the last part of a series of quotes-on-quotes, then it must
1793 be an end-quote */
1794 if(quoteIndex >= (quoteCount / 2))
1796 return TRUE;
1799 /* No cigar */
1800 return FALSE;
1803 /***************************************************************************
1804 * WCMD_ReadAndParseLine
1806 * Either uses supplied input or
1807 * Reads a file from the handle, and then...
1808 * Parse the text buffer, splitting into separate commands
1809 * - unquoted && strings split 2 commands but the 2nd is flagged as
1810 * following an &&
1811 * - ( as the first character just ups the bracket depth
1812 * - unquoted ) when bracket depth > 0 terminates a bracket and
1813 * adds a CMD_LIST structure with null command
1814 * - Anything else gets put into the command string (including
1815 * redirects)
1817 WCHAR *WCMD_ReadAndParseLine(const WCHAR *optionalcmd, CMD_LIST **output, HANDLE readFrom)
1819 WCHAR *curPos;
1820 int inQuotes = 0;
1821 WCHAR curString[MAXSTRING];
1822 int curStringLen = 0;
1823 WCHAR curRedirs[MAXSTRING];
1824 int curRedirsLen = 0;
1825 WCHAR *curCopyTo;
1826 int *curLen;
1827 int curDepth = 0;
1828 CMD_LIST *lastEntry = NULL;
1829 CMD_DELIMITERS prevDelim = CMD_NONE;
1830 static WCHAR *extraSpace = NULL; /* Deliberately never freed */
1831 static const WCHAR remCmd[] = {'r','e','m'};
1832 static const WCHAR forCmd[] = {'f','o','r'};
1833 static const WCHAR ifCmd[] = {'i','f'};
1834 static const WCHAR ifElse[] = {'e','l','s','e'};
1835 BOOL inOneLine = FALSE;
1836 BOOL inFor = FALSE;
1837 BOOL inIn = FALSE;
1838 BOOL inIf = FALSE;
1839 BOOL inElse= FALSE;
1840 BOOL onlyWhiteSpace = FALSE;
1841 BOOL lastWasWhiteSpace = FALSE;
1842 BOOL lastWasDo = FALSE;
1843 BOOL lastWasIn = FALSE;
1844 BOOL lastWasElse = FALSE;
1845 BOOL lastWasRedirect = TRUE;
1846 BOOL lastWasCaret = FALSE;
1847 int lineCurDepth; /* Bracket depth when line was read in */
1848 BOOL resetAtEndOfLine = FALSE; /* Do we need to reset curdepth at EOL */
1850 /* Allocate working space for a command read from keyboard, file etc */
1851 if (!extraSpace)
1852 extraSpace = heap_xalloc((MAXSTRING+1) * sizeof(WCHAR));
1853 if (!extraSpace)
1855 WINE_ERR("Could not allocate memory for extraSpace\n");
1856 return NULL;
1859 /* If initial command read in, use that, otherwise get input from handle */
1860 if (optionalcmd != NULL) {
1861 strcpyW(extraSpace, optionalcmd);
1862 } else if (readFrom == INVALID_HANDLE_VALUE) {
1863 WINE_FIXME("No command nor handle supplied\n");
1864 } else {
1865 if (!WCMD_fgets(extraSpace, MAXSTRING, readFrom))
1866 return NULL;
1868 curPos = extraSpace;
1870 /* Handle truncated input - issue warning */
1871 if (strlenW(extraSpace) == MAXSTRING -1) {
1872 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_TRUNCATEDLINE));
1873 WCMD_output_asis_stderr(extraSpace);
1874 WCMD_output_asis_stderr(newlineW);
1877 /* Replace env vars if in a batch context */
1878 if (context) handleExpansion(extraSpace, FALSE, FALSE);
1880 /* Skip preceding whitespace */
1881 while (*curPos == ' ' || *curPos == '\t') curPos++;
1883 /* Show prompt before batch line IF echo is on and in batch program */
1884 if (context && echo_mode && *curPos && (*curPos != '@')) {
1885 static const WCHAR echoDot[] = {'e','c','h','o','.'};
1886 static const WCHAR echoCol[] = {'e','c','h','o',':'};
1887 static const WCHAR echoSlash[] = {'e','c','h','o','/'};
1888 const DWORD len = ARRAY_SIZE(echoDot);
1889 DWORD curr_size = strlenW(curPos);
1890 DWORD min_len = (curr_size < len ? curr_size : len);
1891 WCMD_show_prompt(TRUE);
1892 WCMD_output_asis(curPos);
1893 /* I don't know why Windows puts a space here but it does */
1894 /* Except for lines starting with 'echo.', 'echo:' or 'echo/'. Ask MS why */
1895 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1896 curPos, min_len, echoDot, len) != CSTR_EQUAL
1897 && CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1898 curPos, min_len, echoCol, len) != CSTR_EQUAL
1899 && CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1900 curPos, min_len, echoSlash, len) != CSTR_EQUAL)
1902 WCMD_output_asis(spaceW);
1904 WCMD_output_asis(newlineW);
1907 /* Skip repeated 'no echo' characters */
1908 while (*curPos == '@') curPos++;
1910 /* Start with an empty string, copying to the command string */
1911 curStringLen = 0;
1912 curRedirsLen = 0;
1913 curCopyTo = curString;
1914 curLen = &curStringLen;
1915 lastWasRedirect = FALSE; /* Required e.g. for spaces between > and filename */
1916 lineCurDepth = curDepth; /* What was the curdepth at the beginning of the line */
1918 /* Parse every character on the line being processed */
1919 while (*curPos != 0x00) {
1921 WCHAR thisChar;
1923 /* Debugging AID:
1924 WINE_TRACE("Looking at '%c' (len:%d, lws:%d, ows:%d)\n", *curPos, *curLen,
1925 lastWasWhiteSpace, onlyWhiteSpace);
1928 /* Prevent overflow caused by the caret escape char */
1929 if (*curLen >= MAXSTRING) {
1930 WINE_ERR("Overflow detected in command\n");
1931 return NULL;
1934 /* Certain commands need special handling */
1935 if (curStringLen == 0 && curCopyTo == curString) {
1936 static const WCHAR forDO[] = {'d','o'};
1938 /* If command starts with 'rem ' or identifies a label, ignore any &&, ( etc. */
1939 if (WCMD_keyword_ws_found(remCmd, ARRAY_SIZE(remCmd), curPos) || *curPos == ':') {
1940 inOneLine = TRUE;
1942 } else if (WCMD_keyword_ws_found(forCmd, ARRAY_SIZE(forCmd), curPos)) {
1943 inFor = TRUE;
1945 /* If command starts with 'if ' or 'else ', handle ('s mid line. We should ensure this
1946 is only true in the command portion of the IF statement, but this
1947 should suffice for now
1948 FIXME: Silly syntax like "if 1(==1( (
1949 echo they equal
1950 )" will be parsed wrong */
1951 } else if (WCMD_keyword_ws_found(ifCmd, ARRAY_SIZE(ifCmd), curPos)) {
1952 inIf = TRUE;
1954 } else if (WCMD_keyword_ws_found(ifElse, ARRAY_SIZE(ifElse), curPos)) {
1955 const int keyw_len = ARRAY_SIZE(ifElse) + 1;
1956 inElse = TRUE;
1957 lastWasElse = TRUE;
1958 onlyWhiteSpace = TRUE;
1959 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1960 (*curLen)+=keyw_len;
1961 curPos+=keyw_len;
1963 /* If we had a single line if XXX which reaches an else (needs odd
1964 syntax like if 1=1 command && (command) else command we pretended
1965 to add brackets for the if, so they are now over */
1966 if (resetAtEndOfLine) {
1967 WINE_TRACE("Resetting curdepth at end of line to %d\n", lineCurDepth);
1968 resetAtEndOfLine = FALSE;
1969 curDepth = lineCurDepth;
1971 continue;
1973 /* In a for loop, the DO command will follow a close bracket followed by
1974 whitespace, followed by DO, ie closeBracket inserts a NULL entry, curLen
1975 is then 0, and all whitespace is skipped */
1976 } else if (inFor && WCMD_keyword_ws_found(forDO, ARRAY_SIZE(forDO), curPos)) {
1977 const int keyw_len = ARRAY_SIZE(forDO) + 1;
1978 WINE_TRACE("Found 'DO '\n");
1979 lastWasDo = TRUE;
1980 onlyWhiteSpace = TRUE;
1981 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1982 (*curLen)+=keyw_len;
1983 curPos+=keyw_len;
1984 continue;
1986 } else if (curCopyTo == curString) {
1988 /* Special handling for the 'FOR' command */
1989 if (inFor && lastWasWhiteSpace) {
1990 static const WCHAR forIN[] = {'i','n'};
1992 WINE_TRACE("Found 'FOR ', comparing next parm: '%s'\n", wine_dbgstr_w(curPos));
1994 if (WCMD_keyword_ws_found(forIN, ARRAY_SIZE(forIN), curPos)) {
1995 const int keyw_len = ARRAY_SIZE(forIN) + 1;
1996 WINE_TRACE("Found 'IN '\n");
1997 lastWasIn = TRUE;
1998 onlyWhiteSpace = TRUE;
1999 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
2000 (*curLen)+=keyw_len;
2001 curPos+=keyw_len;
2002 continue;
2007 /* Nothing 'ends' a one line statement (e.g. REM or :labels mean
2008 the &&, quotes and redirection etc are ineffective, so just force
2009 the use of the default processing by skipping character specific
2010 matching below) */
2011 if (!inOneLine) thisChar = *curPos;
2012 else thisChar = 'X'; /* Character with no special processing */
2014 lastWasWhiteSpace = FALSE; /* Will be reset below */
2015 lastWasCaret = FALSE;
2017 switch (thisChar) {
2019 case '=': /* drop through - ignore token delimiters at the start of a command */
2020 case ',': /* drop through - ignore token delimiters at the start of a command */
2021 case '\t':/* drop through - ignore token delimiters at the start of a command */
2022 case ' ':
2023 /* If a redirect in place, it ends here */
2024 if (!inQuotes && !lastWasRedirect) {
2026 /* If finishing off a redirect, add a whitespace delimiter */
2027 if (curCopyTo == curRedirs) {
2028 curCopyTo[(*curLen)++] = ' ';
2030 curCopyTo = curString;
2031 curLen = &curStringLen;
2033 if (*curLen > 0) {
2034 curCopyTo[(*curLen)++] = *curPos;
2037 /* Remember just processed whitespace */
2038 lastWasWhiteSpace = TRUE;
2040 break;
2042 case '>': /* drop through - handle redirect chars the same */
2043 case '<':
2044 /* Make a redirect start here */
2045 if (!inQuotes) {
2046 curCopyTo = curRedirs;
2047 curLen = &curRedirsLen;
2048 lastWasRedirect = TRUE;
2051 /* See if 1>, 2> etc, in which case we have some patching up
2052 to do (provided there's a preceding whitespace, and enough
2053 chars read so far) */
2054 if (curStringLen > 2
2055 && (*(curPos-1)>='1') && (*(curPos-1)<='9')
2056 && ((*(curPos-2)==' ') || (*(curPos-2)=='\t'))) {
2057 curStringLen--;
2058 curString[curStringLen] = 0x00;
2059 curCopyTo[(*curLen)++] = *(curPos-1);
2062 curCopyTo[(*curLen)++] = *curPos;
2064 /* If a redirect is immediately followed by '&' (ie. 2>&1) then
2065 do not process that ampersand as an AND operator */
2066 if (thisChar == '>' && *(curPos+1) == '&') {
2067 curCopyTo[(*curLen)++] = *(curPos+1);
2068 curPos++;
2070 break;
2072 case '|': /* Pipe character only if not || */
2073 if (!inQuotes) {
2074 lastWasRedirect = FALSE;
2076 /* Add an entry to the command list */
2077 if (curStringLen > 0) {
2079 /* Add the current command */
2080 WCMD_addCommand(curString, &curStringLen,
2081 curRedirs, &curRedirsLen,
2082 &curCopyTo, &curLen,
2083 prevDelim, curDepth,
2084 &lastEntry, output);
2088 if (*(curPos+1) == '|') {
2089 curPos++; /* Skip other | */
2090 prevDelim = CMD_ONFAILURE;
2091 } else {
2092 prevDelim = CMD_PIPE;
2095 /* If in an IF or ELSE statement, put subsequent chained
2096 commands at a higher depth as if brackets were supplied
2097 but remember to reset to the original depth at EOL */
2098 if ((inIf || inElse) && curDepth == lineCurDepth) {
2099 curDepth++;
2100 resetAtEndOfLine = TRUE;
2102 } else {
2103 curCopyTo[(*curLen)++] = *curPos;
2105 break;
2107 case '"': if (WCMD_IsEndQuote(curPos, inQuotes)) {
2108 inQuotes--;
2109 } else {
2110 inQuotes++; /* Quotes within quotes are fun! */
2112 curCopyTo[(*curLen)++] = *curPos;
2113 lastWasRedirect = FALSE;
2114 break;
2116 case '(': /* If a '(' is the first non whitespace in a command portion
2117 ie start of line or just after &&, then we read until an
2118 unquoted ) is found */
2119 WINE_TRACE("Found '(' conditions: curLen(%d), inQ(%d), onlyWS(%d)"
2120 ", for(%d, In:%d, Do:%d)"
2121 ", if(%d, else:%d, lwe:%d)\n",
2122 *curLen, inQuotes,
2123 onlyWhiteSpace,
2124 inFor, lastWasIn, lastWasDo,
2125 inIf, inElse, lastWasElse);
2126 lastWasRedirect = FALSE;
2128 /* Ignore open brackets inside the for set */
2129 if (*curLen == 0 && !inIn) {
2130 curDepth++;
2132 /* If in quotes, ignore brackets */
2133 } else if (inQuotes) {
2134 curCopyTo[(*curLen)++] = *curPos;
2136 /* In a FOR loop, an unquoted '(' may occur straight after
2137 IN or DO
2138 In an IF statement just handle it regardless as we don't
2139 parse the operands
2140 In an ELSE statement, only allow it straight away after
2141 the ELSE and whitespace
2143 } else if (inIf ||
2144 (inElse && lastWasElse && onlyWhiteSpace) ||
2145 (inFor && (lastWasIn || lastWasDo) && onlyWhiteSpace)) {
2147 /* If entering into an 'IN', set inIn */
2148 if (inFor && lastWasIn && onlyWhiteSpace) {
2149 WINE_TRACE("Inside an IN\n");
2150 inIn = TRUE;
2153 /* Add the current command */
2154 WCMD_addCommand(curString, &curStringLen,
2155 curRedirs, &curRedirsLen,
2156 &curCopyTo, &curLen,
2157 prevDelim, curDepth,
2158 &lastEntry, output);
2160 curDepth++;
2161 } else {
2162 curCopyTo[(*curLen)++] = *curPos;
2164 break;
2166 case '^': if (!inQuotes) {
2167 /* If we reach the end of the input, we need to wait for more */
2168 if (*(curPos+1) == 0x00) {
2169 lastWasCaret = TRUE;
2170 WINE_TRACE("Caret found at end of line\n");
2171 break;
2173 curPos++;
2175 curCopyTo[(*curLen)++] = *curPos;
2176 break;
2178 case '&': if (!inQuotes) {
2179 lastWasRedirect = FALSE;
2181 /* Add an entry to the command list */
2182 if (curStringLen > 0) {
2184 /* Add the current command */
2185 WCMD_addCommand(curString, &curStringLen,
2186 curRedirs, &curRedirsLen,
2187 &curCopyTo, &curLen,
2188 prevDelim, curDepth,
2189 &lastEntry, output);
2193 if (*(curPos+1) == '&') {
2194 curPos++; /* Skip other & */
2195 prevDelim = CMD_ONSUCCESS;
2196 } else {
2197 prevDelim = CMD_NONE;
2199 /* If in an IF or ELSE statement, put subsequent chained
2200 commands at a higher depth as if brackets were supplied
2201 but remember to reset to the original depth at EOL */
2202 if ((inIf || inElse) && curDepth == lineCurDepth) {
2203 curDepth++;
2204 resetAtEndOfLine = TRUE;
2206 } else {
2207 curCopyTo[(*curLen)++] = *curPos;
2209 break;
2211 case ')': if (!inQuotes && curDepth > 0) {
2212 lastWasRedirect = FALSE;
2214 /* Add the current command if there is one */
2215 if (curStringLen) {
2217 /* Add the current command */
2218 WCMD_addCommand(curString, &curStringLen,
2219 curRedirs, &curRedirsLen,
2220 &curCopyTo, &curLen,
2221 prevDelim, curDepth,
2222 &lastEntry, output);
2225 /* Add an empty entry to the command list */
2226 prevDelim = CMD_NONE;
2227 WCMD_addCommand(NULL, &curStringLen,
2228 curRedirs, &curRedirsLen,
2229 &curCopyTo, &curLen,
2230 prevDelim, curDepth,
2231 &lastEntry, output);
2232 curDepth--;
2234 /* Leave inIn if necessary */
2235 if (inIn) inIn = FALSE;
2236 } else {
2237 curCopyTo[(*curLen)++] = *curPos;
2239 break;
2240 default:
2241 lastWasRedirect = FALSE;
2242 curCopyTo[(*curLen)++] = *curPos;
2245 curPos++;
2247 /* At various times we need to know if we have only skipped whitespace,
2248 so reset this variable and then it will remain true until a non
2249 whitespace is found */
2250 if ((thisChar != ' ') && (thisChar != '\t') && (thisChar != '\n'))
2251 onlyWhiteSpace = FALSE;
2253 /* Flag end of interest in FOR DO and IN parms once something has been processed */
2254 if (!lastWasWhiteSpace) {
2255 lastWasIn = lastWasDo = FALSE;
2258 /* If we have reached the end, add this command into the list
2259 Do not add command to list if escape char ^ was last */
2260 if (*curPos == 0x00 && !lastWasCaret && *curLen > 0) {
2262 /* Add an entry to the command list */
2263 WCMD_addCommand(curString, &curStringLen,
2264 curRedirs, &curRedirsLen,
2265 &curCopyTo, &curLen,
2266 prevDelim, curDepth,
2267 &lastEntry, output);
2269 /* If we had a single line if or else, and we pretended to add
2270 brackets, end them now */
2271 if (resetAtEndOfLine) {
2272 WINE_TRACE("Resetting curdepth at end of line to %d\n", lineCurDepth);
2273 resetAtEndOfLine = FALSE;
2274 curDepth = lineCurDepth;
2278 /* If we have reached the end of the string, see if bracketing or
2279 final caret is outstanding */
2280 if (*curPos == 0x00 && (curDepth > 0 || lastWasCaret) &&
2281 readFrom != INVALID_HANDLE_VALUE) {
2282 WCHAR *extraData;
2284 WINE_TRACE("Need to read more data as outstanding brackets or carets\n");
2285 inOneLine = FALSE;
2286 prevDelim = CMD_NONE;
2287 inQuotes = 0;
2288 memset(extraSpace, 0x00, (MAXSTRING+1) * sizeof(WCHAR));
2289 extraData = extraSpace;
2291 /* Read more, skipping any blank lines */
2292 do {
2293 WINE_TRACE("Read more input\n");
2294 if (!context) WCMD_output_asis( WCMD_LoadMessage(WCMD_MOREPROMPT));
2295 if (!WCMD_fgets(extraData, MAXSTRING, readFrom))
2296 break;
2298 /* Edge case for carets - a completely blank line (i.e. was just
2299 CRLF) is oddly added as an LF but then more data is received (but
2300 only once more!) */
2301 if (lastWasCaret) {
2302 if (*extraSpace == 0x00) {
2303 WINE_TRACE("Read nothing, so appending LF char and will try again\n");
2304 *extraData++ = '\r';
2305 *extraData = 0x00;
2306 } else break;
2309 } while (*extraData == 0x00);
2310 curPos = extraSpace;
2312 /* Skip preceding whitespace */
2313 while (*curPos == ' ' || *curPos == '\t') curPos++;
2315 /* Replace env vars if in a batch context */
2316 if (context) handleExpansion(curPos, FALSE, FALSE);
2318 /* Continue to echo commands IF echo is on and in batch program */
2319 if (context && echo_mode && *curPos && *curPos != '@') {
2320 WCMD_output_asis(extraSpace);
2321 WCMD_output_asis(newlineW);
2324 /* Skip repeated 'no echo' characters and whitespace */
2325 while (*curPos == '@' || *curPos == ' ' || *curPos == '\t') curPos++;
2329 /* Dump out the parsed output */
2330 WCMD_DumpCommands(*output);
2332 return extraSpace;
2335 /***************************************************************************
2336 * WCMD_process_commands
2338 * Process all the commands read in so far
2340 CMD_LIST *WCMD_process_commands(CMD_LIST *thisCmd, BOOL oneBracket,
2341 BOOL retrycall) {
2343 int bdepth = -1;
2345 if (thisCmd && oneBracket) bdepth = thisCmd->bracketDepth;
2347 /* Loop through the commands, processing them one by one */
2348 while (thisCmd) {
2350 CMD_LIST *origCmd = thisCmd;
2352 /* If processing one bracket only, and we find the end bracket
2353 entry (or less), return */
2354 if (oneBracket && !thisCmd->command &&
2355 bdepth <= thisCmd->bracketDepth) {
2356 WINE_TRACE("Finished bracket @ %p, next command is %p\n",
2357 thisCmd, thisCmd->nextcommand);
2358 return thisCmd->nextcommand;
2361 /* Ignore the NULL entries a ')' inserts (Only 'if' cares
2362 about them and it will be handled in there)
2363 Also, skip over any batch labels (eg. :fred) */
2364 if (thisCmd->command && thisCmd->command[0] != ':') {
2365 WINE_TRACE("Executing command: '%s'\n", wine_dbgstr_w(thisCmd->command));
2366 WCMD_execute (thisCmd->command, thisCmd->redirects, &thisCmd, retrycall);
2369 /* Step on unless the command itself already stepped on */
2370 if (thisCmd == origCmd) thisCmd = thisCmd->nextcommand;
2372 return NULL;
2375 /***************************************************************************
2376 * WCMD_free_commands
2378 * Frees the storage held for a parsed command line
2379 * - This is not done in the process_commands, as eventually the current
2380 * pointer will be modified within the commands, and hence a single free
2381 * routine is simpler
2383 void WCMD_free_commands(CMD_LIST *cmds) {
2385 /* Loop through the commands, freeing them one by one */
2386 while (cmds) {
2387 CMD_LIST *thisCmd = cmds;
2388 cmds = cmds->nextcommand;
2389 heap_free(thisCmd->command);
2390 heap_free(thisCmd->redirects);
2391 heap_free(thisCmd);
2396 /*****************************************************************************
2397 * Main entry point. This is a console application so we have a main() not a
2398 * winmain().
2401 int wmain (int argc, WCHAR *argvW[])
2403 int args;
2404 WCHAR *cmdLine = NULL;
2405 WCHAR *cmd = NULL;
2406 WCHAR *argPos = NULL;
2407 WCHAR string[1024];
2408 WCHAR envvar[4];
2409 BOOL promptNewLine = TRUE;
2410 BOOL opt_q;
2411 int opt_t = 0;
2412 static const WCHAR offW[] = {'O','F','F','\0'};
2413 static const WCHAR promptW[] = {'P','R','O','M','P','T','\0'};
2414 static const WCHAR defaultpromptW[] = {'$','P','$','G','\0'};
2415 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2416 static const WCHAR cmdW[] = {'\\','c','m','d','.','e','x','e',0};
2417 WCHAR comspec[MAX_PATH];
2418 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
2419 OSVERSIONINFOW osv;
2420 char osver[50];
2422 if (!GetEnvironmentVariableW(comspecW, comspec, ARRAY_SIZE(comspec)))
2424 GetSystemDirectoryW(comspec, ARRAY_SIZE(comspec) - ARRAY_SIZE(cmdW));
2425 strcatW(comspec, cmdW);
2426 SetEnvironmentVariableW(comspecW, comspec);
2429 srand(time(NULL));
2431 /* Get the windows version being emulated */
2432 osv.dwOSVersionInfoSize = sizeof(osv);
2433 GetVersionExW(&osv);
2435 /* Pre initialize some messages */
2436 strcpyW(anykey, WCMD_LoadMessage(WCMD_ANYKEY));
2437 sprintf(osver, "%d.%d.%d (%s)", osv.dwMajorVersion, osv.dwMinorVersion,
2438 osv.dwBuildNumber, PACKAGE_VERSION);
2439 cmd = WCMD_format_string(WCMD_LoadMessage(WCMD_VERSION), osver);
2440 strcpyW(version_string, cmd);
2441 LocalFree(cmd);
2442 cmd = NULL;
2444 /* Can't use argc/argv as it will have stripped quotes from parameters
2445 * meaning cmd.exe /C echo "quoted string" is impossible
2447 cmdLine = GetCommandLineW();
2448 WINE_TRACE("Full commandline '%s'\n", wine_dbgstr_w(cmdLine));
2449 args = 0;
2451 opt_c = opt_k = opt_q = opt_s = FALSE;
2452 WCMD_parameter(cmdLine, args, &argPos, TRUE, TRUE);
2453 while (argPos && argPos[0] != 0x00)
2455 WCHAR c;
2456 WINE_TRACE("Command line parm: '%s'\n", wine_dbgstr_w(argPos));
2457 if (argPos[0]!='/' || argPos[1]=='\0') {
2458 args++;
2459 WCMD_parameter(cmdLine, args, &argPos, TRUE, TRUE);
2460 continue;
2463 c=argPos[1];
2464 if (tolowerW(c)=='c') {
2465 opt_c = TRUE;
2466 } else if (tolowerW(c)=='q') {
2467 opt_q = TRUE;
2468 } else if (tolowerW(c)=='k') {
2469 opt_k = TRUE;
2470 } else if (tolowerW(c)=='s') {
2471 opt_s = TRUE;
2472 } else if (tolowerW(c)=='a') {
2473 unicodeOutput = FALSE;
2474 } else if (tolowerW(c)=='u') {
2475 unicodeOutput = TRUE;
2476 } else if (tolowerW(c)=='v' && argPos[2]==':') {
2477 delayedsubst = strncmpiW(&argPos[3], offW, 3);
2478 if (delayedsubst) WINE_TRACE("Delayed substitution is on\n");
2479 } else if (tolowerW(c)=='t' && argPos[2]==':') {
2480 opt_t=strtoulW(&argPos[3], NULL, 16);
2481 } else if (tolowerW(c)=='x' || tolowerW(c)=='y') {
2482 /* Ignored for compatibility with Windows */
2485 if (argPos[2]==0 || argPos[2]==' ' || argPos[2]=='\t' ||
2486 tolowerW(c)=='v') {
2487 args++;
2488 WCMD_parameter(cmdLine, args, &argPos, TRUE, TRUE);
2490 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
2492 /* Do not step to next parameter, instead carry on parsing this one */
2493 argPos+=2;
2496 if (opt_c || opt_k) /* break out of parsing immediately after c or k */
2497 break;
2500 if (opt_q) {
2501 WCMD_echo(offW);
2504 /* Until we start to read from the keyboard, stay as non-interactive */
2505 interactive = FALSE;
2507 SetEnvironmentVariableW(promptW, defaultpromptW);
2509 if (opt_c || opt_k) {
2510 int len;
2511 WCHAR *q1 = NULL,*q2 = NULL,*p;
2513 /* Handle very edge case error scenario, "cmd.exe /c" ie when there are no
2514 * parameters after the /C or /K by pretending there was a single space */
2515 if (argPos == NULL) argPos = (WCHAR *)spaceW;
2517 /* Take a copy */
2518 cmd = heap_strdupW(argPos);
2520 /* opt_s left unflagged if the command starts with and contains exactly
2521 * one quoted string (exactly two quote characters). The quoted string
2522 * must be an executable name that has whitespace and must not have the
2523 * following characters: &<>()@^| */
2525 if (!opt_s) {
2526 /* 1. Confirm there is at least one quote */
2527 q1 = strchrW(argPos, '"');
2528 if (!q1) opt_s=1;
2531 if (!opt_s) {
2532 /* 2. Confirm there is a second quote */
2533 q2 = strchrW(q1+1, '"');
2534 if (!q2) opt_s=1;
2537 if (!opt_s) {
2538 /* 3. Ensure there are no more quotes */
2539 if (strchrW(q2+1, '"')) opt_s=1;
2542 /* check first parameter for a space and invalid characters. There must not be any
2543 * invalid characters, but there must be one or more whitespace */
2544 if (!opt_s) {
2545 opt_s = TRUE;
2546 p=q1;
2547 while (p!=q2) {
2548 if (*p=='&' || *p=='<' || *p=='>' || *p=='(' || *p==')'
2549 || *p=='@' || *p=='^' || *p=='|') {
2550 opt_s = TRUE;
2551 break;
2553 if (*p==' ' || *p=='\t')
2554 opt_s = FALSE;
2555 p++;
2559 WINE_TRACE("/c command line: '%s'\n", wine_dbgstr_w(cmd));
2561 /* Finally, we only stay in new mode IF the first parameter is quoted and
2562 is a valid executable, i.e. must exist, otherwise drop back to old mode */
2563 if (!opt_s) {
2564 WCHAR *thisArg = WCMD_parameter(cmd, 0, NULL, FALSE, TRUE);
2565 WCHAR pathext[MAXSTRING];
2566 BOOL found = FALSE;
2568 /* Now extract PATHEXT */
2569 len = GetEnvironmentVariableW(envPathExt, pathext, ARRAY_SIZE(pathext));
2570 if ((len == 0) || (len >= ARRAY_SIZE(pathext))) {
2571 strcpyW (pathext, dfltPathExt);
2574 /* If the supplied parameter has any directory information, look there */
2575 WINE_TRACE("First parameter is '%s'\n", wine_dbgstr_w(thisArg));
2576 if (strchrW(thisArg, '\\') != NULL) {
2578 GetFullPathNameW(thisArg, ARRAY_SIZE(string), string, NULL);
2579 WINE_TRACE("Full path name '%s'\n", wine_dbgstr_w(string));
2580 p = string + strlenW(string);
2582 /* Does file exist with this name? */
2583 if (GetFileAttributesW(string) != INVALID_FILE_ATTRIBUTES) {
2584 WINE_TRACE("Found file as '%s'\n", wine_dbgstr_w(string));
2585 found = TRUE;
2586 } else {
2587 WCHAR *thisExt = pathext;
2589 /* No - try with each of the PATHEXT extensions */
2590 while (!found && thisExt) {
2591 WCHAR *nextExt = strchrW(thisExt, ';');
2593 if (nextExt) {
2594 memcpy(p, thisExt, (nextExt-thisExt) * sizeof(WCHAR));
2595 p[(nextExt-thisExt)] = 0x00;
2596 thisExt = nextExt+1;
2597 } else {
2598 strcpyW(p, thisExt);
2599 thisExt = NULL;
2602 /* Does file exist with this extension appended? */
2603 if (GetFileAttributesW(string) != INVALID_FILE_ATTRIBUTES) {
2604 WINE_TRACE("Found file as '%s'\n", wine_dbgstr_w(string));
2605 found = TRUE;
2610 /* Otherwise we now need to look in the path to see if we can find it */
2611 } else {
2612 /* Does file exist with this name? */
2613 if (SearchPathW(NULL, thisArg, NULL, ARRAY_SIZE(string), string, NULL) != 0) {
2614 WINE_TRACE("Found on path as '%s'\n", wine_dbgstr_w(string));
2615 found = TRUE;
2616 } else {
2617 WCHAR *thisExt = pathext;
2619 /* No - try with each of the PATHEXT extensions */
2620 while (!found && thisExt) {
2621 WCHAR *nextExt = strchrW(thisExt, ';');
2623 if (nextExt) {
2624 *nextExt = 0;
2625 nextExt = nextExt+1;
2626 } else {
2627 nextExt = NULL;
2630 /* Does file exist with this extension? */
2631 if (SearchPathW(NULL, thisArg, thisExt, ARRAY_SIZE(string), string, NULL) != 0) {
2632 WINE_TRACE("Found on path as '%s' with extension '%s'\n", wine_dbgstr_w(string),
2633 wine_dbgstr_w(thisExt));
2634 found = TRUE;
2636 thisExt = nextExt;
2641 /* If not found, drop back to old behaviour */
2642 if (!found) {
2643 WINE_TRACE("Binary not found, dropping back to old behaviour\n");
2644 opt_s = TRUE;
2649 /* strip first and last quote characters if opt_s; check for invalid
2650 * executable is done later */
2651 if (opt_s && *cmd=='\"')
2652 WCMD_strip_quotes(cmd);
2655 /* Save cwd into appropriate env var (Must be before the /c processing */
2656 GetCurrentDirectoryW(ARRAY_SIZE(string), string);
2657 if (IsCharAlphaW(string[0]) && string[1] == ':') {
2658 static const WCHAR fmt[] = {'=','%','c',':','\0'};
2659 wsprintfW(envvar, fmt, string[0]);
2660 SetEnvironmentVariableW(envvar, string);
2661 WINE_TRACE("Set %s to %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(string));
2664 if (opt_c) {
2665 /* If we do a "cmd /c command", we don't want to allocate a new
2666 * console since the command returns immediately. Rather, we use
2667 * the currently allocated input and output handles. This allows
2668 * us to pipe to and read from the command interpreter.
2671 /* Parse the command string, without reading any more input */
2672 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2673 WCMD_process_commands(toExecute, FALSE, FALSE);
2674 WCMD_free_commands(toExecute);
2675 toExecute = NULL;
2677 heap_free(cmd);
2678 return errorlevel;
2681 SetConsoleTitleW(WCMD_LoadMessage(WCMD_CONSTITLE));
2683 /* Note: cmd.exe /c dir does not get a new color, /k dir does */
2684 if (opt_t) {
2685 if (!(((opt_t & 0xF0) >> 4) == (opt_t & 0x0F))) {
2686 defaultColor = opt_t & 0xFF;
2687 param1[0] = 0x00;
2688 WCMD_color();
2690 } else {
2691 /* Check HKCU\Software\Microsoft\Command Processor
2692 Then HKLM\Software\Microsoft\Command Processor
2693 for defaultcolour value
2694 Note Can be supplied as DWORD or REG_SZ
2695 Note2 When supplied as REG_SZ it's in decimal!!! */
2696 HKEY key;
2697 DWORD type;
2698 DWORD value=0, size=4;
2699 static const WCHAR regKeyW[] = {'S','o','f','t','w','a','r','e','\\',
2700 'M','i','c','r','o','s','o','f','t','\\',
2701 'C','o','m','m','a','n','d',' ','P','r','o','c','e','s','s','o','r','\0'};
2702 static const WCHAR dfltColorW[] = {'D','e','f','a','u','l','t','C','o','l','o','r','\0'};
2704 if (RegOpenKeyExW(HKEY_CURRENT_USER, regKeyW,
2705 0, KEY_READ, &key) == ERROR_SUCCESS) {
2706 WCHAR strvalue[4];
2708 /* See if DWORD or REG_SZ */
2709 if (RegQueryValueExW(key, dfltColorW, NULL, &type,
2710 NULL, NULL) == ERROR_SUCCESS) {
2711 if (type == REG_DWORD) {
2712 size = sizeof(DWORD);
2713 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2714 (LPBYTE)&value, &size);
2715 } else if (type == REG_SZ) {
2716 size = ARRAY_SIZE(strvalue);
2717 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2718 (LPBYTE)strvalue, &size);
2719 value = strtoulW(strvalue, NULL, 10);
2722 RegCloseKey(key);
2725 if (value == 0 && RegOpenKeyExW(HKEY_LOCAL_MACHINE, regKeyW,
2726 0, KEY_READ, &key) == ERROR_SUCCESS) {
2727 WCHAR strvalue[4];
2729 /* See if DWORD or REG_SZ */
2730 if (RegQueryValueExW(key, dfltColorW, NULL, &type,
2731 NULL, NULL) == ERROR_SUCCESS) {
2732 if (type == REG_DWORD) {
2733 size = sizeof(DWORD);
2734 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2735 (LPBYTE)&value, &size);
2736 } else if (type == REG_SZ) {
2737 size = ARRAY_SIZE(strvalue);
2738 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2739 (LPBYTE)strvalue, &size);
2740 value = strtoulW(strvalue, NULL, 10);
2743 RegCloseKey(key);
2746 /* If one found, set the screen to that colour */
2747 if (!(((value & 0xF0) >> 4) == (value & 0x0F))) {
2748 defaultColor = value & 0xFF;
2749 param1[0] = 0x00;
2750 WCMD_color();
2755 if (opt_k) {
2756 /* Parse the command string, without reading any more input */
2757 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2758 WCMD_process_commands(toExecute, FALSE, FALSE);
2759 WCMD_free_commands(toExecute);
2760 toExecute = NULL;
2761 heap_free(cmd);
2765 * Loop forever getting commands and executing them.
2768 interactive = TRUE;
2769 if (!opt_k) WCMD_version ();
2770 while (TRUE) {
2772 /* Read until EOF (which for std input is never, but if redirect
2773 in place, may occur */
2774 if (echo_mode) WCMD_show_prompt(promptNewLine);
2775 if (!WCMD_ReadAndParseLine(NULL, &toExecute, GetStdHandle(STD_INPUT_HANDLE)))
2776 break;
2777 WCMD_process_commands(toExecute, FALSE, FALSE);
2778 WCMD_free_commands(toExecute);
2779 promptNewLine = !!toExecute;
2780 toExecute = NULL;
2782 return 0;